PROJECT TO CREATE SNAKE GAME BY USING PYTHON
BY
[Link] ABIJITH AND [Link]
(SHRI GURUMUKI VIDHAYASSHARM)
DATEBASE TABLE :
Processor (CPU) Dual-core 2.0 GHz processor
Memory (RAM) At least 4 GB RAM
Storage A minimum of 5 GB of free space
Graphics Card (GPU) NVIDIA GPU (such as an RTX
series card)
Operating System Windows 10/11
INTRODUTION
Create Snake Game in Python – Snake Game Program using Pygame
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
the advent of smartphones. This is a very simple project in which the snake will
eat It’s the most famous game we used to play in our childhood before 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.
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.
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 = [Link]()
width_of_screen = 900
height_of_screen = 600
gameWindow =
[Link].set_mode((width_of_screen,height_of_screen))
[Link].set_caption("python snake game PythonGeeks")
[Link]()
clock = [Link]()
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
[Link](): It initializes all the imported modules of pygame for snake game.
[Link].set_mode(): It helps to set up the screen for display.
[Link].set_caption(): It displays the caption on the top of your screen.
[Link](): 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 = [Link](text, True , color)
[Link](screen_text,[x,y])
Code Explanation:
This function is defined to display snake game scores on the screen. [Link]()
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:
[Link]((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 [Link](): 5 | P a g e
if [Link]==[Link]:
game_exit = True
if [Link]==[Link]:
if [Link]==pygame.K_SPACE:
game()
[Link]()
[Link](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.
[Link](): It returns the list of all events that are unprocessed.
[Link](): It checks whether we are in the game or not.
[Link](): 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= 60
init_velocity = 5
score= 0
apple_x = [Link](20,width_of_screen/2)
apple_y = [Link](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 ("[Link]","r") as f:
highscore = [Link]()
while not game_exit:
if game_over:
with open ("high [Link]","w") as f: 7
[Link](str(highscore))
[Link](white)
score_on_screen("Game Over! Press Enter to continue",red,100,250)
for event in [Link]():
if [Link] == [Link]:
game_exit = True
if [Link]== [Link]:
if [Link] == pygame.K_RETURN:
welcome()
Code Explanation:
[Link] 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
[Link]().
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 [Link]():
if [Link] == [Link]:
game_exit = True
if [Link]==[Link]:
if [Link] == pygame.K_RIGHT:
velocity_x = init_velocity
velocity_y = 0
if [Link] == pygame.K_LEFT:
velocity_x = -init_velocity
velocity_y = 0
if [Link] == pygame.K_UP:
velocity_y = -init_velocity
velocity_x = 0
if [Link] == 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 = [Link](20,width_of_screen/2)
apple_y = [Link](20,height_of_screen/2)
snake_length+=5
if score>int(highscore):
highscore = score
[Link](white)
score_on_screen("Score: "+str(score) + " highscore:
"+str(highscore),red,5,5)
[Link](gameWindow,red,[apple_x,apple_y,snake_size,snake_siz
e])
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=[]
[Link](snake_x)
[Link](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:
[Link](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)
[Link](gameWindow,black,[snake_x,snake_y,snake_size,snake_
size])
[Link]()
[Link](fps)
[Link]()
quit()
welcome()