Python implementation of the Snake Game using PyGame
In the following walkthrough, we will learn how to create a Snake Game by using the PyGame package in the programming language Python.
Nevertheless, before we get started, let’s first have a quick review of what the Snake Game is.
is.
The arcade version of the video game known as
A Brief Overview of the Snake Game
Snake was first introduced in the late 1970s. In 1998, it became the standard game that was pre-loaded onto Nokia mobile phones. The primary purpose of the game is for the player to take control of a long, slender creature that resembles a snake and moves about on a bounded plane while attempting to gather the most amount of fruits possible without colliding with the wall or oneself. The head of the snake may be controlled by the player in any one of four directions (up, down, left, or right), and the body of the snake will move in that direction. The complexity of the game will increase each time the snake consumes a new item of food since its tail will continue to grow longer.
The process of learning how to make a video game is both intriguing and enjoyable. When first getting started with Python or the PyGame module, making a Snake game might be a tough task. Any newbie programmer should take on the task of creating a game based on the Snake franchise since it is one of the simpler projects available.
Now, let us have a little discussion on the Python game known as PyGame.
library
Understanding the PyGame library
The PyGame library is a collection of Python modules that may be used to create video games. It is compatible with several platforms. The majority of what makes up PyGame are computer graphics and sound libraries that are intended to be used in conjunction with the programming language Python. This library was developed by Pete Shinners in an official capacity as a replacement for PySDL. It is appropriate to design client-side programs that have the possibility of being packaged in a standalone
executable.
How to install the PyGame library?
On a command prompt or terminal, use the following command to install the PyGame library with the PIP installer. You may do this by following the instructions below. Syntax:
-
# installing the PyGame library
-
$ pip install pygame
When the installation has been finished, we will be able to determine whether or not the pygame library was installed correctly by generating a new Python program file and importing the pygame module. This will allow us to do so.
The portion of code that illustrates the aforementioned concept may be found below. File: verify.py
-
import
pygame
Now that we have finished editing the file, let’s save it and then execute the following command on the command prompt or terminal. Syntax:
-
$ python verify.py
If the software does not report any importing errors once the library has been installed, then the installation was successful. In the event that an error is thrown, you should attempt to reload the library and think about looking at their official
documentation.
Prerequisites of the Project
Let’s take a quick look at the project’s requirements now that we have successfully installed the necessary library. The following is a list of the modules that were necessary for the
project:
-
PyGame:
This module will allow us to develop the game. -
Random:
This module will allow us to generate random numbers, print a random value for a list or string, and more. -
Time:
This module will allow us to work with time.
Developing the Snake Game using PyGame
After we have completed all of the requirements for the project, we will move on to the next step, which is the creation of the game. The process of developing the Python version of the Snake Game has been broken down into the progressive manner by our team. The following are the actions that need to be taken: Step 1: In the very first step, we will import the necessary modules. Step 2: After that, we will specify the required variables for the application Step 3: After that, we will initialize the pygame for the application Step 4: After that, we will initialize the sizes and locations of the game objects. In the fifth step, we will proceed to identify the essential functionalities that must be included in order for the game to be playable. In the sixth and last step, we will establish the application’s primary functionality, also known as the game loop.
Today we shall comprehend the measures that were previously taken in
detail.
Importing the required modules
First things first, we will begin the process of developing the game by loading the essential modules. At this step, we will also import the time and random modules in addition to the pygame module.
Let us take into consideration the following piece of code that demonstrates the same thing. File: snake.py
Explanation: W01A1@@3 Explanation:
In order to build the game, we have imported the pygame module, which can be seen in the preceding bit of code. After that, the time module was imported so that we could control the time. In the end, we were successful in importing the random module so that we could produce the objects in the
game.
Defining the necessary variables for the game
We are going to begin by defining some of the game’s required variables right now. The pace of the snake, the screen’s width and height, and the colors that will be used in the program are all examples of these variables.
Let’s have a look at the following bit of code that illustrates the same thing, shall we? File: snake.py
Explanation:
-
# defining the game variables
-
speed_of_snake =
15
-
-
# defining the size of the window
-
SCREEN_WIDTH =
700
-
SCREEN_HEIGHT =
460
-
-
# defining the colors
-
midnight_blue = pygame.Color(
25
,
25
,
112
)
-
mint_cream = pygame.Color(
245
,
255
,
250
)
-
crimson_red = pygame.Color(
220
,
20
,
60
)
-
lawn_green = pygame.Color(
124
,
252
,
0
)
-
orange_red = pygame.Color(
255
,
69
,
0
)
Related:
The variable that stores the speed of the snake has been defined in the line of code that was just shown to you. After that, we have established the width as well as the height of the window. Using the use of the Color() class provided by pygame, we have at long last specified a few colors, including white, black, red, green, and blue.
module.
Initializing the pygame for the application
Now that pygame has been loaded, we will initialize it by using the init() method, and we will use the pygame.display module to construct the main window that will show how the game is being played. In addition to this, we will use the pygame.time module in order to determine the game’s frame rates.
Let’s have a look at the following bit of code to better see how the functionality is really implemented. File: snake.py
Explanation:
-
# initializing the pygame window using the pygame.init() function
-
pygame.init()
-
-
# using the set_mode() function of the pygame.display module to set the size of the screen
-
display_screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
-
-
# setting the title of the application using the set_caption() function
-
pygame.display.set_caption(
‘SNAKE – JAVATPOINT’
)
-
-
# creating an object of the Clock() class of the pygame.time module
-
game_clock = pygame.time.Clock()
Related:
The pygame window has been initialized by using the init() method, which can be seen in the above bit of code. After that, we adjusted the dimensions of the screen by using the set mode() method that is included in the pygame.display module. After that, in order to set the application’s title, we made use of the set caption() method that is included in the pygame.display module. At long last, an instance of the Clock() class inside the pygame.time module has been constructed by us in order to establish the refresh rate for the
game.
Initializing the sizes and positions of the game objects
Adding the items to the game, as well as configuring their sizes and locations, is the next step. The fruit and the snake are both included in these things. To begin, we are going to determine the initial location of the snake as well as its size. In addition to this, we will move the fruits to the desired location and ensure that their spawn flag is set to True. In addition to this, we will determine the default position of the snake’s head.
Let’s have a look at the following bit of code that illustrates the same thing, shall we? File: snake.py
Explanation of
-
# defining the default position of the snake
-
position_of_snake = [
100
,
50
]
-
-
# defining the first four blocks of snake body
-
body_of_snake = [
-
[
100
,
50
],
-
[
90
,
50
],
-
[
80
,
50
],
-
[
70
,
50
]
-
]
-
-
# position of the fruit
-
position_of_fruit = [
-
random.randrange(
1
, (SCREEN_WIDTH//
10
)) *
10
,
-
random.randrange(
1
, (SCREEN_HEIGHT//
10
)) *
10
-
]
-
spawning_of_fruit =
True
-
-
# setting the default direction of the snake towards RIGHT
-
initial_direction =
‘RIGHT’
-
snake_direction = initial_direction
Format:
The default location of the snake has been specified in the piece of code that was just shown to you. After defining these first four sections of the snake’s body, we are now finished. After that, the location of the fruit has been specified, and the spawning of fruit variable has had its value changed to True. Also, we have configured the starting course of the snake to go in the right direction.
.
Defining the necessary functions of the game
It is time for us to specify some needed functions at this point, seeing as how we have already gone through the basic needs of the game. A function will be defined to show the player’s score, and another function will be defined to end the game. The actual operation of these functions in the system will now be shown to us.
detail.
Function to display the score of the player
The very first function that we will write will provide us the ability to show the player’s current score.
Let’s have a look at the following bit of code that illustrates the same thing, shall we? File: snake.py
Explanation:
-
# initial score
-
player_score =
0
-
-
# defining the functions
-
# function to display the score
-
def
display_score(selection, font_color, font_style, font_size):
-
-
# creating the font object
-
score_font_style = pygame.font.SysFont(font_style, font_size)
-
-
# creating the display surface object
-
score_surface = score_font_style.render(
‘Your Score : ‘
+ str(player_score),
True
, font_color)
-
-
# creating a rectangular object for the text placement
-
score_rectangle = score_surface.get_rect()
-
-
# displaying the text
-
display_screen.blit(score_surface, score_rectangle)
Related:
With the line of code that you just read, we have constructed a variable that will store the number 0 when it is first assigned to the score. Next, we went ahead and built a function called display score(), which takes in many arguments including the text that was chosen as well as its color, style, and size. Under the context of this function, a font object was produced by us. After that, we have made use of the render() method to produce a backdrop surface, which will undergo modifications anytime the score is revised. After that, we fashioned a rectangle object for use in the positioning of the text. At long last, we have successfully shown the score on the main screen by using the blit() technique.
screen.
Function to over the game
When the snake collides with a wall or with itself, the second function that we construct will take over, showing the final score and quitting the program.
Let’s have a look at the following bit of code that illustrates the same thing, shall we? File: snake.py
Explanation of
-
# function to over the game
-
def
game_over():
-
-
# creating the font object
-
game_over_font_style = pygame.font.SysFont(
‘times new roman’
,
50
)
-
-
# creating the display surface object
-
game_over_surface = game_over_font_style.render(
-
‘Your Score is : ‘
+ str(player_score),
True
, crimson_red
-
)
-
-
# creating a rectangular object for the text placement
-
game_over_rectangle = game_over_surface.get_rect()
-
-
# setting the position of the text
-
game_over_rectangle.midtop = (SCREEN_WIDTH/
2
, SCREEN_HEIGHT/
4
)
-
-
# displaying the text on the screen
-
display_screen.blit(game_over_surface, game_over_rectangle)
-
-
# using the flip() function to update the small portion of the screen
-
pygame.display.flip()
-
-
# suspending the execution of the current thread for 2 seconds
-
time.sleep(
2
)
-
-
# calling the quit() function
-
pygame.quit()
-
-
# quiting the application
-
quit()
Format:
The line of code that you just looked at contains the definition of a method that we called game over(). Within the context of this function, we have developed a font object in order to show the scores. In addition to that, we have developed text surfaces in order to represent the scores. After that, we made sure that the text was centered in the playable area by using the blit() technique, and we displayed the final scores on the screen that was previously utilized. After that, we made advantage of the flip() method to bring the score up to date by modifying the surface. At long last, we used the sleep() method of the time module to pause the execution of the currently active threat for two seconds, and then we used the quit() function to terminate the process.
application.
Creating the Game Loop to run the application
Now that we have completed all of the prerequisites for developing the game, it is time for us to write the primary function, also known as the game loop, in order to put the program into action. Because of this loop, everything that we have generated will be rendered, and both functions will be implemented properly.
Let us analyze the following bit of code, which demonstrates how the game loop should be implemented. File: snake.py
Explanation for W01A1@@9:
After that, in the preceding bit of code, we have changed the value of the game run flag to True and are now running the game with the help of the while loop. In this loop, we have iterated over the list of events and checked to see whether the player asked to exit the program. If they did, we have continued the process as before and changed the flag value to False. We have also determined whether or not the key is responsible for the movement of the snake, and we have established the unique condition that stipulates the snake should not be permitted to go in the opposite direction immediately. After that, we searched for the collision that occurred between the snake and the fruit, and when we found it, we added one to the score, which caused a fresh fruit to appear. After that, we checked to see whether the snake had collided with a wall, and if it had, we invoked the game over() method. In addition to that, we tested to see whether the snake was able to strike itself before calling the game over() method once again. After that, the display score() method was used so that the scores could be shown to the audience. After that, we refreshed the game screen by using the update() method, and we synchronized the game’s refresh rate with the snake’s movement pace. At long last, we have successfully exited the while loop and used the quit() method.
We are pleased to announce that the code for the Snake game has been successfully developed. We are now able to save the file, and in order to execute the program, we will need to type the following command into a command shell or terminal. Syntax:
-
$ python snake.py
But before we get to the section where we discuss the outcome, let’s take a quick look at the whole project code for the “Snake game using PyGame
“.
The Complete Project Code
The whole piece of code for the “Snake game using PyGame in Python” project is going to be shown to us today. File: snake.py
-
# importing the necessary modules
-
import
pygame
# importing the pygame module
-
import
time
# importing the time module
-
import
random
# importing the random module
-
-
# defining the speed of the snake
-
speed_of_snake =
15
-
-
# defining the size of the window
-
SCREEN_WIDTH =
700
-
SCREEN_HEIGHT =
460
-
-
# defining the colors
-
midnight_blue = pygame.Color(
25
,
25
,
112
)
-
mint_cream = pygame.Color(
245
,
255
,
250
)
-
crimson_red = pygame.Color(
220
,
20
,
60
)
-
lawn_green = pygame.Color(
124
,
252
,
0
)
-
orange_red = pygame.Color(
255
,
69
,
0
)
-
-
# initializing the pygame window using the pygame.init() function
-
pygame.init()
-
-
# using the set_mode() function of the pygame.display module to set the size of the screen
-
display_screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
-
-
# setting the title of the application using the set_caption() function
-
pygame.display.set_caption(
‘SNAKE – JAVATPOINT’
)
-
-
# creating an object of the Clock() class of the pygame.time module
-
game_clock = pygame.time.Clock()
-
-
# defining the default position of the snake
-
position_of_snake = [
100
,
50
]
-
-
# defining the first four blocks of snake body
-
body_of_snake = [
-
[
100
,
50
],
-
[
90
,
50
],
-
[
80
,
50
],
-
[
70
,
50
]
-
]
-
-
# position of the fruit
-
position_of_fruit = [
-
random.randrange(
1
, (SCREEN_WIDTH//
10
)) *
10
,
-
random.randrange(
1
, (SCREEN_HEIGHT//
10
)) *
10
-
]
-
spawning_of_fruit =
True
-
-
# setting the default direction of the snake towards RIGHT
-
initial_direction =
‘RIGHT’
-
snake_direction = initial_direction
-
-
# initial score
-
player_score =
0
-
-
# defining the functions
-
# function to display the score
-
def
display_score(selection, font_color, font_style, font_size):
-
-
# creating the font object
-
score_font_style = pygame.font.SysFont(font_style, font_size)
-
-
# creating the display surface object
-
score_surface = score_font_style.render(
‘Your Score : ‘
+ str(player_score),
True
, font_color)
-
-
# creating a rectangular object for the text placement
-
score_rectangle = score_surface.get_rect()
-
-
# displaying the text
-
display_screen.blit(score_surface, score_rectangle)
-
-
# function to over the game
-
def
game_over():
-
-
# creating the font object
-
game_over_font_style = pygame.font.SysFont(
‘times new roman’
,
50
)
-
-
# creating the display surface object
-
game_over_surface = game_over_font_style.render(
-
‘Your Score is : ‘
+ str(player_score),
True
, crimson_red
-
)
-
-
# creating a rectangular object for the text placement
-
game_over_rectangle = game_over_surface.get_rect()
-
-
# setting the position of the text
-
game_over_rectangle.midtop = (SCREEN_WIDTH/
2
, SCREEN_HEIGHT/
4
)
-
-
# displaying the text on the screen
-
display_screen.blit(game_over_surface, game_over_rectangle)
-
-
# using the flip() function to update the small portion of the screen
-
pygame.display.flip()
-
-
# suspending the execution of the current thread for 2 seconds
-
time.sleep(
2
)
-
-
# calling the quit() function
-
pygame.quit()
-
-
# quiting the application
-
quit()
-
-
# setting the run flag value to True
-
game_run =
True
-
-
# the game loop
-
# using the while loop
-
while
game_run:
-
# iterating through the events in the pygame.event module
-
for
event
in
pygame.event.get():
-
# setting the variable value to False if the event’s type is equivalent to pygame’s QUIT constant
-
if
event.type == pygame.QUIT:
-
# setting the flag value to False
-
game_run =
False
-
-
# setting the variable value either to UP, DOWN, LEFT, or RIGHT
-
# if the event’s type is equivalent to pygame’s KEYDOWN constant,
-
# and any of the stated keys is pressed
-
if
event.type == pygame.KEYDOWN:
-
if
event.key == pygame.K_UP:
-
snake_direction =
‘UP’
-
if
event.key == pygame.K_DOWN:
-
snake_direction =
‘DOWN’
-
if
event.key == pygame.K_LEFT:
-
snake_direction =
‘LEFT’
-
if
event.key == pygame.K_RIGHT:
-
snake_direction =
‘RIGHT’
-
-
# neglecting the action taken if the key of opposite direction is pressed
-
if
snake_direction ==
‘UP’
and
initial_direction !=
‘DOWN’
:
-
initial_direction =
‘UP’
-
if
snake_direction ==
‘DOWN’
and
initial_direction !=
‘UP’
:
-
initial_direction =
‘DOWN’
-
if
snake_direction ==
‘LEFT’
and
initial_direction !=
‘RIGHT’
:
-
initial_direction =
‘LEFT’
-
if
snake_direction ==
‘RIGHT’
and
initial_direction !=
‘LEFT’
:
-
initial_direction =
‘RIGHT’
-
-
# updating the position of the snake for every direction
-
if
initial_direction ==
‘UP’
:
-
position_of_snake[
1
] -=
10
-
if
initial_direction ==
‘DOWN’
:
-
position_of_snake[
1
] +=
10
-
if
initial_direction ==
‘LEFT’
:
-
position_of_snake[
0
] -=
10
-
if
initial_direction ==
‘RIGHT’
:
-
position_of_snake[
0
] +=
10
-
-
# updating the body of the snake
-
body_of_snake.insert(
0
, list(position_of_snake))
-
if
position_of_snake[
0
] == position_of_fruit[
0
]
and
position_of_snake[
1
] == position_of_fruit[
1
]:
-
# incrementing the player’s score by 1
-
player_score +=
1
-
spawning_of_fruit =
False
-
else
:
-
body_of_snake.pop()
-
-
# randomly spawning the fruit
-
if
not
spawning_of_fruit:
-
position_of_fruit = [
-
random.randrange(
1
, (SCREEN_WIDTH//
10
)) *
10
,
-
random.randrange(
1
, (SCREEN_HEIGHT//
10
)) *
10
-
]
-
spawning_of_fruit =
True
-
-
# filling the color on the screen
-
display_screen.fill(mint_cream)
-
-
# drawing the game objects on the screen
-
for
position
in
body_of_snake:
-
pygame.draw.rect(display_screen, lawn_green, pygame.Rect(position[
0
], position[
1
],
10
,
10
))
-
pygame.draw.rect(display_screen, orange_red, pygame.Rect(position_of_fruit[
0
], position_of_fruit[
1
],
10
,
10
))
-
-
# conditions for the game to over
-
if
position_of_snake[
0
] <
0
or
position_of_snake[
0
] > SCREEN_WIDTH –
10
:
-
game_over()
-
if
position_of_snake[
1
] <
0
or
position_of_snake[
1
] > SCREEN_HEIGHT –
10
:
-
game_over()
-
-
# touching the snake body
-
for
block
in
body_of_snake[
1
:]:
-
if
position_of_snake[
0
] == block[
0
]
and
position_of_snake[
1
] == block[
1
]:
-
game_over
-
-
# displaying the score continuously
-
display_score(
1
, midnight_blue,
‘times new roman’
,
20
)
-
-
# refreshing the game screen
-
pygame.display.update()
-
-
# refresh rate
-
game_clock.tick(speed_of_snake)
-
-
# calling the quit() function to quit the application
-
pygame.quit()
Output:
Picture 1 shows the final product of the Snake Game developed using PyGame.
Picture 2: The Mechanisms Behind the Snake Game
Picture 3: The End of the Game