Skip to content

Instantly share code, notes, and snippets.

@Zwork101
Created June 27, 2017 23:09
Show Gist options
  • Save Zwork101/ef75613ade80d55f15f60bce6045c9f7 to your computer and use it in GitHub Desktop.
Save Zwork101/ef75613ade80d55f15f60bce6045c9f7 to your computer and use it in GitHub Desktop.
The snake game using processing :P
SCREEN_SIZE = 600
pla = None
FPS = 12
def round20(x, base=20):
return int(base * round(float(x)/base))
APPLE_POS = [round20(random(SCREEN_SIZE)), round20(random(SCREEN_SIZE))]
class Snake:
def __init__(self, headx, heady, sLength, cMotion):
self.headx = headx
self.heady = heady
self.sLength = sLength
self.bodies = []
self.cMotion = cMotion
def update(self):
global APPLE_POS, FPS
pHead = (self.headx, self.heady)
if self.cMotion == 'LEFT':
self.headx += 20
elif self.cMotion == 'UP':
self.heady -= 20
elif self.cMotion == 'DOWN':
self.heady += 20
elif self.cMotion == 'RIGHT':
self.headx -= 20
if self.headx == APPLE_POS[0] and self.heady == APPLE_POS[1]:
self.sLength += 1
FPS += 1
APPLE_POS = [round20(random(SCREEN_SIZE)), round20(random(SCREEN_SIZE))]
self.bodies.append(pHead)
while len(self.bodies) > self.sLength:
self.bodies.pop(0)
for b in self.bodies:
if b[0] == self.headx and b[1] == self.heady:
print('OW!')
exit()
def show(self):
fill(0,255,0)
noStroke()
rect(self.headx, self.heady, 20, 20)
for b in self.bodies:
rect(b[0], b[1], 20, 20)
def setup():
global pla
size(SCREEN_SIZE, SCREEN_SIZE)
pla = Snake(width/2, height/2, 0, 'LEFT')
def draw():
global pla, FPS
frameRate(FPS)
background(255)
if keyPressed:
if pla.cMotion == 'DOWN':
if key == 'd':
pla.cMotion = 'LEFT'
if key == 'a':
pla.cMotion = 'RIGHT'
if pla.cMotion == 'UP':
if key == 'd':
pla.cMotion = 'LEFT'
if key == 'a':
pla.cMotion = 'RIGHT'
if pla.cMotion == 'LEFT':
if key == 'w':
pla.cMotion = 'UP'
if key == 's':
pla.cMotion = 'DOWN'
if pla.cMotion == 'RIGHT':
if key == 'w':
pla.cMotion = 'UP'
if key == 's':
pla.cMotion = 'DOWN'
if pla.headx >= width or pla.headx <= 0 or pla.heady >= height or pla.heady <= 0:
print('OW!')
exit()
fill(255,0,0)
noStroke()
rect(APPLE_POS[0], APPLE_POS[1], 20, 20)
pla.update()
pla.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment