Skip to content

Program to Create Snake Game in Python

  • by

Write a program to create a Snake Game in Python.

Here is a step by step guide to create Snake Game in Python:

Introduction to Create Snake Game in Python:

The Snake game is a classic arcade game that was first introduced in the 1970s. In this game the player controls a snake that moves around the screen eating food and growing in length. The game ends when the snake collides with a wall or with its own tail. In this tutorial we will show you how to create your own Snake game using Python.

Also Practice:

Write a Program to Create Hangman Game in Python

Program to Create Tic Tac Toe Game in Python

Step 1: Setting up the environment For Snake Game in Python

First step is set up your Python environment. We recommend use Python 3 and install Pygame library which is a popular library for creating games in Python. You may install Pygame using pip by running following command in terminal.

pip install pygame

Step 2: Initializing the game

The next step is to initialize game window and set up the game variables. Here we define the window size the initial position of the snake and the food and the initial length of the snake. Add following code to your Python file

import pygame
import random

# Initialize Pygame
pygame.init()

# Window size
width = 500
height = 500

# Colors
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)

# Create the window
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Game")

# Initial position of the snake
x = 250
y = 250

# Initial position of the food
food_x = round(random.randrange(0, width - 10) / 10.0) * 10.0
food_y = round(random.randrange(0, height - 10) / 10.0) * 10.0

# Initial length of the snake
length = 1
snake = [[x, y]]

This code initialize Pygame and set up the window size colors and caption. It also initializes the position of the snake and food and the initial length of the snake.

Step 3: Handling user input

The next step is to handle user input which involves moving the snake in response to the arrow keys. Add following code to your Python file

# Movement
move_x = 0
move_y = 0

# Game loop
game_over = False
clock = pygame.time.Clock()

while not game_over:
    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:
                move_x = -10
                move_y = 0
            elif event.key == pygame.K_RIGHT:
                move_x = 10
                move_y = 0
            elif event.key == pygame.K_UP:
                move_x = 0
                move_y = -10
            elif event.key == pygame.K_DOWN:
                move_x = 0
                move_y = 10

    # Move the snake
    x += move_x
    y += move_y

This code defines a while the loop that runs until the game is over and handles user input by moving the snake in response to the arrow keys.

Step 4: Creating the snake

Now that we have the movement of the snake handling lets create the snake itself.

To do this we will use list of blocks where each block represents segment of the snake body. The blocks will be drawn on the screen as rectangles.

Add the following code to your Python file

# Create the snake
snake_block_size = 10
snake_list = []
snake_length = 1

def draw_snake(snake_block_size, snake_list):
    for x in snake_list:
        pygame.draw.rect(screen, black, [x[0], x[1], snake_block_size, snake_block_size])

while not game_over:
    # Handle user input
    for event in pygame.event.get():
        # ...

    # Move the snake
    x += move_x
    y += move_y

    # Create the snake
    snake_head = []
    snake_head.append(x)
    snake_head.append(y)
    snake_list.append(snake_head)

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

    draw_snake(snake_block_size, snake_list)

    # Check for collisions with the food
    # ...

In this code we create function called draw_snake that takes the snake block size and the list of blocks as arguments and draws each block on the screen using pygame.draw.rect.

We also create a list called snake_list to hold the blocks and set the initial length of the snake to 1.

In game loop we add a new block snake_list based on the snake position and delete the first block if the snake is longer than its length.

We then call the draw_snake function to draw the snake on the screen.

Step 5: Adding the food

Now that we have the snake let us add the food.

The food will be represented by small rectangle that snake can eat to increase its length.

Add the following code to your Python file

# Create the food
food_block_size = 10

def draw_food():
    pygame.draw.rect(screen, red, [food_x, food_y, food_block_size, food_block_size])

while not game_over:
    # Handle user input
    # ...

    # Move the snake
    # ...

    # Create the snake
    # ...

    # Draw the snake
    # ...

    # Create the food
    draw_food()

    # Check for collisions with the food
    if x == food_x and y == food_y:
        food_x = round(random.randrange(0, width - food_block_size) / 10.0) * 10.0
        food_y = round(random.randrange(0, height - food_block_size) / 10.0) * 10.0
        snake_length += 1

In this code we create a function called draw_food that draw food on the screen as a red rectangle.

We also create a variable called food_block_size to set the size of the food.

In game loop we call the draw_food function to draw the food on the screen and check for collisions with the food. If the snake collides with the food we randomly generate a new position for the food and increase the snake length.

Step 6: Checking for collisions

Now that we have snake and food we need to check collisions.

