def run_game(): pygame.init() pygame.font.init() w = s.screen_width * s.cell_size + 1 h = s.screen_height * s.cell_size + 1 screen = pygame.display.set_mode((w, h)) pygame.display.set_caption("Snake") myfont = pygame.font.SysFont('Arial', 40) clock = pygame.time.Clock() snake = Snake() apple = Apple(snake) snake.apple = apple ai = AI() while (True): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: snake.direction = (-1, 0) elif event.key == pygame.K_RIGHT: snake.direction = (1, 0) elif event.key == pygame.K_UP: snake.direction = (0, -1) elif event.key == pygame.K_DOWN: snake.direction = (0, 1) elif event.key == pygame.K_ESCAPE: sys.exit() elif event.key == pygame.K_SPACE: pause() if not snake.dead: ai.pass_through(snake.body[:], apple.position[:]) snake.direction = ai.output() snake.move() screen.fill(s.bg_color) screen = draw_board(screen, snake, apple, ai.path, myfont) pygame.display.flip() if (snake.dead): print("Snake lost, size: ", len(snake)) apple.randomize() snake = Snake() apple.snake = snake snake.apple = apple ai = AI() elif len(snake.body) == s.screen_width * s.screen_height: print("Snake won! Size: ", len(snake)) return fps = s.FPS if ai.mode == "Tail": fps *= 2 clock.tick(fps)
def loop(self): #TIME clock = pygame.time.Clock() #INSTANCE board = Board(self.display) apple = Apple(self.display) snake = Snake(self.display) #ACTUAL GAMELOOP while True: path = astar(board.returnBoard(), snake.snake_pos(), apple.apple_Position()) print(path) for i in range(1, len(path)): #if next move is not orthogonal if snake.changeDirectionTo(snake.CoordinateToDirection( path[i])): path = astar(board.returnBoard(), snake.snake_pos(), apple.apple_Position()) for event in pygame.event.get(): if event.type == pygame.QUIT: print("exit pressed!") return 0 # DRAW BACKGROUND if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: snake.changeDirectionTo('UP') elif event.key == pygame.K_DOWN: snake.changeDirectionTo('DOWN') elif event.key == pygame.K_LEFT: snake.changeDirectionTo('LEFT') elif event.key == pygame.K_RIGHT: snake.changeDirectionTo('RIGHT') # MOVE SNAKE and record position of SNAKE snake.move() # Collision Detection if snake.collision(): return 0 #eating if snake.ate(apple.apple_Position()): self.score += 1 pygame.display.set_caption(GAME['CAPTION'] + str(self.score)) apple.randomize() #DRAW board.drawBoard(self.display, snake.snake_body(), apple.apple_Position()) apple.draw() snake.draw_body() #DRAW UPDATE pygame.display.update() clock.tick(GAME['FPS'])