Create Snake Game in Python
Create Snake Game in 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.
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.
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.