Creating an advanced Snake AI involves implementing not only the classic Snake game but also an intelligent agent that can navigate the game environment efficiently. In this guide, we'll use Python along with the Pygame library to create a visually appealing game and incorporate an AI that uses the A* (A-Star) pathfinding algorithm to make intelligent decisions.
Overview
Game Setup: We'll use Pygame to create the game window, handle graphics, and manage the game loop.
Snake Representation: The snake will be represented as a list of coordinates on a grid.
Food Generation: Randomly place food on the grid ensuring it doesn't appear on the snake's body.
AI Agent: Implement the A* algorithm for pathfinding to determine the optimal path to the food while avoiding collisions.
Dependencies
Make sure you have Python installed on your system. You'll also need the Pygame library. You can install it using pip:
bash
pip install pygame
Complete Python Code
Below is the complete Python script for the advanced Snake AI game:
python
import pygame
import sys
import random
from collections import deque
# Initialize Pygame
pygame.init()
# Game Constants
GRID_SIZE = 20 # Size of each grid cell
GRID_WIDTH = 30 # Number of cells in width
GRID_HEIGHT = 20 # Number of cells in height
SCREEN_WIDTH = GRID_SIZE * GRID_WIDTH
SCREEN_HEIGHT = GRID_SIZE * GRID_HEIGHT
FPS = 10 # Frames per second
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (200, 0, 0)
GREEN = (0, 200, 0)
BLUE = (0, 0, 255)
GREY = (40, 40, 40)
# Directions
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
# Initialize Screen
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Advanced Snake AI")
clock = pygame.time.Clock()
def draw_grid():
for x in range(0, SCREEN_WIDTH, GRID_SIZE):
pygame.draw.line(screen, GREY, (x, 0), (x, SCREEN_HEIGHT))
for y in range(0, SCREEN_HEIGHT, GRID_SIZE):
pygame.draw.line(screen, GREY, (0, y), (SCREEN_WIDTH, y))
class Snake:
def __init__(self):
self.body = deque()
self.body.append((GRID_WIDTH // 2, GRID_HEIGHT // 2))
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
self.grow = False
def move(self, next_pos):
if not self.grow:
self.body.pop()
else:
self.grow = False
self.body.appendleft(next_pos)
def set_direction(self, direction):
# Prevent the snake from moving in the opposite direction
if (direction[0] * -1, direction[1] * -1) != self.direction:
self.direction = direction
def get_head(self):
return self.body[0]
def collision(self, pos):
return pos in self.body
def get_body_set(self):
return set(self.body)
class Food:
def __init__(self, snake_body):
self.position = self.generate_food(snake_body)
def generate_food(self, snake_body):
positions = set((x, y) for x in range(GRID_WIDTH) for y in range(GRID_HEIGHT))
positions -= set(snake_body)
return random.choice(list(positions))
def respawn(self, snake_body):
self.position = self.generate_food(snake_body)
def heuristic(a, b):
# Use Manhattan distance as heuristic
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def get_neighbors(node, snake_body):
neighbors = []
directions = [UP, DOWN, LEFT, RIGHT]
for direction in directions:
neighbor = (node[0] + direction[0], node[1] + direction[1])
if (0 <= neighbor[0] < GRID_WIDTH) and (0 <= neighbor[1] < GRID_HEIGHT) and (neighbor not in snake_body):
neighbors.append(neighbor)
return neighbors
def a_star(start, goal, snake_body):
open_set = set()
open_set.add(start)
came_from = {}
g_score = {start: 0}
f_score = {start: heuristic(start, goal)}
while open_set:
current = min(open_set, key=lambda o: f_score.get(o, float('inf')))
if current == goal:
# Reconstruct path
path = []
while current in came_from:
path.append(current)
current = came_from[current]
path.reverse()
return path
open_set.remove(current)
for neighbor in get_neighbors(current, snake_body):
tentative_g_score = g_score[current] + 1
if tentative_g_score < g_score.get(neighbor, float('inf')):
came_from[neighbor] = current
g_score[neighbor] = tentative_g_score
f_score[neighbor] = tentative_g_score + heuristic(neighbor, goal)
if neighbor not in open_set:
open_set.add(neighbor)
return None # No path found
def bfs(start, goal, snake_body):
queue = deque()
queue.append(start)
came_from = {}
visited = set()
visited.add(start)
while queue:
current = queue.popleft()
if current == goal:
# Reconstruct path
path = []
while current in came_from:
path.append(current)
current = came_from[current]
path.reverse()
return path
for neighbor in get_neighbors(current, snake_body):
if neighbor not in visited:
visited.add(neighbor)
came_from[neighbor] = current
queue.append(neighbor)
return None
def find_safe_path(snake, food, method='A*'):
path = None
snake_body = list(snake.body)
if method == 'A*':
path = a_star(snake.get_head(), food.position, snake_body)
elif method == 'BFS':
path = bfs(snake.get_head(), food.position, snake_body)
return path
def main():
snake = Snake()
food = Food(snake.body)
path = []
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# AI Decision Making
if not path:
path = find_safe_path(snake, food, method='A*')
if path:
next_cell = path.pop(0)
direction = (next_cell[0] - snake.get_head()[0], next_cell[1] - snake.get_head()[1])
snake.set_direction(direction)
else:
# If no path found, make a safe move (e.g., turn right)
for direction in [UP, DOWN, LEFT, RIGHT]:
new_head = (snake.get_head()[0] + direction[0], snake.get_head()[1] + direction[1])
if (0 <= new_head[0] < GRID_WIDTH and 0 <= new_head[1] < GRID_HEIGHT) and (new_head not in snake.body):
snake.set_direction(direction)
break
# Move Snake
new_head = (snake.get_head()[0] + snake.direction[0], snake.get_head()[1] + snake.direction[1])
# Check collisions
if (not (0 <= new_head[0] < GRID_WIDTH and 0 <= new_head[1] < GRID_HEIGHT)) or snake.collision(new_head):
print("Game Over! Your score:", len(snake.body))
pygame.quit()
sys.exit()
# Check if food is eaten
if new_head == food.position:
snake.grow = True
food.respawn(snake.body)
path = find_safe_path(snake, food, method='A*') # Recalculate path after eating
else:
pass # Continue normally
snake.move(new_head)
# Drawing
screen.fill(BLACK)
draw_grid()
# Draw Food
pygame.draw.rect(screen, RED, (food.position[0]*GRID_SIZE, food.position[1]*GRID_SIZE, GRID_SIZE, GRID_SIZE))
# Draw Snake
for idx, segment in enumerate(snake.body):
color = GREEN if idx == 0 else BLUE
pygame.draw.rect(screen, color, (segment[0]*GRID_SIZE, segment[1]*GRID_SIZE, GRID_SIZE, GRID_SIZE))
pygame.display.flip()
clock.tick(FPS)
if __name__ == "__main__":
main()
Explanation of the Code
1. Importing Libraries and Initializing Pygame
python
import pygame
import sys
import random
from collections import deque
pygame.init()
We import necessary libraries:
pygame: For handling graphics and game loop.
sys: To handle system-specific parameters and functions.
random: To generate random positions for food.
deque from collections: Efficiently manage the snake's body.
2. Defining Game Constants
python
GRID_SIZE = 20 # Size of each grid cell
GRID_WIDTH = 30 # Number of cells in width
GRID_HEIGHT = 20 # Number of cells in height
SCREEN_WIDTH = GRID_SIZE * GRID_WIDTH
SCREEN_HEIGHT = GRID_SIZE * GRID_HEIGHT
FPS = 10 # Frames per second
Set up the grid dimensions, screen size, and frames per second.
3. Setting Colors and Directions
python
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (200, 0, 0)
GREEN = (0, 200, 0)
BLUE = (0, 0, 255)
GREY = (40, 40, 40)
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
Define color codes and possible movement directions.
4. Drawing the Grid
python
def draw_grid():
for x in range(0, SCREEN_WIDTH, GRID_SIZE):
pygame.draw.line(screen, GREY, (x, 0), (x, SCREEN_HEIGHT))
for y in range(0, SCREEN_HEIGHT, GRID_SIZE):
pygame.draw.line(screen, GREY, (0, y), (SCREEN_WIDTH, y))
Function to draw grid lines on the screen for better visualization.
5. Snake Class
python
class Snake:
def __init__(self):
self.body = deque()
self.body.append((GRID_WIDTH // 2, GRID_HEIGHT // 2))
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
self.grow = False
def move(self, next_pos):
if not self.grow:
self.body.pop()
else:
self.grow = False
self.body.appendleft(next_pos)
def set_direction(self, direction):
# Prevent the snake from moving in the opposite direction
if (direction[0] * -1, direction[1] * -1) != self.direction:
self.direction = direction
def get_head(self):
return self.body[0]
def collision(self, pos):
return pos in self.body
def get_body_set(self):
return set(self.body)
Initialization: Starts the snake at the center of the grid with a random initial direction.
Move: Moves the snake by adding a new head position and optionally removing the tail.
Set Direction: Updates the snake's direction, ensuring it doesn't reverse.
Collision Detection: Checks if the snake collides with itself or the walls.
6. Food Class
python
class Food:
def __init__(self, snake_body):
self.position = self.generate_food(snake_body)
def generate_food(self, snake_body):
positions = set((x, y) for x in range(GRID_WIDTH) for y in range(GRID_HEIGHT))
positions -= set(snake_body)
return random.choice(list(positions))
def respawn(self, snake_body):
self.position = self.generate_food(snake_body)
Handles food generation, ensuring it doesn't spawn on the snake's body.
Used in the A* algorithm to estimate the cost from the current node to the goal.
Get Neighbors
python
def get_neighbors(node, snake_body):
neighbors = []
directions = [UP, DOWN, LEFT, RIGHT]
for direction in directions:
neighbor = (node[0] + direction[0], node[1] + direction[1])
if (0 <= neighbor[0] < GRID_WIDTH) and (0 <= neighbor[1] < GRID_HEIGHT) and (neighbor not in snake_body):
neighbors.append(neighbor)
return neighbors
Returns valid neighboring nodes considering the grid boundaries and snake's body.
A Algorithm*
python
def a_star(start, goal, snake_body):
open_set = set()
open_set.add(start)
came_from = {}
g_score = {start: 0}
f_score = {start: heuristic(start, goal)}
while open_set:
current = min(open_set, key=lambda o: f_score.get(o, float('inf')))
if current == goal:
# Reconstruct path
path = []
while current in came_from:
path.append(current)
current = came_from[current]
path.reverse()
return path
open_set.remove(current)
for neighbor in get_neighbors(current, snake_body):
tentative_g_score = g_score[current] + 1
if tentative_g_score < g_score.get(neighbor, float('inf')):
came_from[neighbor] = current
g_score[neighbor] = tentative_g_score
f_score[neighbor] = tentative_g_score + heuristic(neighbor, goal)
if neighbor not in open_set:
open_set.add(neighbor)
return None # No path found
Implements the A* pathfinding algorithm to find the shortest path to the food.
Breadth-First Search (Alternative Method)
python
def bfs(start, goal, snake_body):
queue = deque()
queue.append(start)
came_from = {}
visited = set()
visited.add(start)
while queue:
current = queue.popleft()
if current == goal:
# Reconstruct path
path = []
while current in came_from:
path.append(current)
current = came_from[current]
path.reverse()
return path
for neighbor in get_neighbors(current, snake_body):
if neighbor not in visited:
visited.add(neighbor)
came_from[neighbor] = current
queue.append(neighbor)
return None
An alternative pathfinding method using BFS. You can switch between A* and BFS by changing the method parameter.
Decides which pathfinding algorithm to use and returns the computed path.
9. Main Game Loop
python
def main():
snake = Snake()
food = Food(snake.body)
path = []
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# AI Decision Making
if not path:
path = find_safe_path(snake, food, method='A*')
if path:
next_cell = path.pop(0)
direction = (next_cell[0] - snake.get_head()[0], next_cell[1] - snake.get_head()[1])
snake.set_direction(direction)
else:
# If no path found, make a safe move (e.g., turn right)
for direction in [UP, DOWN, LEFT, RIGHT]:
new_head = (snake.get_head()[0] + direction[0], snake.get_head()[1] + direction[1])
if (0 <= new_head[0] < GRID_WIDTH and 0 <= new_head[1] < GRID_HEIGHT) and (new_head not in snake.body):
snake.set_direction(direction)
break
# Move Snake
new_head = (snake.get_head()[0] + snake.direction[0], snake.get_head()[1] + snake.direction[1])
# Check collisions
if (not (0 <= new_head[0] < GRID_WIDTH and 0 <= new_head[1] < GRID_HEIGHT)) or snake.collision(new_head):
print("Game Over! Your score:", len(snake.body))
pygame.quit()
sys.exit()
# Check if food is eaten
if new_head == food.position:
snake.grow = True
food.respawn(snake.body)
path = find_safe_path(snake, food, method='A*') # Recalculate path after eating
else:
pass # Continue normally
snake.move(new_head)
# Drawing
screen.fill(BLACK)
draw_grid()
# Draw Food
pygame.draw.rect(screen, RED, (food.position[0]*GRID_SIZE, food.position[1]*GRID_SIZE, GRID_SIZE, GRID_SIZE))
# Draw Snake
for idx, segment in enumerate(snake.body):
color = GREEN if idx == 0 else BLUE
pygame.draw.rect(screen, color, (segment[0]*GRID_SIZE, segment[1]*GRID_SIZE, GRID_SIZE, GRID_SIZE))
pygame.display.flip()
clock.tick(FPS)
Event Handling: Listens for quit events to close the game gracefully.
AI Decision Making: Calculates the path to the food using A*. If a path exists, it sets the snake's direction accordingly. If not, it tries to make any safe move to survive.
Movement and Collision: Moves the snake and checks for collisions with walls or itself.
Food Consumption: If the snake eats the food, it grows, and new food is spawned.
Rendering: Draws the grid, food, and snake on the screen.
10. Running the Game
python
if __name__ == "__main__":
main()
Ensures that the game starts when the script is run.
Customization and Enhancements
Pathfinding Method: You can switch between A* and BFS by changing the method parameter in the find_safe_path function call.
python
path = find_safe_path(snake, food, method='BFS') # Use BFS instead of A*
Dynamic Difficulty: Increase or decrease the FPS variable to make the game faster or slower.
Advanced AI: Implement additional strategies such as avoiding cycles or trapping to make the AI more resilient.
Running the Game
Save the provided code in a file, for example, snake_ai.py.
Open a terminal or command prompt in the directory containing the file.
Run the script using Python:
bash
python snake_ai.py
The snake will autonomously navigate toward the food using the A* pathfinding algorithm. The game ends if the snake collides with the walls or itself.
Conclusion
This implementation demonstrates an advanced Snake AI using Python and Pygame. The AI utilizes the A* algorithm to find the optimal path to the food while avoiding obstacles. You can further enhance the AI by incorporating more sophisticated strategies and optimizing the pathfinding process. Happy coding!