How to Code a Snake Game in Python?

Estimated read time 3 min read

Creating a Snake game in Python is a great project to learn game development concepts. Here’s a simplified example to get you started:

  1. Set up the Game Window:
    • Import the necessary libraries such as Pygame.
    • Create a game window with a specified width and height.
    • Set up the game clock to control the frame rate.
  2. Initialize the Snake and Food:
    • Define the initial position, size, and movement direction of the snake.
    • Randomly position the food item on the game window.
  3. Handle User Input:
    • Capture keyboard inputs to change the snake’s direction.
    • Update the snake’s direction accordingly (up, down, left, or right).
  4. Update Snake Position:
    • Move the snake’s head in the current direction.
    • Update the positions of the snake’s body segments accordingly.
    • Check for collisions with the game window boundaries and the snake’s body.
  5. Check for Food Consumption:
    • Check if the snake’s head collides with the food item.
    • If so, increase the snake’s length and generate a new food item.
  6. Game Over Condition:
    • Check for collisions between the snake’s head and its body.
    • Check for collisions with the game window boundaries.
    • If a collision occurs, end the game and display the score.
  7. Render the Game:
    • Clear the game window.
    • Draw the snake and the food item.
    • Update the display to show the changes.
  8. Game Loop:
    • Continuously repeat the following steps:
      • Handle user input.
      • Update the snake’s position.
      • Check for food consumption.
      • Check for game over conditions.
      • Render the game.

Here’s a simplified code example to demonstrate the basic structure of a Snake game:

import pygame
import random

# Game window dimensions
WIDTH = 640
HEIGHT = 480

# Snake and food dimensions
SNAKE_SIZE = 20
FOOD_SIZE = 20

# Initialize Pygame
pygame.init()
window = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()

# Snake initial position and movement direction
snake_x = WIDTH // 2
snake_y = HEIGHT // 2
snake_dx = 0
snake_dy = 0

# Food initial position
food_x = random.randint(0, WIDTH - FOOD_SIZE)
food_y = random.randint(0, HEIGHT - FOOD_SIZE)

# Game loop
running = True
while running:
    # Handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                snake_dx = 0
                snake_dy = -1
            elif event.key == pygame.K_DOWN:
                snake_dx = 0
                snake_dy = 1
            elif event.key == pygame.K_LEFT:
                snake_dx = -1
                snake_dy = 0
            elif event.key == pygame.K_RIGHT:
                snake_dx = 1
                snake_dy = 0

    # Update snake position
    snake_x += snake_dx * SNAKE_SIZE
    snake_y += snake_dy * SNAKE_SIZE

    # Check for food consumption
    if snake_x == food_x and snake_y == food_y:
        food_x = random.randint(0, WIDTH - FOOD_SIZE)
        food_y = random.randint(0, HEIGHT - FOOD_SIZE)

    # Check for game over conditions
    if snake_x < 0 or snake_x >= WIDTH or snake_y < 0 or snake_y >= HEIGHT:
        running = False

    # Clear the window
    window.fill((0, 0, 0))

    # Draw the snake
    pygame.draw.rect(window, (255, 255, 255), (snake_x, snake_y, SNAKE_SIZE, SNAKE_SIZE))

    # Draw the food
    pygame.draw.rect(window, (255, 0, 0), (food_x, food_y, FOOD_SIZE, FOOD_SIZE))

    # Update the display
    pygame.display.update()

    # Control the frame rate
    clock.tick(10)

# Quit the game
pygame.quit()

This code provides a basic structure for a simple Snake game using Pygame. You can further enhance the game by adding features such as score tracking, increasing difficulty, and more complex collision detection.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply