BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
Directions
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
class Snake:
def init(self, color, position):
self.color = color
self.body = [position]
self.direction = RIGHT
code
def get_head_position(self):
return self.body[0]
def update(self):
head_x, head_y = self.get_head_position()
new_head = (head_x + self.direction[0], head_y + self.direction[1])
self.body.insert(0, new_head)
self.body.pop()
def grow(self):
self.body.append(self.body[-1]) # Grow the snake by adding a new segment
def change_direction(self, direction):
# Prevent the snake from reversing
if (direction[0] * -1, direction[1] * -1) != self.direction:
self.direction = direction
def draw(self, surface):
for segment in self.body:
pygame.draw.rect(surface, self.color, (segment[0] * CELL_SIZE, segment[1] * CELL_SIZE, CELL_SIZE, CELL_SIZE))
def check_collision(self, position):
# Check if the head collides with the position
return self.get_head_position() == position
def check_self_collision(self):
# Check if the head collides with any part of its body
return self.get_head_position() in self.body[1:]
def check_wall_collision(self):
head_x, head_y = self.get_head_position()
return head_x < 0 or head_x >= (SCREEN_WIDTH // CELL_SIZE) or head_y < 0 or head_y >= (SCREEN_HEIGHT // CELL_SIZE)
class AI_Snake(Snake):
def init(self, color, position):
super().(color, position)
Assistant
init
code
def update(self, food_position):
head_x, head_y = self.get_head_position()
possible_moves = [UP, DOWN, LEFT, RIGHT]
valid_moves = []
# Check for valid moves (not hitting walls)
for move in possible_moves:
new_head = (head_x + move[0], head_y + move[1])
if not self.check_wall_collision_move(new_head) and not self.check_self_collision_move(new_head):
valid_moves.append(move)
if valid_moves:
target_move = self.get_best_move(valid_moves, food_position)
if target_move and random.random() < 0.8: # 80% chance to go towards food
self.change_direction(target_move)
else:
self.change_direction(random.choice(valid_moves))
super().update()
def check_wall_collision_move(self, position):
head_x, head_y = position
return head_x < 0 or head_x >= (SCREEN_WIDTH // CELL_SIZE) or head_y < 0 or head_y >= (SCREEN_HEIGHT // CELL_SIZE)
def check_self_collision_move(self, position):
return position in self.body
def get_best_move(self, valid_moves, food_position):
best_move = None
min_distance = float('inf')
for move in valid_moves:
new_head = (self.get_head_position()[0] + move[0], self.get_head_position()[1] + move[1])
distance = self.calculate_distance(new_head, food_position)
if distance < min_distance:
min_distance = distance
best_move = move
return best_move
def calculate_distance(self, pos1, pos2):
return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1])
def main():
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Snake Game with Improved AI Opponent")
clock = pygame.time.Clock()
code
player_snake = Snake(GREEN, (5, 5))
ai_snake = AI_Snake(WHITE, (10, 10))
food_position = (random.randint(0, (SCREEN_WIDTH // CELL_SIZE) - 1), random.randint(0, (SCREEN_HEIGHT // CELL_SIZE) - 1))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
player_snake.change_direction(UP)
elif event.key == pygame.K_DOWN:
player_snake.change_direction(DOWN)
elif event.key == pygame.K_LEFT:
player_snake.change_direction(LEFT)
elif event.key == pygame.K_RIGHT:
player_snake.change_direction(RIGHT)
player_snake.update()
ai_snake.update(food_position)
# Check for collisions
if player_snake.check_wall_collision() or player_snake.check_self_collision():
print("Game Over! Player collided with the wall or itself.")
pygame.quit()
sys.exit()
if ai_snake.check_wall_collision() or ai_snake.check_self_collision():
print("Game Over! AI collided with the wall or itself.")
pygame.quit()
sys.exit()
# Check for food collision
if player_snake.check_collision(food_position):
player_snake.grow()
food_position = (random.randint(0, (SCREEN_WIDTH // CELL_SIZE) - 1), random.randint(0, (SCREEN_HEIGHT // CELL_SIZE) - 1))
if ai_snake.check_collision(food_position):
ai_snake.grow()
food_position = (random.randint(0, (SCREEN_WIDTH // CELL_SIZE) - 1), random.randint(0, (SCREEN_HEIGHT // CELL_SIZE) - 1))
# Clear the screen
screen.fill(BLACK)
# Draw everything
player_snake.draw(screen)
ai_snake.draw(screen)
draw_food(screen, food_position)
pygame.display.flip()
clock.tick(FPS)
if name == "main":
main()
Massively overhaul.
Certainly! Let's undertake a comprehensive overhaul of your Snake game in Pygame. The revamped version will feature:
Enhanced Code Structure: Improved object-oriented design for better maintainability and scalability.
Advanced AI: A smarter AI that uses the A* pathfinding algorithm to navigate toward the food while avoiding obstacles.
Additional Features:
Score Tracking: Displaying the player's and AI's scores.
Game Over Screen: Informative screen when the game ends with the option to restart.
Sound Effects: Adding sounds for movements, eating food, and game over events.
Multiple Levels: Increasing difficulty as the player's score increases.
Improved Graphics: Smoother rendering and visual enhancements.
Optimized Performance: Efficient handling of game loops and rendering.
Below is the revamped code with detailed comments and explanations.
Comprehensive Snake Game with Enhanced Features
Prerequisites
Ensure you have Pygame installed. You can install it using pip:
bash
pip install pygame
Complete Code
python
import pygame
import random
import sys
import math
import heapq
# Initialize Pygame
pygame.init()
pygame.mixer.init()
# Constants
SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600
CELL_SIZE = 20
FPS = 10
# Colors
BLACK = (0, 0, 0)
DARK_GRAY = (40, 40, 40)
WHITE = (255, 255, 255)
GREEN = (0, 200, 0)
LIGHT_GREEN = (0, 255, 0)
RED = (200, 0, 0)
LIGHT_RED = (255, 0, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
# 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 Game with AI Opponent")
clock = pygame.time.Clock()
# Load Sounds
EAT_SOUND = pygame.mixer.Sound('eat.wav')
GAME_OVER_SOUND = pygame.mixer.Sound('game_over.wav')
MOVE_SOUND = pygame.mixer.Sound('move.wav')
# Fonts
FONT_SMALL = pygame.font.SysFont('arial', 24)
FONT_MEDIUM = pygame.font.SysFont('arial', 36)
FONT_LARGE = pygame.font.SysFont('arial', 72)
def load_sound(name):
try:
sound = pygame.mixer.Sound(name)
return sound
except pygame.error as e:
print(f"Cannot load sound: {name}")
return None
# A* Pathfinding Implementation
def heuristic(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def a_star(start, goal, obstacles, grid_width, grid_height):
neighbors = [(0,1),(1,0),(0,-1),(-1,0)]
close_set = set()
came_from = {}
gscore = {start:0}
fscore = {start:heuristic(start, goal)}
oheap = []
heapq.heappush(oheap, (fscore[start], start))
while oheap:
current = heapq.heappop(oheap)[1]
if current == goal:
data = []
while current in came_from:
data.append(current)
current = came_from[current]
return data[::-1]
close_set.add(current)
for i, j in neighbors:
neighbor = current[0] + i, current[1] + j
tentative_g_score = gscore[current] + 1
if 0 <= neighbor[0] < grid_width:
if 0 <= neighbor[1] < grid_height:
if neighbor in obstacles:
continue
else:
continue
else:
continue
if neighbor in close_set and tentative_g_score >= gscore.get(neighbor, 0):
continue
if tentative_g_score < gscore.get(neighbor, 0) or neighbor not in [i[1] for i in oheap]:
came_from[neighbor] = current
gscore[neighbor] = tentative_g_score
fscore[neighbor] = tentative_g_score + heuristic(neighbor, goal)
heapq.heappush(oheap, (fscore[neighbor], neighbor))
return []
class Snake:
def __init__(self, color, position, controls=None, is_ai=False):
self.color = color
self.body = [position]
self.direction = RIGHT
self.next_direction = RIGHT
self.is_ai = is_ai
self.controls = controls # Dictionary mapping keys to directions
self.grow_flag = False
self.score = 0
self.path = []
def get_head_position(self):
return self.body[0]
def turn(self, direction):
# Prevent the snake from reversing
if (direction[0] * -1, direction[1] * -1) != self.direction:
self.next_direction = direction
def move(self):
if not self.is_ai:
self.direction = self.next_direction
MOVE_SOUND.play()
head_x, head_y = self.get_head_position()
new_head = (head_x + self.direction[0], head_y + self.direction[1])
self.body.insert(0, new_head)
if self.grow_flag:
self.grow_flag = False
else:
self.body.pop()
def grow(self):
self.grow_flag = True
self.score += 1
EAT_SOUND.play()
def draw(self, surface):
for segment in self.body:
pygame.draw.rect(surface, self.color, (segment[0]*CELL_SIZE, segment[1]*CELL_SIZE, CELL_SIZE, CELL_SIZE))
pygame.draw.rect(surface, DARK_GRAY, (segment[0]*CELL_SIZE, segment[1]*CELL_SIZE, CELL_SIZE, CELL_SIZE), 1)
def check_collision(self, grid_width, grid_height):
head = self.get_head_position()
# Check wall collision
if head[0] < 0 or head[0] >= grid_width or head[1] < 0 or head[1] >= grid_height:
return True
# Check self collision
if head in self.body[1:]:
return True
return False
def get_direction(self):
return self.direction
class AISnake(Snake):
def __init__(self, color, position):
super().__init__(color, position, is_ai=True)
self.path = []
def find_path(self, food_position, obstacles, grid_width, grid_height):
path = a_star(self.get_head_position(), food_position, obstacles, grid_width, grid_height)
return path
def update(self, food_position, obstacles, grid_width, grid_height):
if not self.path or self.path[-1] != food_position:
self.path = self.find_path(food_position, obstacles, grid_width, grid_height)
if self.path:
next_cell = self.path.pop(0)
dx = next_cell[0] - self.get_head_position()[0]
dy = next_cell[1] - self.get_head_position()[1]
self.turn((dx, dy))
else:
# No path found; make a safe random move
possible_moves = [UP, DOWN, LEFT, RIGHT]
random.shuffle(possible_moves)
for move in possible_moves:
new_head = (self.get_head_position()[0] + move[0], self.get_head_position()[1] + move[1])
if (0 <= new_head[0] < grid_width and
0 <= new_head[1] < grid_height and
new_head not in obstacles):
self.turn(move)
break
self.move()
def draw_grid(surface, grid_width, grid_height):
for x in range(grid_width):
pygame.draw.line(surface, DARK_GRAY, (x*CELL_SIZE, 0), (x*CELL_SIZE, SCREEN_HEIGHT))
for y in range(grid_height):
pygame.draw.line(surface, DARK_GRAY, (0, y*CELL_SIZE), (SCREEN_WIDTH, y*CELL_SIZE))
def draw_food(surface, position):
pygame.draw.rect(surface, YELLOW, (position[0]*CELL_SIZE, position[1]*CELL_SIZE, CELL_SIZE, CELL_SIZE))
pygame.draw.rect(surface, DARK_GRAY, (position[0]*CELL_SIZE, position[1]*CELL_SIZE, CELL_SIZE, CELL_SIZE), 1)
def generate_food(snake1, snake2, grid_width, grid_height):
while True:
position = (random.randint(0, grid_width -1), random.randint(0, grid_height -1))
if position not in snake1.body and position not in snake2.body:
return position
def display_score(surface, player_score, ai_score):
score_text = FONT_SMALL.render(f"Player: {player_score} AI: {ai_score}", True, WHITE)
surface.blit(score_text, (10, 10))
def display_game_over(surface, player_score, ai_score):
overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
overlay.set_alpha(180)
overlay.fill(BLACK)
surface.blit(overlay, (0,0))
game_over_text = FONT_LARGE.render("GAME OVER", True, RED)
score_text = FONT_MEDIUM.render(f"Player Score: {player_score}", True, WHITE)
ai_score_text = FONT_MEDIUM.render(f"AI Score: {ai_score}", True, WHITE)
restart_text = FONT_SMALL.render("Press R to Restart or Q to Quit", True, WHITE)
surface.blit(game_over_text, (SCREEN_WIDTH//2 - game_over_text.get_width()//2, SCREEN_HEIGHT//2 - 100))
surface.blit(score_text, (SCREEN_WIDTH//2 - score_text.get_width()//2, SCREEN_HEIGHT//2 - 30))
surface.blit(ai_score_text, (SCREEN_WIDTH//2 - ai_score_text.get_width()//2, SCREEN_HEIGHT//2 + 10))
surface.blit(restart_text, (SCREEN_WIDTH//2 - restart_text.get_width()//2, SCREEN_HEIGHT//2 + 50))
pygame.display.flip()
def main():
grid_width = SCREEN_WIDTH // CELL_SIZE
grid_height = SCREEN_HEIGHT // CELL_SIZE
player_start_pos = (grid_width//4, grid_height//2)
ai_start_pos = (3 * grid_width//4, grid_height//2)
player_snake = Snake(GREEN, player_start_pos, controls={
pygame.K_UP: UP,
pygame.K_DOWN: DOWN,
pygame.K_LEFT: LEFT,
pygame.K_RIGHT: RIGHT
})
ai_snake = AISnake(RED, ai_start_pos)
food_position = generate_food(player_snake, ai_snake, grid_width, grid_height)
game_over = False
while True:
if not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
if event.key in player_snake.controls:
player_snake.turn(player_snake.controls[event.key])
# Move snakes
player_snake.move()
ai_obstacles = set(ai_snake.body + player_snake.body)
ai_snake.update(food_position, ai_obstacles, grid_width, grid_height)
# Check collisions
if player_snake.check_collision(grid_width, grid_height):
GAME_OVER_SOUND.play()
game_over = True
if ai_snake.check_collision(grid_width, grid_height):
GAME_OVER_SOUND.play()
game_over = True
# Check if snakes eat the food
if player_snake.get_head_position() == food_position:
player_snake.grow()
food_position = generate_food(player_snake, ai_snake, grid_width, grid_height)
elif ai_snake.get_head_position() == food_position:
ai_snake.grow()
food_position = generate_food(player_snake, ai_snake, grid_width, grid_height)
# Increase difficulty based on player score
current_fps = FPS + player_snake.score // 5
if current_fps > 30:
current_fps = 30
# Drawing
screen.fill(BLACK)
draw_grid(screen, grid_width, grid_height)
draw_food(screen, food_position)
player_snake.draw(screen)
ai_snake.draw(screen)
display_score(screen, player_snake.score, ai_snake.score)
pygame.display.flip()
clock.tick(current_fps)
else:
display_game_over(screen, player_snake.score, ai_snake.score)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
pygame.quit()
sys.exit()
elif event.key == pygame.K_r:
main() # Restart the game
if __name__ == "__main__":
main()
Explanation of the Overhaul
Code Structure and Organization:
Classes:
Snake: Base class representing a generic snake. Handles movement, growing, drawing, and collision detection.
AISnake: Inherits from Snake and adds pathfinding capabilities using the A* algorithm to navigate towards the food intelligently.
Functions:
a_star: Implements the A* pathfinding algorithm to find the shortest path from the AI snake's head to the food, considering obstacles.
draw_grid: Renders the game grid for better visual structure.
draw_food: Draws the food item on the screen.
generate_food: Randomly places food on the grid, ensuring it doesn't overlap with either snake.
display_score: Shows the current scores of the player and AI.
display_game_over: Presents a game-over screen with the final scores and options to restart or quit.
load_sound: Helper function to load sound files with error handling.
Advanced AI:
The AISnake class uses the A* algorithm to find the most efficient path to the food while avoiding collisions.
If no path is found (e.g., the AI is trapped), it defaults to making a safe random move.
Additional Features:
Score Tracking: Both the player and AI have individual scores displayed at the top-left corner.
Game Over Screen: When a collision is detected (with walls or self), a translucent overlay displays the game-over message along with the final scores. Players can press R to restart or Q to quit.
Sound Effects: Added sounds for eating food (eat.wav), game over (game_over.wav), and movements (move.wav). Ensure these .wav files are present in your working directory or adjust the paths accordingly.
Multiple Levels: The game's speed increases as the player's score increases, making the game progressively more challenging.
Improved Graphics: Added grid lines for better visual guidance and outlined the snake segments and food for a polished look.
Optimized Performance:
Enhancements and Customizations
Sound Files: You'll need to provide the following sound files in the same directory as your script or adjust the paths accordingly:
eat.wav: Played when a snake eats the food.
game_over.wav: Played when the game ends.
move.wav: Played whenever the player changes direction.
If you don't have these files, you can create simple beep sounds or remove the sound-playing lines to avoid errors.
Graphics Customization: Feel free to tweak colors, fonts, and grid sizes to suit your aesthetic preferences.
AI Behavior: The current AI uses the A* algorithm for pathfinding. You can further enhance its behavior by implementing obstacle anticipation or multi-step planning.
Additional Features:
High Scores: Implement a high-score tracking system to keep track of the best performances.
Multiple Food Types: Introduce different food items with varying effects, such as speed boosts or temporary invincibility.
Multiplayer Mode: Allow multiple players to compete on the same screen.
Running the Game
Ensure Dependencies: Make sure Pygame is installed and the necessary sound files are in place.
Execute the Script: Run the Python script using your preferred IDE or via the command line:
bash
python advanced_snake_game.py
Gameplay:
Use the arrow keys to control your snake.
Avoid colliding with walls or yourself.
Compete against the AI snake to eat food and grow longer.
The game's difficulty increases as your score increases.