Skip to main content

Welcome to our Python Tutorial on building a Snake Game! In this short guide, we’ll walk you through the steps to create a classic Snake Game using Python and Pygame. Follow along as we explore the world of game development with Python and learn how to code this fun and interactive game from scratch. Let’s dive in and embark on this exciting programming adventure together!

Importing necessary modules:

import pygame
import random

We import the pygame library, which is used to create games and multimedia applications in Python. We also import the random module to generate random positions for the food.

Initializing Pygame and setting up the screen:

screen_width, screen_height = 800, 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Snake Game')

We initialize the Pygame modules and set up the game window with a width of 800 pixels and a height of 600 pixels. We also set the caption of the window to “Snake Game.”

Defining colors and snake properties:

white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
snake_block = 20
snake_speed = 15

We define some colors using RGB values. snake_block represents the size of each block of the snake and the food, and snake_speed controls the speed of the snake.

Defining the our_snake function:

our_snake(snake_block, snake_list):
    for x, y in snake_list:
        pygame.draw.rect(screen, green, [x, y, snake_block, snake_block])

This function is used to draw the snake on the screen. It takes snake_block (size of the block) and snake_list (a list of (x, y) positions of the snake segments) as arguments. It uses pygame.draw.rect to draw rectangles with green color on the screen for each segment of the snake.

Defining the game_loop function:

def game_loop():
    # ... (Rest of the code inside the game_loop function)

This function is the main game loop where the game logic is implemented.

Handling game states and user input:

game_over = False
game_close = False
# ...
while not game_over:
    while game_close:
        # ... (Handling game over and restart conditions)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                # ... (Handling different arrow key inputs)

We use game_over and game_close variables to manage different game states. When game_close is True, it means the player has lost, and we display the appropriate message and handle restart or quitting. The main game loop listens for events, and if the player presses the arrow keys, we change the direction of the snake accordingly.

Moving the snake and handling collisions:

if snake_x >= screen_width or snake_x < 0 or snake_y >= screen_height or snake_y < 0:
    game_close = True

snake_x += snake_change_x
snake_y += snake_change_y
# ...
snake_head = [snake_x, snake_y]

if len(snake_list) > snake_length:
    del snake_list[0]

for segment in snake_list[:-1]:
    if segment == snake_head:
        game_close = True

Here, we check for collisions with the boundaries of the screen and with the snake’s own body. If the snake hits the boundaries or collides with itself, game_close becomes True, and the game over message is displayed.

Drawing the snake and food on the screen:

pygame.draw.rect(screen, red, [food_x, food_y, snake_block, snake_block])
our_snake(snake_block, snake_list)

We first fill the screen with white color and then draw the red food rectangle using pygame.draw.rect. After that, we draw the snake on the screen using the our_snake function, which iterates through the snake segments and draws green rectangles for each segment. Finally, we call pygame.display.update() to update the display with the latest changes.

Handling food consumption and increasing the snake length:

if snake_x == food_x and snake_y == food_y:
    food_x, food_y = round(random.randrange(0, screen_width - snake_block) / 20) * 20, round(random.randrange(0, screen_height - snake_block) / 20) * 20
    snake_length += 1

If the snake’s head position matches the food position, it means the snake has consumed the food. We generate new random positions for the food and increase the length of the snake.

Controlling the game speed with clock.tick(snake_speed):

clock = pygame.time.Clock()
# ...

We create a Clock object to control the game’s frame rate, and we call clock.tick(snake_speed) inside the game loop to set the speed of the snake.

Quitting the game:


When the game loop ends (the player quits or loses), we call pygame.quit() to uninitialize the Pygame modules and quit() to exit the Python program.

The full source code for this project is available on Github.

Close Menu

Welcome to Coded Brainy

Coded Brainy Provides you with technical blogs

Coded Brainy