Creating an advanced AI for the classic Snake game involves developing both the game environment and an intelligent agent capable of navigating the snake effectively to maximize its length without colliding with walls or itself. In this implementation, we'll use Python along with the pygame library for rendering the game and implementing the AI using the A* pathfinding algorithm for efficient navigation.
Overview
Game Environment: Using pygame, we'll create a Snake game where the snake moves on a grid, eats food to grow, and must avoid collisions.
AI Agent: Implement the A* pathfinding algorithm to determine the shortest path to the food while avoiding obstacles (walls and the snake's own body).
Prerequisites
Python 3.x: Make sure you have Python installed. You can download it from python.org.
pygame: Install via pip if you don't have it.
bash
pip install pygame
Implementation
Below is the complete Python code for the advanced Snake AI.
python
import pygame
import sys
import random
from collections import deque
import heapq
# Initialize pygame
pygame.init()
# Game Constants
CELL_SIZE = 20
WIDTH = 20 # Number of cells horizontally
HEIGHT = 20 # Number of cells vertically
SCREEN_WIDTH = CELL_SIZE * WIDTH
SCREEN_HEIGHT = CELL_SIZE * HEIGHT
FPS = 10
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (200, 0, 0)
GREEN = (0, 200, 0)
BLUE = (0, 0, 200)
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()
class Snake:
def __init__(self):
self.body = deque([(WIDTH // 2, HEIGHT // 2)])
self.direction = RIGHT
self.grow = False
def move(self, next_position):
if self.grow:
self.body.appendleft(next_position)
self.grow = False
else:
self.body.appendleft(next_position)
self.body.pop()
def set_direction(self, direction):
# Prevent snake from reversing
opposite = (-self.direction[0], -self.direction[1])
if direction != opposite:
self.direction = direction
def get_head(self):
return self.body[0]
def collision(self, point=None):
if point is None:
point = self.get_head()
return (point in list(self.body)[1:])
def grow_snake(self):
self.grow = True
class Food:
def __init__(self, snake):
self.position = self.random_position(snake)
def random_position(self, snake):
while True:
pos = (random.randint(0, WIDTH -1), random.randint(0, HEIGHT -1))
if pos not in snake.body:
return pos
def respawn(self, snake):
self.position = self.random_position(snake)
def heuristic(a, b):
# Manhattan distance
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def get_neighbors(node):
dirs = [UP, DOWN, LEFT, RIGHT]
neighbors = []
for d in dirs:
neighbor = (node[0] + d[0], node[1] + d[1])
if 0 <= neighbor[0] < WIDTH and 0 <= neighbor[1] < HEIGHT:
neighbors.append(neighbor)
return neighbors
def a_star(start, goal, snake):
open_set = []
heapq.heappush(open_set, (0 + heuristic(start, goal), 0, start, None))
came_from = {}
g_score = {start: 0}
closed_set = set()
snake_body = set(snake.body)
while open_set:
_, current_cost, current, parent = heapq.heappop(open_set)
if current in closed_set:
continue
came_from[current] = parent
if current == goal:
# Reconstruct path
path = []
while current != start:
path.append(current)
current = came_from[current]
path.reverse()
return path
closed_set.add(current)
for neighbor in get_neighbors(current):
if neighbor in snake_body and neighbor != goal:
continue
tentative_g = current_cost + 1
if neighbor in g_score and tentative_g >= g_score[neighbor]:
continue
g_score[neighbor] = tentative_g
f_score = tentative_g + heuristic(neighbor, goal)
heapq.heappush(open_set, (f_score, tentative_g, neighbor, current))
return None # No path found
def find_path(snake, food):
path = a_star(snake.get_head(), food.position, snake)
return path
def draw_grid():
for x in range(0, SCREEN_WIDTH, CELL_SIZE):
pygame.draw.line(screen, GREY, (x, 0), (x, SCREEN_HEIGHT))
for y in range(0, SCREEN_HEIGHT, CELL_SIZE):
pygame.draw.line(screen, GREY, (0, y), (SCREEN_WIDTH, y))
def main():
snake = Snake()
food = Food(snake)
score = 0
while True:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# AI Decision: Find path to food
path = find_path(snake, food)
if path and len(path) > 0:
next_move = path[0]
direction = (next_move[0] - snake.get_head()[0], next_move[1] - snake.get_head()[1])
snake.set_direction(direction)
else:
# If no path found, try to move safely
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] < WIDTH and 0 <= new_head[1] < HEIGHT and
new_head not in snake.body):
snake.set_direction(direction)
break # Move in the first safe direction
# Calculate next position
new_head = (snake.get_head()[0] + snake.direction[0],
snake.get_head()[1] + snake.direction[1])
# Check collisions
if (not (0 <= new_head[0] < WIDTH and 0 <= new_head[1] < HEIGHT)) or snake.collision(new_head):
print("Game Over! Score:", score)
pygame.quit()
sys.exit()
# Move snake
snake.move(new_head)
# Check if food eaten
if new_head == food.position:
snake.grow_snake()
score += 1
food.respawn(snake)
# Draw everything
screen.fill(BLACK)
draw_grid()
# Draw food
pygame.draw.rect(screen, RED, pygame.Rect(food.position[0]*CELL_SIZE,
food.position[1]*CELL_SIZE,
CELL_SIZE, CELL_SIZE))
# Draw snake
for idx, pos in enumerate(snake.body):
color = GREEN if idx == 0 else BLUE
pygame.draw.rect(screen, color, pygame.Rect(pos[0]*CELL_SIZE,
pos[1]*CELL_SIZE,
CELL_SIZE, CELL_SIZE))
# Display score
font = pygame.font.SysFont('Arial', 20)
score_surf = font.render(f'Score: {score}', True, WHITE)
screen.blit(score_surf, (5,5))
pygame.display.flip()
if __name__ == "__main__":
main()
Explanation
Components
Snake Class:
Manages the snake's position, movement, direction, and growth.
move(new_head): Moves the snake by adding a new head and optionally removing the tail if not growing.
set_direction(direction): Updates the direction while preventing the snake from reversing.
collision(point): Checks if the snake collides with itself.
Food Class:
Manages the food's position on the grid.
Ensures food spawns in locations not occupied by the snake.
*A Pathfinding (a_star function)**:
Implements the A* algorithm to find the shortest path from the snake's head to the food.
Utilizes Manhattan distance as the heuristic.
Considers the snake's current body as obstacles, except for the food's position.
AI Decision Making (find_path and main loop):
The AI continuously computes the path to the food using A*.
If a path exists, it follows the first move in the path.
If no path is found (e.g., the snake is trapped), it attempts to make a safe move to survive as long as possible.
Rendering (pygame):
The grid, snake, and food are rendered using pygame.
The score is displayed on the screen.
Enhancements and Considerations
Pathfinding Efficiency: The A* algorithm is efficient for grid-based pathfinding, ensuring that the AI makes optimal moves towards the food.
Safety Moves: If the AI cannot find a path to the food, it doesn't panic; instead, it looks for any safe move to keep the snake alive longer.
Scalability: The grid size can be adjusted by modifying the WIDTH, HEIGHT, and CELL_SIZE constants.
Running the Game
Ensure Dependencies Are Installed:
Install pygame if you haven't:
bash
pip install pygame
Save the Script:
Save the provided Python code in a file, e.g., snake_ai.py.
Run the Script:
Execute the script using Python:
bash
python snake_ai.py
Game Behavior:
The AI-controlled snake will automatically navigate towards the food.
The game will print "Game Over!" and the final score in the console when the snake collides with a wall or itself.
Possible Improvements
While the above AI provides a foundational level of intelligence for the snake, there are several ways to enhance its capabilities:
Hamiltonian Cycle: Implement a Hamiltonian cycle approach to ensure the snake can traverse the grid without getting trapped.
Reinforcement Learning: Train a neural network using reinforcement learning techniques (e.g., Deep Q-Learning) for the snake to learn optimal strategies over time.
Dynamic Difficulty: Adjust the AI's speed or decision-making complexity based on the current score or snake length.
Visualization Enhancements: Improve the graphical representation with smoother animations or additional visual cues.
Multiple Food Items: Introduce multiple food items to increase complexity.
Conclusion
This implementation provides a solid foundation for an advanced Snake AI using Python and pygame. The A* pathfinding algorithm ensures efficient navigation towards food while avoiding self-collisions and walls. By building upon this base, you can introduce more sophisticated AI behaviors and game features to create a more challenging and engaging Snake game.