Create Snake Game in Python – Snake Game Program using Pygame

FREE Online Courses: Your Passport to Excellence - Start Now

It’s always fun to play games developed by us, let’s develop one of the most popular games – snake game in python. Let’s start making the python project and learn amazing concepts of python.

Snake Game

It’s the most famous game we used to play in our childhood before the advent of smartphones. This is a very simple project in which the snake will eat the food when its mouth touches the food. Furthermore, the length of the snake will keep on increasing after eating the food and if the snake touches the screen or itself the game will be over.

Python Snake Game Project

The objective of this project is to implement the snake game using Python. It requires a specific module pygame to start building the game. You also need to import pygame and random modules. Knowledge of Python functions and loops is required.

Project Prerequisites

This python project requires a good knowledge of the pygame module, concept of functions, loops as they will be used in this snake game project. Basics of the pygame module is a must to start the project.

Download Snake Game Python Code

Please download the source code of python snake game: Snake Game Python Project Code

Project File structure

Steps to follow to built snake game in python:

  1. Installing Pygame
  2. Importing random and Pygame
  3. Creating the game window
  4. Displaying score on the screen
  5. To make the welcome screen
  6. Defining the variables that will be used in the program
  7. If the game is over
  8. To play the game with the help of arrow keys
  9. Eating the food and displaying score
  10. Increasing the length of snake
  11. If the snake collides with itself or the wall
  12. Plotting the snake

Let’s start developing the python snake game

1. Installing Pygame:

Before starting the project you need to install Pygame on your system. It’s a set of modules in Python, which are designed to write code for video games. To install it on your system, write the given command on your command prompt.

pip install Pygame

2. Importing random and Pygame:

import pygame
import random

Code Explanation:

  • Import pygame: It is used to import a set of python modules designed to write video games.
  • Import random: It imports the module which generates pseudo-random variables.

3. Creating the snake game window:

x = pygame.init()
width_of_screen = 900
height_of_screen = 600
gameWindow = pygame.display.set_mode((width_of_screen,height_of_screen))
pygame.display.set_caption("python snake game PythonGeeks")
pygame.display.update()
clock = pygame.time.Clock()

Code Explanation:

We define the variables width_of _screen and height_of_screen to store the width and height of the screen of the game screen

  • pygame.init(): It initializes all the imported modules of pygame for snake game.
  • pygame.display.set_mode(): It helps to set up the screen for display.
  • pygame.display.set_caption(): It displays the caption on the top of your screen.
  • pygame.display.update(): It is used to update the display of the screen.

4. Displaying snake game score on the screen:

def score_on_screen(text,color,x,y):
    screen_text = font.render(text, True , color)
    gameWindow.blit(screen_text,[x,y])

Code Explanation:

This function is defined to display snake game scores on the screen. font.render() takes the text and color of the text and stores it in a variable. blit() function takes this variable and the coordinates of x and y to display it on the screen. This function will be used later in the game to display the score.

5. To make the welcome screen:

def welcome():
    game_exit = False
    while not game_exit:
        gameWindow.fill((255,182,193))
        score_on_screen("Welcome to snakes game by PythonGeeks",black,90,250)
        score_on_screen("Press spacebar to play",black,232,290)
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                game_exit = True
            if event.type==pygame.KEYDOWN:
                if event.key==pygame.K_SPACE:
                    game()
        pygame.display.update()
        clock.tick(60)

Code Explanation:

This function is defined to display a welcome screen before the start of the snake game.

  • fill(): This function takes the RGB values of color as argument and fills the whole screen with that color.
  • score_on_screen() : This function will display the text on screen.
  • pygame.event.get(): It returns the list of all events that are unprocessed.
  • pygame.QUIT(): It checks whether we are in the game or not.
  • pygame.KEYDOWN(): It checks whether a key is pressed or not.
  • pygame.K_SPACE(): After clicking the space key, the python snake game will start.

6. Defining the variables that will be used in the program:

def game():
    game_exit= False
    game_over= False
    snake_x=45
    snake_y=55
    velocity_x= 0
    velocity_y= 0
    init_velocity = 5
    score= 0
    apple_x = random.randint(20,width_of_screen/2)
    apple_y = random.randint(20,height_of_screen/2)
    snake_size=30
    snake_list = []
    snake_length = 1
    fps=40

Code Explanation:

We define a game function in which various variables are initialized :

  • game_exit: It is initialized to False. Once the variable is True, we will exit from the game.
  • game_over: It is also initialized to False. Once the variable is assigned True the python sanke game will be over.
  • snake_x and snake_y: It is the coordinates of the snake in x and y direction.
  • velocity_x and velocity_y: It is the velocity of the snake in x and y direction which will be changed later in the game.
  • init_velocity: It is the velocity of the snake in the snake game.
  • apple_x and apple_y: It is the position of food in x and y coordinate.
  • snake_size: It is the size of the snake
  • snake_list and snake_length: They will be used further in this function.
  • fps: It is the number of pictures a program can draw in a second.

7. If the snake game is over:

with open ("highscore.txt","r") as f:
        highscore = f.read()
    while not game_exit:
        if game_over:
            with open ("high score.txt","w") as f:
                f.write(str(highscore))
            gameWindow.fill(white)
            score_on_screen("Game Over! Press Enter to continue",red,100,250)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    game_exit = True
                if event.type== pygame.KEYDOWN:
                    if event.key == pygame.K_RETURN:
                        welcome()

