Snake Game with Auto-Player using A* Algorithm in Pygame
In this implementation, we will create a Snake game using Pygame, where the snake is controlled by an A* algorithm. The A* algorithm is a pathfinding algorithm that is often used in many fields of science due to its completeness, optimality, and optimal efficiency.
Game Requirements
Python 3.6+
Pygame 2.0.1+
Game Implementation
python
import pygame
import heapq
import random
# Window dimensions
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
# Grid dimensions
GRID_WIDTH = 40
GRID_HEIGHT = 30
# Cell size
CELL_SIZE = WINDOW_WIDTH // GRID_WIDTH
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# Directions
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
class SnakeGame:
def __init__(self):
pygame.init()
self.window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
self.clock = pygame.time.Clock()
self.grid = [[0 for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
self.snake = [(10, 10), (11, 10), (12, 10)]
self.direction = RIGHT
self.apple = self.generate_apple()
self.heuristic = self.manhattan_distance
def generate_apple(self):
while True:
x = random.randint(0, GRID_WIDTH - 1)
y = random.randint(0, GRID_HEIGHT - 1)
if (x, y) not in self.snake:
return (x, y)
def manhattan_distance(self, cell, target):
return abs(cell[0] - target[0]) + abs(cell[1] - target[1])
def euclidean_distance(self, cell, target):
return ((cell[0] - target[0]) ** 2 + (cell[1] - target[1]) ** 2) ** 0.5
def astar(self, start, target):
queue = []
heapq.heappush(queue, (0, start))
came_from = {start: None}
cost_so_far = {start: 0}
while queue:
_, current = heapq.heappop(queue)
if current == target:
break
for dx, dy in [UP, DOWN, LEFT, RIGHT]:
x, y = current[0] + dx, current[1] + dy
if 0 <= x < GRID_WIDTH and 0 <= y < GRID_HEIGHT and (x, y) not in self.snake:
new_cost = cost_so_far[current] + 1
if (x, y) not in cost_so_far or new_cost < cost_so_far[(x, y)]:
cost_so_far[(x, y)] = new_cost
priority = new_cost + self.heuristic((x, y), target)
heapq.heappush(queue, (priority, (x, y)))
came_from[(x, y)] = current
if target not in came_from:
return None
current = target
path = []
while current != start:
path.append(current)
current = came_from[current]
path.append(start)
path.reverse()
return path
def run(self):
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
path = self.astar(self.snake[-1], self.apple)
if path:
self.direction = (path[1][0] - path[0][0], path[1][1] - path[0][1])
head = self.snake[-1][0] + self.direction[0], self.snake[-1][1] + self.direction[1]
if head in self.snake or head[0] < 0 or head[0] >= GRID_WIDTH or head[1] < 0 or head[1] >= GRID_HEIGHT:
running = False
self.snake.append(head)
if self.snake[-1] == self.apple:
self.apple = self.generate_apple()
else:
self.snake.pop(0)
self.window.fill(BLACK)
for x, y in self.snake:
pygame.draw.rect(self.window, GREEN, (x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE))
pygame.draw.rect(self.window, RED, (self.apple[0] * CELL_SIZE, self.apple[1] * CELL_SIZE, CELL_SIZE, CELL_SIZE))
pygame.display.flip()
self.clock.tick(10)
pygame.quit()
if __name__ == "__main__":
game = SnakeGame()
game.run()
How to Run the Game
Install the required packages by running pip install pygame in your terminal.
Run the game by executing python snake_game.py in your terminal.
Gameplay
The game will start with a snake at the top-left corner of the window.
The snake will automatically move towards the apple using the A* algorithm.
When the snake eats the apple, a new apple will be generated at a random location.
If the snake runs into itself or the boundary of the window, the game will end.
Note that this is a basic implementation of the Snake game with A* algorithm, and you can improve it by adding features like scorekeeping, smoother animations, and more.