Minor changes

This commit is contained in:
Loic Guegan 2022-11-01 09:55:38 +01:00
parent 368bf244a8
commit 39e8dd6e7c

View file

@ -39,7 +39,7 @@ class Snake:
self.screen.blit(text, (self.grid_pts/2,text_center[1])) self.screen.blit(text, (self.grid_pts/2,text_center[1]))
def new_apple(self): def new_apple(self):
self.apple=(random.randint(0,self.grid_width),random.randint(0,self.grid_height)) self.apple=(random.randint(0,self.grid_width-1),random.randint(0,self.grid_height-1))
while self.apple in self.snake: while self.apple in self.snake:
self.apple=(random.randint(0,self.grid_width),random.randint(0,self.grid_height)) self.apple=(random.randint(0,self.grid_width),random.randint(0,self.grid_height))
@ -76,7 +76,8 @@ class Snake:
return(True) return(True)
return(False) return(False)
def run(self):
def run(self, event_handler=None):
clock = pygame.time.Clock() clock = pygame.time.Clock()
ignore_has_loose=True ignore_has_loose=True
self.new_game() self.new_game()
@ -95,7 +96,7 @@ class Snake:
if event.type == pygame.QUIT: if event.type == pygame.QUIT:
pygame.quit() pygame.quit()
sys.exit() sys.exit()
elif event.type == pygame.KEYDOWN: elif event_handler==None and event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and self.direction != 3: if event.key == pygame.K_LEFT and self.direction != 3:
self.direction=9 self.direction=9
break break
@ -108,6 +109,8 @@ class Snake:
elif event.key == pygame.K_DOWN and self.direction != 12: elif event.key == pygame.K_DOWN and self.direction != 12:
self.direction=6 self.direction=6
break break
if event_handler!=None:
event_handler(self)
self.move() self.move()
# Check for eating apple # Check for eating apple
if self.apple==self.snake[0]: if self.apple==self.snake[0]:
@ -119,5 +122,10 @@ class Snake:
game=Snake() game=Snake()
def event_handler(game):
if game.snake[0][0]==10:
game.direction=6
for i in range(0,10): for i in range(0,10):
game.run() game.run()