summaryrefslogtreecommitdiff
path: root/snake/snake.py
diff options
context:
space:
mode:
Diffstat (limited to 'snake/snake.py')
-rwxr-xr-xsnake/snake.py40
1 files changed, 32 insertions, 8 deletions
diff --git a/snake/snake.py b/snake/snake.py
index 14b0ea0..e28ef61 100755
--- a/snake/snake.py
+++ b/snake/snake.py
@@ -11,6 +11,7 @@ class Snake:
self.fps=fps
self.snake=[(0,0)]*length
self.direction=3 # Like clock (12=up, 3=right, 6=bottom, 9=left)
+ self.new_apple()
pygame.init()
self.screen=pygame.display.set_mode((grid_width*grid_pts,grid_height*grid_pts))
@@ -20,9 +21,9 @@ class Snake:
def new_apple(self):
- self.apple=(random.randint(0,grid_width),random.randint(0,grid_height))
+ self.apple=(random.randint(0,self.grid_width),random.randint(0,self.grid_height))
while self.apple in self.snake:
- self.apple=(random.randint(0,grid_width),random.randint(0,grid_height))
+ self.apple=(random.randint(0,self.grid_width),random.randint(0,self.grid_height))
def move(self):
# Update tail
@@ -47,10 +48,28 @@ class Snake:
for elt in self.snake:
self.draw_pts(elt[0],elt[1])
+ def has_loose(self):
+ if self.snake.count(self.snake[0])>1:
+ return(True)
+ h=self.snake[0]
+ if h[0]<0 or h[1]<0 or h[0] >= self.grid_width or h[1] >= self.grid_height:
+ return(True)
+ return(False)
+
def run(self):
clock = pygame.time.Clock()
self.direction=6
+ ignore_has_loose=True
while True:
+ self.screen.fill((0,0,0))
+ self.draw_snake()
+ self.draw_pts(self.apple[0],self.apple[1],color=(255,0,0))
+ # Check for loose
+ if not(ignore_has_loose) and self.has_loose():
+ break
+ else:
+ ignore_has_loose=False
+ # Check inputs
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
@@ -58,16 +77,21 @@ class Snake:
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and self.direction != 3:
self.direction=9
- if event.key == pygame.K_RIGHT and self.direction != 9:
+ break
+ elif event.key == pygame.K_RIGHT and self.direction != 9:
self.direction=3
- if event.key == pygame.K_UP and self.direction != 6:
+ break
+ elif event.key == pygame.K_UP and self.direction != 6:
self.direction=12
- if event.key == pygame.K_DOWN and self.direction != 12:
+ break
+ elif event.key == pygame.K_DOWN and self.direction != 12:
self.direction=6
-
- self.screen.fill((0,0,0))
- self.draw_snake()
+ break
self.move()
+ # Check for eating apple
+ if self.apple==self.snake[0]:
+ self.snake.append(self.snake[len(self.snake)-1])
+ self.new_apple()
pygame.display.flip()
clock.tick(self.fps)