If snake collides with a wall or with its own body the game is over.

Add the following code to your Python file

# Check for collisions
if x < 0 or x >= width or y < 0 or y >= height:
    game_over = True

for block in snake_list[:-1]:
    if block == snake_head:
        game_over = True

In this code we check if the snake has collided with a wall. If the snake x or y position is less than 0 or greater than the width or height of the screen the game is over.

We also check if the snake has collided with its own body. We loop through each block in the snake_list except the last block (which is the head) and check if it is equal to the snake’s head position. If it is, the game is over.

Step 7: Displaying the score

Finally let’s display the player score on the screen.

Add the following code to your Python file

# Display the score
def display_score(score):
    font = pygame.font.SysFont(None, 25)
    text = font.render("Score: " + str(score), True, white)
    screen.blit(text, [0, 0])

while not game_over:
    # Handle user input
    # ...

    # Move the snake
    # ...

    # Create the snake
    # ...

    # Draw the snake
    # ...

    # Create the food
    # ...

    # Check for collisions
    # ...

    # Display the score
    display_score(snake_length - 1)

    # Update the screen
    pygame.display.update()

In above code we create a function called display_score() that takes the player’s score as an argument and uses Pygame built-in font library to render the score as text on the screen.

In game loop we call the display_score function to display the player score on screen.

Step 8: Putting it all together

Now that we have written all of the code let us put it all together and run the game.

Add the following code to your Python file

# Initialize Pygame
pygame.init()

# Set the screen size
width = 500
height = 500
screen = pygame.display.set_mode((width, height))

# Set the caption
pygame.display.set_caption("Snake Game")

# Set the colors
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)

# Set the initial position of the snake
x = width / 2
y = height / 2
move_x = 0
move_y = 0

# Create the snake
snake_block_size = 10
snake_list = []
snake_length = 1

def draw_snake(snake_block_size, snake_list):
    for x in snake_list:
        pygame.draw.rect(screen, black, [x[0], x[1], snake_block_size, snake_block_size])

# Create the food
food_block_size = 10

def draw_food():
    pygame.draw.rect(screen, red, [food_x, food_y, food_block_size, food_block_size])

# Display the score
def display_score(score):
    font = pygame.font.SysFont(None, 25)
    text = font.render("Score: " + str(score), True, white)
    screen.blit(text, [0, 0])

# Game loop
game_over = False
clock = pygame.time.Clock()
food_x = round(random.randrange(0, width - food_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, height - food_block_size) / 10.0) * 10.0

while not game_over:
    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:
                move_x = -snake_block_size
                move_y = 0
            elif event.key == pygame.K_RIGHT:
                move_x = snake_block_size
                move_y = 0
            elif event.key == pygame.K_UP:
                move_y = -snake_block_size
                move_x = 0
            elif event.key == pygame.K_DOWN:
                move_y = snake_block_size
                move_x = 0

    x += move_x
    y += move_y

    screen.fill(white)

    snake_head = [x, y]
    snake_list.append(snake_head)
    if len(snake_list) > snake_length:
        del snake_list[0]

    for block in snake_list[:-1]:
        if block == snake_head:
            game_over = True

    draw_snake(snake_block_size, snake_list)
    draw_food()

    if x == food_x and y == food_y:
        food_x = round(random.randrange(0, width - food_block_size) / 10.0) * 10.0
        food_y = round(random.randrange(0, height - food_block_size) / 10.0) * 10.0
        snake_length += 1

    if x < 0 or x >= width or y < 0 or y >= height:
        game_over = True

    display_score(snake_length - 1)

    pygame.display.update()

    clock.tick(10)

pygame.quit()

In this code we initialize Pygame and set the screen size and caption. We also set the colors that we will use for the game. We then set initial position of the snake and create the snake.

The draw_snake function takes in snake_block_size and snake_list as arguments and draws the snake on the screen.

We also create food for snake using the draw_food function. The display_score function displays the score of the player.

Next we create game loop that will run until the player quit or the game is over. In the loop we handle events such as quitting the game or moving the snake in a certain direction. We then update position of the snake based on its movement direction.

We check for collisions between snake and itself as well as collisions between the snake and food. If the snake collides with itself the game is over. If the snake collides with the food the food is regenerated in a random location and the length of the snake increases by 1.

If the snake goes out of bounds the game is also over.

We then display the score and update the screen.

Finally we quit Pygame when the game loop ends.

You can now run the Python file and play the game.

Python Useful Links:

Leave a Reply

Your email address will not be published. Required fields are marked *