def main(): # How many fruits collected, displayed on game over score = 0 # The snake (: snake = Snake(spawn_coord=snake_spawn_coord, spawn_length=snake_spawn_length, spawn_dir=snake_spawn_direction) # Generate the first fruit fruit = Fruit(avoid_snake=snake) # The gameboard checker_board = CheckerBoard(b_width=width, b_height=height, b_tilesize=tilesize) # ###### Main game loop ###### # while True: for ev in pg.event.get(): # ev : event if ev.type == QUIT: pg.quit() kill_everything() elif ev.type == KEYDOWN: k = ev.key # Could use a for loop, but this is more readable if k == K_UP or k == k_up_a: snake.change_direction(NORTH) elif k == K_RIGHT or k == k_right_a: snake.change_direction(EAST) elif k == K_DOWN or k == k_down_a: snake.change_direction(SOUTH) elif k == K_LEFT or k == k_left_a: snake.change_direction(WEST) # Limit user to one keypress per frame, this has the drawback that pressing two keys in succession fast # enough will only register the first key if both are pressed during the same frame, without the break # a user can change direction twice in a frame, allowing the snake to make a 180turn in one frame. break # Draw objects checker_board.draw() fruit.draw() snake.update() # move + draw # I placed this outside of the Snake class, as it seemed to make more sense for it to be in the game loop collided = snake.check_collision(fruit) if collided: game_over(score) # This code is only run if player continues, it overwrites the old snake with a new snake: snake = Snake(spawn_coord=snake_spawn_coord, spawn_length=snake_spawn_length, spawn_dir=snake_spawn_direction) score = 0 elif collided == False: # Ignore the pep-8 violation, collided can also return None, and None == not True # a new fruit fruit = Fruit(snake) score += 1 # Update the display pg.display.flip() clock.tick(target_fps)
def game_over(score): cont = False # Whether or not the player wants to play again s = pg.Surface( (width * tilesize, height * tilesize)) # Black background with an alpha making it translucent s.fill(black) s.set_alpha(100) board.blit(s, (0, 0)) big_font = pg.font.SysFont("Arial", 40, bold=True) font = pg.font.SysFont("Arial", 24) game_over_text = big_font.render("Game Over!", True, black) # Antialias=True, color=black score_string = "Your score: " + str(score) score_text = font.render(score_string, True, black) continue_text = font.render("Press SPACE to try again or ESCAPE to quit.", True, black) board.blit(game_over_text, (20, height // 2 * tilesize - 45)) board.blit(score_text, (20, height // 2 * tilesize)) board.blit(continue_text, (20, height // 2 * tilesize + 26)) # Nested game loop while True: # Check for use input for ev in pg.event.get(): # ev : event if ev.type == QUIT: pg.quit() kill_everything() elif ev.type == KEYDOWN: k = ev.key if k == K_ESCAPE: pg.quit() kill_everything() elif k == K_SPACE: cont = True break break if cont: break # Update the display, this might aswell be high to give a more responsive feel clock.tick(60) pg.display.flip()