Here's a complete implementation of the classic Snake game with smooth animations, vibrant visuals, and intuitive controls.
python
import pygame
import random
import sys
import math
# Initialize pygame
pygame.init()
# Screen dimensions
WIDTH, HEIGHT = 800, 600
GRID_SIZE = 20
GRID_WIDTH = WIDTH // GRID_SIZE
GRID_HEIGHT = HEIGHT // GRID_SIZE
# Colors
BACKGROUND = (15, 20, 25)
GRID_COLOR = (30, 35, 40)
SNAKE_HEAD_COLOR = (50, 205, 50)
SNAKE_BODY_COLOR = (34, 139, 34)
FOOD_COLOR = (220, 20, 60)
TEXT_COLOR = (240, 240, 240)
UI_BG = (30, 40, 50, 200)
UI_BORDER = (60, 140, 200)
# Game settings
FPS = 10
SPEED_MULTIPLIER = 1.2
class Snake:
def __init__(self):
self.reset()
def reset(self):
self.length = 3
self.positions = [(GRID_WIDTH // 2, GRID_HEIGHT // 2)]
self.direction = random.choice([(0, 1), (0, -1), (1, 0), (-1, 0)])
self.score = 0
self.grow_to = 3
self.is_alive = True
self.last_move_time = 0
self.move_delay = 100 # milliseconds
def get_head_position(self):
return self.positions[0]
def update(self, current_time):
if not self.is_alive:
return
if current_time - self.last_move_time > self.move_delay:
self.last_move_time = current_time
head = self.get_head_position()
x, y = self.direction
new_x = (head[0] + x) % GRID_WIDTH
new_y = (head[1] + y) % GRID_HEIGHT
new_position = (new_x, new_y)
# Check collision with self
if new_position in self.positions[1:]:
self.is_alive = False
return
self.positions.insert(0, new_position)
if len(self.positions) > self.grow_to:
self.positions.pop()
def render(self, surface):
for i, pos in enumerate(self.positions):
color = SNAKE_HEAD_COLOR if i == 0 else SNAKE_BODY_COLOR
rect = pygame.Rect((pos[0] * GRID_SIZE, pos[1] * GRID_SIZE), (GRID_SIZE, GRID_SIZE))
# Draw the snake segment with rounded corners
pygame.draw.rect(surface, color, rect, border_radius=8)
# Add eyes to the head
if i == 0:
# Determine eye positions based on direction
eye_size = GRID_SIZE // 5
if self.direction == (1, 0): # Right
left_eye = (pos[0] * GRID_SIZE + GRID_SIZE - eye_size - 2, pos[1] * GRID_SIZE + 5)
right_eye = (pos[0] * GRID_SIZE + GRID_SIZE - eye_size - 2, pos[1] * GRID_SIZE + GRID_SIZE - 5 - eye_size)
elif self.direction == (-1, 0): # Left
left_eye = (pos[0] * GRID_SIZE + 2, pos[1] * GRID_SIZE + 5)
right_eye = (pos[0] * GRID_SIZE + 2, pos[1] * GRID_SIZE + GRID_SIZE - 5 - eye_size)
elif self.direction == (0, 1): # Down
left_eye = (pos[0] * GRID_SIZE + 5, pos[1] * GRID_SIZE + GRID_SIZE - eye_size - 2)
right_eye = (pos[0] * GRID_SIZE + GRID_SIZE - 5 - eye_size, pos[1] * GRID_SIZE + GRID_SIZE - eye_size - 2)
else: # Up
left_eye = (pos[0] * GRID_SIZE + 5, pos[1] * GRID_SIZE + 2)
right_eye = (pos[0] * GRID_SIZE + GRID_SIZE - 5 - eye_size, pos[1] * GRID_SIZE + 2)
pygame.draw.rect(surface, (0, 0, 0), pygame.Rect(left_eye, (eye_size, eye_size)), border_radius=eye_size//2)
pygame.draw.rect(surface, (0, 0, 0), pygame.Rect(right_eye, (eye_size, eye_size)), border_radius=eye_size//2)
def change_direction(self, direction):
# Prevent 180-degree turns
if (direction[0] * -1, direction[1] * -1) != self.direction:
self.direction = direction
class Food:
def __init__(self):
self.position = (0, 0)
self.color = FOOD_COLOR
self.randomize_position()
self.pulse_value = 0
self.pulse_direction = 1
def randomize_position(self):
self.position = (random.randint(0, GRID_WIDTH - 1), random.randint(0, GRID_HEIGHT - 1))
def update(self):
# Pulsing effect
self.pulse_value += 0.1 * self.pulse_direction
if self.pulse_value >= 1:
self.pulse_direction = -1
elif self.pulse_value <= 0:
self.pulse_direction = 1
def render(self, surface):
x, y = self.position
center_x = x * GRID_SIZE + GRID_SIZE // 2
center_y = y * GRID_SIZE + GRID_SIZE // 2
# Calculate pulse size
pulse_size = GRID_SIZE // 2 + int(GRID_SIZE // 4 * self.pulse_value)
# Draw pulsating food
pygame.draw.circle(surface, self.color, (center_x, center_y), pulse_size)
# Draw inner highlight
highlight_size = pulse_size // 3
pygame.draw.circle(surface, (255, 255, 255, 100),
(center_x - pulse_size//3, center_y - pulse_size//3),
highlight_size)
class Game:
def __init__(self):
self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake Game")
self.clock = pygame.time.Clock()
self.font = pygame.font.SysFont("Arial", 24)
self.big_font = pygame.font.SysFont("Arial", 48, bold=True)
self.snake = Snake()
self.food = Food()
self.game_state = "playing" # "playing", "game_over"
self.particles = []
self.speed_boost = 1.0
def draw_grid(self):
for x in range(0, WIDTH, GRID_SIZE):
pygame.draw.line(self.screen, GRID_COLOR, (x, 0), (x, HEIGHT))
for y in range(0, HEIGHT, GRID_SIZE):
pygame.draw.line(self.screen, GRID_COLOR, (0, y), (WIDTH, y))
def draw_ui(self):
# Score display
score_text = self.font.render(f"Score: {self.snake.score}", True, TEXT_COLOR)
self.screen.blit(score_text, (20, 20))
# Length display
length_text = self.font.render(f"Length: {len(self.snake.positions)}", True, TEXT_COLOR)
self.screen.blit(length_text, (20, 50))
# Speed display
speed_text = self.font.render(f"Speed: {self.speed_boost:.1f}x", True, TEXT_COLOR)
self.screen.blit(speed_text, (20, 80))
# Draw UI panel
pygame.draw.rect(self.screen, UI_BG, (WIDTH - 200, 20, 180, 100), border_radius=10)
pygame.draw.rect(self.screen, UI_BORDER, (WIDTH - 200, 20, 180, 100), 2, border_radius=10)
# Draw controls info
controls = [
"CONTROLS:",
"Arrow Keys - Move",
"R - Restart",
"+/- - Speed"
]
for i, text in enumerate(controls):
ctrl_text = self.font.render(text, True, TEXT_COLOR)
self.screen.blit(ctrl_text, (WIDTH - 190, 30 + i * 25))
def draw_game_over(self):
overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
overlay.fill((0, 0, 0, 180))
self.screen.blit(overlay, (0, 0))
game_over_text = self.big_font.render("GAME OVER", True, (220, 20, 60))
score_text = self.font.render(f"Final Score: {self.snake.score}", True, TEXT_COLOR)
restart_text = self.font.render("Press R to Restart", True, TEXT_COLOR)
self.screen.blit(game_over_text, (WIDTH//2 - game_over_text.get_width()//2, HEIGHT//2 - 60))
self.screen.blit(score_text, (WIDTH//2 - score_text.get_width()//2, HEIGHT//2))
self.screen.blit(restart_text, (WIDTH//2 - restart_text.get_width()//2, HEIGHT//2 + 50))
def add_particles(self, position):
for _ in range(15):
angle = random.uniform(0, math.pi * 2)
speed = random.uniform(1, 3)
size = random.randint(2, 5)
lifetime = random.randint(20, 40)
color = random.choice([(255, 215, 0), (255, 140, 0), (255, 69, 0)])
self.particles.append({
'pos': list(position),
'vel': [math.cos(angle) * speed, math.sin(angle) * speed],
'size': size,
'color': color,
'lifetime': lifetime
})
def update_particles(self):
for particle in self.particles[:]:
particle['pos'][0] += particle['vel'][0]
particle['pos'][1] += particle['vel'][1]
particle['lifetime'] -= 1
if particle['lifetime'] <= 0:
self.particles.remove(particle)
def draw_particles(self):
for particle in self.particles:
pygame.draw.circle(
self.screen,
particle['color'],
(int(particle['pos'][0]), int(particle['pos'][1])),
particle['size']
)
def handle_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if self.game_state == "playing":
if event.key == pygame.K_UP:
self.snake.change_direction((0, -1))
elif event.key == pygame.K_DOWN:
self.snake.change_direction((0, 1))
elif event.key == pygame.K_LEFT:
self.snake.change_direction((-1, 0))
elif event.key == pygame.K_RIGHT:
self.snake.change_direction((1, 0))
elif event.key == pygame.K_PLUS or event.key == pygame.K_EQUALS:
self.speed_boost = min(self.speed_boost * SPEED_MULTIPLIER, 3.0)
elif event.key == pygame.K_MINUS:
self.speed_boost = max(self.speed_boost / SPEED_MULTIPLIER, 0.5)
if event.key == pygame.K_r:
self.snake.reset()
self.food.randomize_position()
self.game_state = "playing"
self.particles = []
self.speed_boost = 1.0
def check_collision(self):
if self.snake.get_head_position() == self.food.position:
self.snake.grow_to += 1
self.snake.score += 10
self.food.randomize_position()
# Ensure food doesn't appear on snake
while self.food.position in self.snake.positions:
self.food.randomize_position()
# Add particles
food_pos = (
self.food.position[0] * GRID_SIZE + GRID_SIZE // 2,
self.food.position[1] * GRID_SIZE + GRID_SIZE // 2
)
self.add_particles(food_pos)
def run(self):
while True:
current_time = pygame.time.get_ticks()
self.handle_events()
if self.game_state == "playing":
# Update game objects
self.snake.update(current_time)
self.food.update()
self.update_particles()
# Check for collisions
self.check_collision()
# Check if snake is dead
if not self.snake.is_alive:
self.game_state = "game_over"
# Draw everything
self.screen.fill(BACKGROUND)
self.draw_grid()
self.snake.render(self.screen)
self.food.render(self.screen)
self.draw_particles()
self.draw_ui()
if self.game_state == "game_over":
self.draw_game_over()
pygame.display.flip()
self.clock.tick(FPS * self.speed_boost)
# Start the game
if __name__ == "__main__":
game = Game()
game.run()
Enjoy the game! Use the arrow keys to move, and try to get the highest score possible.