Code Explanation:

Highscore.txt file is created and high score of python snake game is stored in this file. The file is opened with the use of open() in read mode and the high score is read. If the game is over the high score will be written in that file with the use of f.write().

  • pygame.K_RETURN: After clicking on enter key, the welcome screen will be displayed.

8. To play the snake game with the help of arrow keys:

else:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    game_exit = True
                if event.type==pygame.KEYDOWN:
                    if event.key == pygame.K_RIGHT:
                        velocity_x =  init_velocity
                        velocity_y = 0
                    if event.key == pygame.K_LEFT:
                        velocity_x = -init_velocity
                        velocity_y = 0
                    if event.key == pygame.K_UP:
                        velocity_y = -init_velocity
                        velocity_x = 0
                    if event.key == pygame.K_DOWN:
                        velocity_y =  init_velocity
                        velocity_x = 0
            snake_x+=velocity_x
            snake_y+=velocity_y

Code Explanation:

  • pygame.K_RIGHT: After clicking the right arrow key the velocity in x direction is set to init_velocity and y to 0 so that snake only moves in x direction.
  • pygame.K_LEFT: After clicking the left arrow key the velocity in x direction is set in negative, so that snake moves only in the left direction. Velocity in y direction is set to 0 so that it doesn’t move diagonally.
  • pygame.K_UP: After clicking the up arrow key the velocity is set only in y direction so that the snake only moves in y axis in upward direction.
  • pygame.K_DOWN: After clicking the down arrow key the velocity is set in y direction so that it only moves in y axis in downward direction and not diagonally.

9. Eating the food and displaying score:

if abs(snake_x - apple_x)<20 and abs(snake_y - apple_y)<20:
                score+=10
                apple_x = random.randint(20,width_of_screen/2)
                apple_y = random.randint(20,height_of_screen/2)
                snake_length+=5
                if score>int(highscore):
                    highscore = score
            gameWindow.fill(white)
            score_on_screen("Score: "+str(score) + " highscore: "+str(highscore),red,5,5)
            pygame.draw.rect(gameWindow,red,[apple_x,apple_y,snake_size,snake_size])

Code Explanation:

  • abs(snake_x-apple_x)<20 and abs(snake_y-apple_y): If the snake comes in this proximity it will eat the food.
  • score_on_screen(): This will display the highest score of python snake game on the screen.

10. Increasing the length of snake:

head=[]
            head.append(snake_x)
            head.append(snake_y)
            snake_list.append(head)
            if len(snake_list)>snake_length:
                del snake_list[0]

Code Explanation:

  • Head: An empty list is initialized and the x,y coordinates are appended in the list.
  • snake_list: Head is appended in this list.

If the length of the snake_list is greater than the length of the snake we will delete the first element of snake_list, so that the length does not increase after every coordinate. It only increases if the snake eats the food.

11. If the snake collides with itself or the wall:

if head in snake_list[:-1]:
                game_over=True
if snake_x<0 or snake_x>width_of_screen or snake_y<0 or snake_y>height_of_screen:
                game_over = True

Code Explanation:

  • Snake_list contains all the coordinates of the snake that it has traveled and the head contains the coordinate of the current position of the snake’s head. If the head of the snake is in the remaining snake_list excluding the first element, it will collide with itself.
  • If the coordinates of the snake in x direction or coordinates in y direction is negative the snake will collide with the wall. Furthermore, if the coordinates of the snake in x direction is greater than the width of the screen or the coordinates of the snake in y direction is greater than the height of the screen in python snake game, the snake will collide with the wall.

12. Plotting the snake:

def plot_snake(gameWindow, color ,snake_list,snake_size):
    for x,y in snake_list:
        pygame.draw.rect(gameWindow,color,[x,y,snake_size,snake_size])

Code Explanation:

This function is defined to plot the snake in the snake game.

13. Remaining code:

plot_snake(gameWindow,black,snake_list,snake_size)
            pygame.draw.rect(gameWindow,black,[snake_x,snake_y,snake_size,snake_size])
        pygame.display.update() 
        clock.tick(fps)
    pygame.quit()
    quit()
welcome()

Python Snake Game Output

python snake game output

Summary

We have successfully developed a snake game in python. We have used pygame to create snake game. We have created various functions to play the game.

Interview questions:

Intermediate level:

1. What is the output of this code?

pygame.init()
width_of_screen = 900
height_of_screen = 600
gameWindow = pygame.display.set_mode((width_of_screen,height_of_screen))

This code will display a blank screen of width 900 and height 600. pygame.init() function initializes all the modules that are imported in python. pygame.display.set_mode() takes two arguments: the width and height of the screen.

2. What is the pygame.event.get() function in pygame?

Take the example of this code:

for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    game_exit = True

pygame.event.get() stores all the events in an event queue. It is a way to access events of the queue and also pygame interacts with the operating system internally. In this code, if the type of event is QUIT game_exit variable is assigned True. This will help in exiting the game.

Did you like our efforts? If Yes, please give PythonGeeks 5 Stars on Google | Facebook

3 Responses

  1. Deep says:

    instead of box we using circle??

  2. G KEERTHANA says:

    learning porpose

  3. G KEERTHANA says:

    learning purpose

Leave a Reply

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