Of course! Creating a Snake game is a classic and fantastic project for learning the fundamentals of game development in Python. Here is a step-by-step guide on how to build it, using the popular Pygame library.
Why Pygame?
Pygame is the standard library for making 2D games in Python. It handles graphics, sound, and user input, making it perfect for a project like this. A simpler alternative for absolute beginners is the built-in turtle module, but Pygame gives you more control and is a better stepping stone to more complex games.
Step 0: Prerequisites - Installation
Before you start, you need to have Python and Pygame installed.
- Install Python: If you don't have it, download it from python.org.
- Install Pygame: Open your terminal or command prompt and type:
pip install pygame
Step 1: Setting Up the Game Window and Loop
This is the foundation of any game. We need a window to draw on and a main loop that keeps the game running.
- Initialize Pygame: Start the Pygame engine.
- Create the Screen: Define the width and height and create a display surface (the window).
- Set up the Game Loop: An infinite
while loop that will:
- Handle user input (like closing the window).
- Update the state of all game objects.
- Draw everything on the screen.
- Control the Frame Rate: Use a
Clock to make sure the game runs at a consistent speed on all computers.
# step1_setup_window.py
import pygame
# 1. Initialize Pygame
pygame.init()
# 2. Create the Screen
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Python Snake')
# Define colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# 4. Clock for controlling the frame rate
clock = pygame.time.Clock()
# 3. Game Loop
running = True
while running:
# Event Handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Drawing
screen.fill(BLACK) # Clear the screen with black
# Update the display
pygame.display.flip()
# Cap the frame rate
clock.tick(15) # Run at 15 frames per second
pygame.quit()
Step 2: Creating the Snake
The snake is not just one object; it's a series of blocks. A Python list is perfect for this.
- Define Snake Properties: Set the size of the snake's blocks and its starting position.
- Represent the Snake: Use a list of
pygame.Rect objects or a list of [x, y] coordinate pairs. The first element in the list is the head.
- Draw the Snake: In the game loop, iterate through the list and draw a rectangle for each segment of the snake.
# In your setup before the game loop:
snake_block_size = 20
snake_speed = 15 # We'll relate this to the clock later
snake_body = [
[screen_width / 2, screen_height / 2],
[screen_width / 2 - snake_block_size, screen_height / 2],
[screen_width / 2 - (2 * snake_block_size), screen_height / 2]
]
snake_direction = 'RIGHT'
# In the game loop, inside the "Drawing" section:
for segment in snake_body:
pygame.draw.rect(screen, WHITE, [segment[0], segment[1], snake_block_size, snake_block_size])
Step 3: Handling User Input to Move the Snake
We need to change the snake's direction when the user presses the arrow keys.
- Check for Key Presses: In the event handling part of the loop, look for
pygame.KEYDOWN events.
- Update Direction: Change the
snake_direction variable based on which key was pressed (Up, Down, Left, Right).
- Prevent Reversing: Add a check to prevent the snake from immediately reversing on itself (e.g., if moving right, you can't go left).
# In the event handling loop:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and snake_direction != 'RIGHT':
snake_direction = 'LEFT'
elif event.key == pygame.K_RIGHT and snake_direction != 'LEFT':
snake_direction = 'RIGHT'
elif event.key == pygame.K_UP and snake_direction != 'DOWN':
snake_direction = 'UP'
elif event.key == pygame.K_DOWN and snake_direction != 'UP':
snake_direction = 'DOWN'
Step 4: Implementing the Movement Logic
Now we make the snake actually move across the screen. The trick is to add a new head in the direction of movement and remove the tail.
- Calculate New Head Position: Based on
snake_direction, determine the coordinates for the new head.
- Update the Body: Insert the new head at the beginning of the
snake_body list.
- Remove the Tail: Use
snake_body.pop() to remove the last element of the list. This makes it look like the entire snake moved forward.
# Add an "Update Game State" section in your main loop, before drawing
# Get the current head position
head = snake_body[0]
new_head = [head[0], head[1]]
# Calculate new head position based on direction
if snake_direction == 'LEFT':
new_head[0] -= snake_block_size
elif snake_direction == 'RIGHT':
new_head[0] += snake_block_size
elif snake_direction == 'UP':
new_head[1] -= snake_block_size
elif snake_direction == 'DOWN':
new_head[1] += snake_block_size
# Insert the new head and remove the tail
snake_body.insert(0, new_head)
snake_body.pop() # For now, we always remove the tail
Step 5: Creating the Food
The snake needs something to eat!
- Import
random: We'll need this to place food randomly.
- Generate Food Position: Create a function that generates a random
(x, y) position for the food. Make sure it aligns with the grid (i.e., is a multiple of snake_block_size).
- Draw the Food: In the game loop, draw the food on the screen.
import random # Add this at the top of your file
# Before the game loop:
food_pos = [
random.randrange(1, (screen_width // snake_block_size)) * snake_block_size,
random.randrange(1, (screen_height // snake_block_size)) * snake_block_size,
]
food_color = (255, 0, 0) # Red
# In the "Drawing" section of the loop:
pygame.draw.rect(screen, food_color, [food_pos[0], food_pos[1], snake_block_size, snake_block_size])
Step 6: Collision Detection & Growing the Snake
This is where the game logic gets interesting.
- Check for Collision with Food: See if the snake's head position is the same as the food's position.
- If they collide:
- Don't remove the tail segment for one frame. This makes the snake one block longer.
- Generate a new piece of food at a new random location.
- (Optional) Increase the score.
# In the "Update Game State" section, after inserting the new head:
# Check for collision with food
if snake_body[0][0] == food_pos[0] and snake_body[0][1] == food_pos[1]:
# Food eaten, generate new food
food_pos = [
random.randrange(1, (screen_width // snake_block_size)) * snake_block_size,
random.randrange(1, (screen_height // snake_block_size)) * snake_block_size,
]
else:
# If no food was eaten, remove the tail
snake_body.pop()
Step 7: Implementing Game Over Conditions
The game must end if the snake hits a wall or itself.
- Wall Collision: Check if the snake's head has gone outside the screen boundaries.
- Self Collision: Check if the snake's head position is the same as any other segment in its body.
- End the Game: If either collision happens, set the
running variable to False to exit the game loop.
# In the "Update Game State" section, after movement:
head = snake_body[0]
# 1. Wall Collision
if head[0] >= screen_width or head[0] < 0 or head[1] >= screen_height or head[1] < 0:
running = False # Game over
# 2. Self Collision
for segment in snake_body[1:]:
if head[0] == segment[0] and head[1] == segment[1]:
running = False # Game over
Step 8: Displaying the Score
Give the player feedback on how well they are doing.
- Create a Font Object:
pygame.font.SysFont() lets you create a font to render text.
- Keep Score: Create a
score variable and increment it when food is eaten.
- Render and Display: In the drawing section, render the score text onto a
Surface and then "blit" (copy) it onto the main screen.
# Before the game loop:
score = 0
font = pygame.font.SysFont('tahoma', 35)
# When food is eaten (in the collision check):
if snake_body[0][0] == food_pos[0] and snake_body[0][1] == food_pos[1]:
score += 10
# ... rest of the food eating logic ...
# In the "Drawing" section of the loop:
score_text = font.render(f"Score: {score}", True, WHITE)
screen.blit(score_text, [10, 10])
Summary of Steps
- Setup: Initialize Pygame, create a window, and start a game loop with a clock.
- Snake: Represent the snake as a list of coordinates and draw it.
- Input: Listen for arrow key presses to change the snake's direction.
- Movement: In each frame, add a new head in the current direction.
- Food: Create a food object at a random position and draw it.
- Collision & Growth: If the head hits the food, make the snake longer (by not removing the tail) and move the food. Otherwise, move the snake normally (by removing the tail).
- Game Over: End the game if the snake hits the wall or itself.
- Score: Keep track of a score and display it on the screen.
Next Steps and Improvements
Once you have this basic version working, you can add more features:
- "Play Again" Screen: Instead of just quitting, show a "Game Over" message and ask the player if they want to play again.
- Increasing Difficulty: Make the snake speed up as the score increases.
- Sounds: Add sound effects for eating food and for game over.
- Start Menu: Create a main menu before the game starts.
- High Score: Save the high score to a file so it persists between games.