In this tutorial, we will create a classic snake game using the Pygame library in Python. The game will feature a snake that moves around the screen and eats food to grow longer. If the snake hits a wall or its own tail, the game will end.

Setting Up the Environment

Before we start coding, we need to set up our environment. We will be using Python 3 and the Pygame library. To install Pygame, open your terminal or command prompt and type:

pip install pygame

Creating the Game Window

To create the game window, we first need to import the Pygame library and initialize it:

import pygame

pygame.init()

# Set up the window
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Snake Game")

Here, we create a window with a width of 800 pixels and a height of 600 pixels, and set the caption to "Snake Game".

Creating the Snake

To create the snake, we will use a list of rectangles. Each rectangle represents a segment of the snake's body. We will start with a single rectangle, which will be the snake's head.

# Set up the snake
snake = []
snake_segment = pygame.Rect(400, 300, 20, 20)
snake.append(snake_segment)

Here, we create a rectangle with a width and height of 20 pixels, and position it at the center of the screen. We then append the rectangle to the snake list.

Moving the Snake

To move the snake, we will modify the position of each rectangle in the snake list. We will start at the end of the list and move each rectangle to the position of the one in front of it.

# Move the snake
for i in range(len(snake)-1, 0, -1):
    snake[i].x = snake[i-1].x
    snake[i].y = snake[i-1].y

Here, we loop through the snake list backwards, starting at the end. We set the position of each rectangle to the position of the one in front of it.

To move the snake in a specific direction, we need to modify the position of the snake's head. We can do this by checking for keyboard input in the game loop:

# Check for keyboard input
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        running = False
    elif event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            snake[0].x -= 20
        elif event.key == pygame.K_RIGHT:
            snake[0].x += 20
        elif event.key == pygame.K_UP:
            snake[0].y -= 20
        elif event.key == pygame.K_DOWN:
            snake[0].y += 20

Here, we loop through the events in the Pygame event queue. If the user clicks the close button, we set the running variable to False to exit the game loop. If the user presses a key, we check which key was pressed and modify the position of the snake's head accordingly.

Creating the Food