Snake Game in Python - Using Pygame Module - Final
Snake Game in Python - Using Pygame Module - Final
module
Introduction:
Snake game is one of the most popular arcade games of all time. In this game, the main
objective of the player is to catch the maximum number of fruits without hitting the wall or
itself. Creating a snake game can be taken as a challenge while learning Python or Pygame. It
is one of the best beginner-friendly projects that every novice programmer should take as a
challenge. Learning to build a video game is kinda interesting and fun learning.
We will be using Pygame to create this snake game. Pygame is an open-source library that is
designed for making video games. It has inbuilt graphics and sound libraries. It is also beginner-
To install Pygame, you need to open up your terminal or command prompt and type the
After installing Pygame we are ready to create our cool snake game.
After that, we are defining the width and height of the window in which the game will be
played.
And define the color in RGB format that we are going to use in our game for displaying
text.
Python3:
# importing libraries
import pygame import
time import random
snake_speed = 15
# Window size
window_x = 720
window_y = 480
Step 2: After importing libraries we need to initialize Pygame using pygame.init() method.
Create a game window using the width and height defined in the previous step. Here
pygame.time.Clock() will be used further in the main logic of the game to change the
speed of the snake.
Python3
# Initialising pygame
pygame.init()
Initialise game window
pygame.display.set_caption('GeeksforGeeks Snakes')
game_window = pygame.display.set_mode((window_x, window_y))
# FPS (frames per second) controller fps
= pygame.time.Clock()
▲
Step 3: Initialize snake position and its size.
After initializing snake position, initialize the fruit position randomly anywhere in the
defined height and width.
By setting direction to RIGHT we ensure that, whenever a user runs the program/game,
the snake must move right to the screen.
Python3
In this function, firstly we’re creating a font object i.e. the font color will go here. Then we
are using render to create a background surface that we are going to change whenever
our score updates.
Create a rectangular object for the text surface object (where text will be refreshed)
Then, we are displaying our score using blit. blit takes two argument
screen.blit(background,(x,y))
Python3
# initial score
score = 0
▲
score_rect = score_surface.get_rect()
# displaying text
game_window.blit(score_surface, score_rect)
Step 5: Now create a game over function that will represent the score after the snake is hit by
a wall or itself.
Python3
# game over function def
game_over():
Step 6: Now we will be creating our main function that will do the following things:
We will be validating the keys that will be responsible for the movement of the snake,
then we will be creating a special condition that the snake should not be allowed to move
in the opposite direction instantaneously.
After that, if snake and fruit collide we will be incrementing the score by 10 and new fruit
will be spanned.
After that, we are checking that is the snake hit with a wall or not. If a snake hits a wall we
will call game over function.
If the snake hits itself, the game over function will be called.
And in the end, we will be displaying the scores using the show_score function created
earlier.
Python3
# Main Function
while True:
Python3
# importing libraries
import pygame import
time import random
snake_speed =
15
# Window size
window_x = 720
window_y = 480
# Initialising pygame
pygame.init()
▲
random.randrange(1, (window_y//10)) * 10]
fruit_spawn = True
# initial score
score = 0
# displaying Score function def
show_score(choice, color, font, size):
# displaying text
game_window.blit(score_surface, score_rect)
# game over function def
game_over():
# Main Function
while True:
Output:
Code Explanation:
1. The code starts by importing the necessary libraries.
2. These are pygame, time, and random.
3. Next, the code defines some variables.
4. The snake_speed variable controls how fast the snake moves around the screen.
5. The window_x and window_y variables define the size of the game window onscreen.
6. The next line of code initializes pygame.
7. This is important because it sets up all of the game objects and their properties so that
they can be used later in the program.
8. Next, the code creates an instance of pygame’s GameWindow class object.
9. This object represents a rectangular area onscreen that can be filled with graphics and
text content.
10. The GameWindow object has two properties: width and height .
11. These values represent how wide and tall the game window is respectively.
12. The next line of code assigns values to these properties based on a user-defined value
called snake_speed .
13. This variable tellspygame how fast (in pixels per second) to move the snake aroundthe
screen. 14. Higher values will make for faster movement but also more intense
gameplay!
15. Next, PyGame starts loading various ges into memoryy to uyse as background graphics for
our game world .
16 First it loads in an
17. The code will create a window with dimensions of 720×480 pixels.
18. The colours black, white, red, green and blue will be used to represent the game’s
various elements.
19. Next, the pygame module will be imported and initialized.
20. This will allow us to start working with the game’s various objects and functions.
21. The game’s main loop will then be started by calling pygame.init().
22. This function will ensure that all of the necessary modules are loaded and ready for use.
23. Finally, we’ll call the window’s constructor to create our game window.
24. The code starts by creating a pygame.display.set_mode() function to set the window size
and position.
25. The code then creates a game window and sets its mode to (0, 0).
26. Next, the code defines some variables: fps, snake_position, snake_body, and
fruit_position.
27. These variables will be used to control the speed of the snake, where it starts from
(snake_position), how wide it is (snake_body), where the fruit is located (fruit_position),
and whether or not fruit should spawn (fruit_spawn).
28. The next block of code calculates the distance between each point on the screen using
pygame.time.Clock().
29. This allows us to move the snake around on-screen without having to constantly
recalculate its position.
30. Finally, we set up two boolean variables: fruit_spawn and analyze().
31. These will determine whether or not fruit will spawn at random locations onscreen and
be analyzed for player input.
32. The code sets up a basic game window with a snake positioned at (100, 50) on the X-axis
and (window_x, window_y) on the Y-axis.
33. The FPS controller is initialized and set to run at 60 frames per second.
34. The next block of code defines the body of the snake.
35. A list of ten [100, 50] points is created, starting at position (100, 50).
▲
36. The first four points are set to be in the center of the snake’s body while the remaining
six points are evenly spaced around it.
37. Next, a fruit position is defined as [(random.randrange(1, (window_x//10)) * 10),
(random.randrange(1
38. The code starts by initializing some variables.
39. The first is the score, which starts at 0. 40. The second is the direction variable, which
will determine how the snake moves.
▲
67. Next, a rectangular object called game_over_rect is created.
68 This object will be used to position the text on the surface.
69. The midpoint of the rectangle is set to (window_x/2, window_y/4).
70. The code starts by initializing the pygame library.
71. Next, the code creates a window and assigns it to game_window.
72. The window has a surface (a graphic representation of the screen) and a Rectangle object
that specifies its size and position.
73. Next, the code blits (transfers) the text “GAME OVER” onto the game_over_surface
object.
74. The text is drawn in white, centered on top of the game_over_rect object.
75. The program then sets up a timer that will run for 2 seconds.
76. At this point, the program will quit because there is no more code to execute.
77. The code will check for key events and if the event corresponds to a valid key, it will
change the text displayed on screen accordingly.
78. If you press any other key, the program will continue to run as normal.
79. The code starts by checking to see if the player has pressed two keys at the same time.
80. If they have, the code changes the direction of the snake.
81. Next, the code checks to see if either key was pressed in a different direction than
expected.
82. If it was, then the code adjusts the position of the snake accordingly.
83. Finally, it updates how big the snake’s body is getting.
84. The code will check if the two keys being pressed at the same time are either ‘UP’ or
‘DOWN’.
85. If they are, then the direction of the snake will be changed accordingly.
86. If the two keys being pressed are not equal, then the code will check to see if they are
different directions.
87. If they are not, then the snake’s position will be adjusted by 10 pixels in each direction.
88. Lastly, a function is created that will change how big the snake’s body grows when it
moves.
89. The code starts by creating a list of snake positions.
90. The first position in the list is at (0, 0), and the last position in the list is at (window_x-10,
window_y-10).
91. Next, the code checks to see if any of the positions in the snake are equal to a fruit
position.
92. If so, then that fruit gets scored 10 points and is added to the fruit spawn variable.
▲
93. If no fruits are found, then the game moves on to checking for collisions betweens snakes
and fruits.
▲
94 If two snakes intersect, then their scores are incremented by 10.
95. If a snake collides with a wall or another snake, then that snake dies and game over
conditions are triggered.
96. Finally, touching any part of a snake causes it to die and also triggers game over
conditions.
97. The code will check to see if two positions in the snake body are equal.
98. If they are, then the score is incremented by 10 and the game_over() function is called.
99. If a player touches the snake body at any point, then the game_over() function will be
called
100.
Related Articles