You are on page 1of 36

Snake Game

A
Project Report
SUBMITTED TO THE
Integrated Institute of Technology
(Affiliated to GGSIPU)

In Partial Fulfilment of the Requirements


For the award of the degree of
Bachelor of Computer Application

SUBMITTED BY
NAVEEN KUMAR
04750102019

UNDER THE GUIDANCE OF


MR. ARUN DABAS
<<Designation>>

DEPARTMENT OF COMPUTER SCIENCE


Integrated Institute of Technology,
Sector 9, Dwarka, New Delhi
2021
Snake Game

Name of Student – NAVEEN KUMAR

Registration Number- 04750102019

Name of Guide- MR. ARUN DABAS

Designation-

Student’s Signature Guide Signature


DECLARATION

I hereby declare that the project work entitled “SNAKE GAME” submitted to
Integrated Institute of Technology, Dwarka, is a record of an original work done
by me under the guidance of “ARUN DABAS”. This project work is submitted in
the partial fulfilment of the requirements for the award of the degree of Bachelor
of Computer Application. The results embodied in this report have not been
submitted to any other University or Institute for the award of any degree or
diploma.

Signature of Candidate

Name of the student NAVEEN KUMAR

University Enrollment No. 0475012019


ACKNOWLEDGEMENT

I, NAVEEN KUMAR would like to sincerely thank Integrated Institute of


Technology, DWARKA for providing me an opportunity for this internship which
has enhanced my knowledge on this area.
I take this opportunity to express my gratitude to the people who have been
instrumental in the successful completion of my report.
Above all, I would like to thank almighty God for his blessings and my family who
have been a constant source of support &inspiration.

NAVEEN KUMAR,
04750102019
INTRODUCTION

Overview:
Snake game is one of the most popular arcade games of all time. In this project,
we will be using PYGMAE to create this snake game.
PYGAME is an open-source library that is designed for making video games. It has
inbuilt graphics and sounds libraries. It is also beginner-friendly, and cross-
platform.
How to play the game:
The main objective of the player is to catch the maximum number of fruits
without hitting the wall or itself.
The snake can be controlled by the keyboard UP key to move Upward, DOWN key
to move Downward, LEFT key to move Left and RIGHT key to move Right.
What is Python?
Python is a computer programming language often used to build websites and
software, automate tasks, and conduct data analysis. Python is a general purpose
language, meaning it can be used to create a variety of different programs and
isn’t specialized for any specific problems. This versatility, along with its beginner-
friendliness, has made it one of the most-used programming languages today. A
survey conducted by industry analyst firm RedMonk found that it was the most
popular programming language among developers in 2020.

What is Python used for?


Python is commonly used for developing websites and software, task
automation, data analysis, and data visualization. Since it’s relatively easy to
learn, Python has been adopted by many non-programmers such as accountants
and scientists, for a variety of everyday tasks, like organizing finances.

Areas in which Python is used very dominantly-

1. Data Analysis and Machine Learning: Python has become a staple in data
science, allowing data analysis and other professionals to use the language
to conduct complex statistical calculations, create data visualizations,
build machine learning algorithms, manipulate and analyze data, and
complete other data-related tasks.

2. Web Development: Python is often used to develop the back end of a


website or application—the parts that a user doesn’t see. Python’s role in
web development can include sending data to and from servers,
processing data and communicating with databases, URL routing, and
ensuring security. Python offers several frameworks for web development.
Commonly used ones include Django and Flask.
3. Automation or scripting: We could work more efficiently by automating it
with Python. Writing code used to build these automated processes is
called scripting. In the coding world, automation can be used to check for
errors across multiple files, convert files, execute simple math, and
remove duplicates in data.
Python can even be used by relative beginners to automate simple tasks on
the computer—such as renaming files, finding and downloading online
content or sending emails or texts at desired intervals.

4. Software testing and prototyping: In software development, Python can


aid in tasks like build control, bug tracking, and testing. With Python,
software developers can automate testing for new products or features.
Some Python tools used for software testing include Green and
Requestium.

5. Game Development: PYGAME: "the original and still very much active
package for game development using Python. It allows Python to talk
to SDL, a cross-platform, multimedia library. Because it needs to be
compiled for each platform and each Python version, there can be a lag
when a new Python version comes along."
Methods used in Making of the Snake Game-

1. Functions: In Python, a function is a group of related


statements that performs a specific task. Functions help break
our program into smaller and modular chunks. As our program
grows larger and larger, functions make it more organized and
manageable.

2. Loops: A loop statement allows us to execute a statement


or group of statements multiple times. Some loops used in
the program is:

 While Loop: Repeats a statement or group of statements


while a given condition is TRUE. It tests the condition before
executing the loop body.
 For Loop: Executes a sequence of statements multiple
times and abbreviates the code that manages the loop
variable.

3. Classes: A class is a user-defined blueprint or prototype from


which objects are created. Classes provide a means of
bundling data and functionality together. Creating a new class
creates a new type of object, allowing new instances of that
type to be made. Each class instance can have attributes
attached to it for maintaining its state. Class instances can also
have methods (defined by their class) for modifying their state.

4. Conditional Statements: Conditional Statement in Python


perform different computations or actions depending on whether
a specific Boolean constraint evaluates to true or false.
Conditional statements are handled by IF statements in Python.
5. Objects: An Object is an instance of a Class. A class is like a
blueprint while an instance is a copy of the class with actual
values. It’s not an idea anymore, it’s an actual dog, like a dog of
breed pug who’s seven years old. You can have many dogs to
create many different instances, but without the class as a guide,
you would be lost, not knowing what information is required.

6. Inheritance: Inheritance is the capability of one class to derive or


inherit the properties from another class. The benefits of
Inheritance are:
 It represents real-world relationships well.

 It provides reusability of a code. We don’t have to write the


same code again and again. Also, it allows us to add more
features to a class without modifying it.

 It is transitive in nature, which means that if class B inherits


from another class A, then all the subclasses of B would
automatically inherit from class A

Different forms of Inheritance:


 Single inheritance: When a child class inherits from
only one parent class, it is called single inheritance.
We saw an example above.

 Multiple inheritance: When a child class inherits from


multiple parent classes, it is called multiple
inheritance.
 Multilevel inheritance: When we have a child and
grandchild relationship.
 Hierarchical inheritance: More than one
derived classes are created from a single base.

 Hybrid inheritance: This form combines more than one


form of inheritance. Basically, it is a blend of more
than one type of inheritance.

7. Constructors: Constructors are generally used for instantiating an


object. The task of constructors is to initialize(assign values) to the
data members of the class when an object of the class is created.
In Python the init () method is called the constructor and is
always called when an object is created.
Syntax:
def init (self):
# body of the constructor

Types of constructors:
 Default constructor: The default constructor is a
simple constructor which doesn’t accept any
arguments. Its definition has only one argument which
is a reference to the instance being constructed.
 Parameterized constructor: constructor with
parameters is known as parameterized constructor.
The parameterized constructor takes its first argument
as a reference to the instance being constructed
known as self and the rest of the arguments are
provided by the programmer.
8. List Slicing: In Python, list slicing is a common practice and it is
the most used technique for programmers to solve efficient
problems. Consider a python list, In-order to access a range of
elements in a list, you need to slice a list. One way to do this is to
use the simple slicing operator i.e. colon(:)
List_name[ Starting_index : Stop_index : Step ]
Python Modules used in the project

1. PYGAME Module: PYGAME is a cross-platform set of Python modules


designed for writing video games. It includes computer graphics and
sound libraries designed to be used with the Python programming
language.

2. Random Module: The random module is a built-in module to generate


the pseudo-random variables. It can be used perform some action
randomly such as to get a random number, selecting a random elements
from a list, shuffle elements randomly, etc.

3. SYS Module: The sys module in Python provides various functions and
variables that are used to manipulate different parts of the Python
runtime environment.
Installations of the module in the IDE

1. PYGAME: To install PYGAME in your IDE, open the terminal of your IDE
and in the terminal write this command:
pip install pygame

2. Random Module: Random module comes built in the environment. So


just import the module in your file.

3. SYS Module: SYS module comes built in the environment. So just


import the module in your file.
IDE Used in the Project

VS Code: Visual Studio Code (famously known as VS Code) is a


free open source text editor by Microsoft. VS Code is available for
Windows, Linux, and macOS. Although the editor is relatively
lightweight, it includes some powerful features that have made
VS Code one of the most popular development environment tools
in recent times.

Features of VS Code:
VS Code supports a wide array of programming languages from
Java, C++, and Python to CSS, Go, and Dockerfile. Moreover, VS
Code allows you to add on and even creating new extensions
including code linters, debuggers, and cloud and web
development support.

The VS Code user interface allows for a lot of interaction


compared to other text editors. To simplify user experience, VS
Code is divided into five main regions:

 The activity bar


 The side bar
 Editor groups
 The panel
 The status bar
Work Flow of the Game:

 First we have to import the required module from the python


library.
import pygame
import sys
import random
from pygame.math import Vector2

 Now we have to set some CONSTANTS, such as width, height of


the game window.

 Setting up the window:


Everything in the game is the image drawn on the surface
(window), the image drawn on the screen is very fast. So its
feel like a smooth game is running
To set the surface we use the pygame functions:
screen = pygame.display.set_mode((width,height)):This
function will create a display Surface. The arguments passed
in are requests for a display type. The actual created display
will be the best possible match supported by the system.

pygame.display.set_caption(“Title of the game”):Set the


current window caption.
 Loading all the required Images and Fonts for the game in the
code:
Importing Images
Pygame.image.load(“The image path in the directory”):
Load an image from a file source. You can pass either a
filename, a Python file-like object, or a pathlib.Path.

Importing Fonts file:


Pygame.font.Font(“The font file path in the directory”):
This function will load the font file in the code.

 Everything in pygame is run in the infinite loop: The reason for it


that every time any movement happens in the game then the
new image is drawn on the screen, but the process is very fast
human eye cannot detect the drawing of the image so its feel like
a smooth video game is running.

 How to exit from the game: As the above explained the game
runs in an infinite loop, then to exit from the game, pygame
has provided an method to do so.

1. To exit first we have to create a “for loop” to check the


every input coming from the user.
2. After getting the input, we check all the input using
conditional statements to know that if user has click
on the “close button”, and if that’s true then we break
the loop and use the pygmae function to quit the
game.
Here is the code for exiting from the game:

for event in pygame.event.get():


if event.type == pygame.QUIT:
pygame.quit()
sys.exit()

 Drawing the Images on the screen: As explained before all the


things we saw on the screen is the images are drawn by the
pygame.
Pygame method to draw images on the screen:

screen.blit(image,(positon_x,position_Y)): The blit function


draws the images of the screen. It take two arguments.

1. First it take the image we want to draw on to


the screen.
2. The second argument it take is a tuple in which the
x and y location of the image is specified, where we
want to draw the image on the screen

 Taking the inputs from the user: To move the snake around the
screen to reach the fruits. We have to get the access of the every
key pressed by the user on the keyboard. After getting the user
input we have to check for the specific input is pressed or not. If
the user press UP key than we call another pygame function
which control the object on the screen and manipulate the
snake using that function.
Here how we do the above logic in the code:
1. First accessing the every input from the user:
for event in pygame.event.get():

2. Check if user have press any button on the keyboard:


if event.type == pygame.KEYDOWN:

3. Check the if the user have pressed the


UP,DOWN,LEFT,RIGHT buttons on the keyboard
if event.key == pygame.K_UP:

4. Now we what key is pressed by the user, if the user


pressed UP button than we decrease the snake Y
location. And since the every time image is drawn on
the screen, the new image will be drawn on the
upward position from before position. And it will feel
like the snake has move upward.

 Random position of the fruit on the screen: Since in the snake


game the fruit/food comes in different position on the screen,
after eaten by the snake. We can do this easily.
1) First we have to check the if the snake and
food has collided or not.

2) For this we can just get the position of the snake


and the food at any moment. If both position
happens to same. Than that means the snake
has collided with the food.
3) If the snake is collided with the food, then we
remove the image of the food from the
screen and draw it on other random location.

4) We have already seen how to draw the image on


the screen. So now we have to know how to get
the random position on screen to draw the food.
We can do this using random module.

5) Random module provide a function called


randint, which will provide the random number
between the range we provided to it.

6) So we can use randint function to get random


number and store in a variable say, x and y.

7) After getting the random function we can pass


these value in the blit function to draw the fruit
on the new location.

 The collision of the Snake with the wall.


When the snake hit the wall of the window then snake dies
and game is over. The method of detecting the collision
between the snake and wall is same as detecting the
collision between the snake and the food. So after checking
that snake and wall has collided we can quit the game. We
can quit game in two manner. First we can break the loop
using the “break” keyword in the main loop. Or we can use
“Sys” module to quit the game. We can just call “sys.exit()”
function and this function automatically terminate the
screen.

 Detection of the snake head with its own body:

In snake game, if snake bit itself than the game is over.

So first we detect the collision of the snake head and body


by the method explained before. Than we quit the game, as
mentioned above.

 Keeping the score on the screen:


In snake game if the snake eat the food the score is
increased by one point.
We can do the same using the pygame game_font method.
1) First we check if the snake has collided with the food
or not. Because if snake collided with the food than
its means that snake has eaten the food.
2) If the snake has eaten the food, than we will call our
user defined function in which we handle the score the
section of the game, also when snake eat food we
increment a variable called score with one and draw it
along the score text.
3) In our function, we use pygame method to store text
in the variable.
score_surface=game_font.render(score
_text,True,(56,74,12))

4) Then we will draw this score text on the screen


using blit function.
Code:
import pygame

from pygame.math import Vector2

import sys

import random

pygame.init()

cell_size = 30

cell_num = 20

APPLE = pygame.image.load("Graphics/apple.png")

game_font = pygame.font.Font("Font/PoetsenOne-Regular.ttf",25)

screen = pygame.display.set_mode((cell_size * cell_num,cell_size *


cell_num))

pygame.display.set_caption("Snake Game")

clock = pygame.time.Clock()

class FRUIT:

def init (self) -> None:


#create an x and y positon

self.randomize()

#create a square on the screen

def draw_fruit(self):

#create a rectangle

fruit_rect = pygame.Rect(int(self.pos.x * cell_size),int(self.pos.y *


cell_size),cell_size,cell_size)

screen.blit(APPLE,fruit_rect)

def randomize(self):

self.x = random.randint(0,cell_num - 1)

self.y = random.randint(0,cell_num - 1)

self.pos = Vector2(self.x,self.y)

class SNAKE():

def init (self) -> None:

self.body = [Vector2(5,5),Vector2(4,5),Vector2(3,5)]

self.direction = Vector2(1,0)
self.new_block = False

self.head_up =
pygame.image.load('Graphics/head_up.png').convert_alpha()

self.head_down =
pygame.image.load('Graphics/head_down.png').convert_alpha()

self.head_right =
pygame.image.load('Graphics/head_right.png').convert_alpha()

self.head_left =
pygame.image.load('Graphics/head_left.png').convert_alpha()

self.tail_up =
pygame.image.load('Graphics/tail_up.png').convert_alpha()

self.tail_down =
pygame.image.load('Graphics/tail_down.png').convert_alpha()

self.tail_right =
pygame.image.load('Graphics/tail_right.png').convert_alpha()

self.tail_left =
pygame.image.load('Graphics/tail_left.png').convert_alpha()

self.body_vertical =
pygame.image.load('Graphics/body_vertical.png').convert_alpha()
self.body_horizontal =
pygame.image.load('Graphics/body_horizontal.png').convert_alpha()

self.body_tr =
pygame.image.load('Graphics/body_tr.png').convert_alpha()

self.body_tl =
pygame.image.load('Graphics/body_tl.png').convert_alpha()

self.body_br =
pygame.image.load('Graphics/body_br.png').convert_alpha()

self.body_bl =
pygame.image.load('Graphics/body_bl.png').convert_alpha()

def draw_snake(self):

self.update_head_graphics()

self.update_tail_graphics()

for index,block in enumerate(self.body):

# we still need a rect for the positioning

pos_x = int(block.x * cell_size)


pos_y = int(block.y * cell_size)

block_rect = pygame.Rect(pos_x,pos_y,cell_size,cell_size)

# direction of the head

if index == 0:screen.blit(self.head,block_rect)

elif index == len(self.body) - 1:

screen.blit(self.tail,block_rect)

else:

previous_block = self.body[index + 1] - block

next_block = self.body[index - 1] - block

if previous_block.x ==
next_block.x:screen.blit(self.body_vertical,block_rect)

elif previous_block.y == next_block.y:

screen.blit(self.body_horizontal,block_rect)

else:

if previous_block.x == -1 and next_block.y == -1 or


previous_block.y == -1 and next_block.x == -1:

screen.blit(self.body_tl,block_rect)

elif previous_block.x == -1 and next_block.y == 1 or


previous_block.y == 1 and next_block.x == -1:

screen.blit(self.body_bl,block_rect)
elif previous_block.x == 1 and next_block.y == -1 or
previous_block.y == -1 and next_block.x == 1:

screen.blit(self.body_tr,block_rect)

elif previous_block.x == 1 and next_block.y == 1 or


previous_block.y == 1 and next_block.x == 1:

screen.blit(self.body_br,block_rect)

def update_head_graphics(self):

head_relation = self.body[1] - self.body[0]

if head_relation == Vector2(1,0): self.head = self.head_left

elif head_relation == Vector2(-1,0): self.head = self.head_right

elif head_relation == Vector2(0,1): self.head = self.head_up

elif head_relation == Vector2(0,-1): self.head = self.head_down

def update_tail_graphics(self):

tail_relation = self.body[len(self.body) - 2] - self.body[len(self.body)


- 1]

if tail_relation == Vector2(1,0): self.tail = self.tail_left

elif tail_relation == Vector2(-1,0): self.tail = self.tail_right

elif tail_relation == Vector2(0,1): self.tail = self.tail_up

elif tail_relation == Vector2(0,-1): self.tail = self.tail_down


def move_snake(self):

if self.new_block:

body_copy = self.body[:]

body_copy.insert(0,body_copy[0] + self.direction)

self.body = body_copy[:]

self.new_block = False

else:

body_copy = self.body[:-1]

body_copy.insert(0,body_copy[0] + self.direction)

self.body = body_copy[:]

def add_block(self):

self.new_block = True

def reset(self):

self.body = [Vector2(5,5),Vector2(4,5),Vector2(3,5)]
class MAIN():

def init (self) -> None:

self.snake = SNAKE()

self.fruit = FRUIT()

def update(self):

self.snake.move_snake()

self.check_collision()

self.check_fail()

def draw_elements(self):

self.fruit.draw_fruit()

self.snake.draw_snake()

self.draw_score()

def check_collision(self):

if self.fruit.pos == self.snake.body[0]:

# changing the position of the fruit

self.fruit.randomize()

# add the block on the snake body


self.snake.add_block()

def check_fail(self):

# check if snake outside of screen

if not 0 <= self.snake.body[0].x < cell_num:

self.game_over()

elif not 0 <= self.snake.body[0].y < cell_num:

self.game_over()

# check if snake bit himself

for block in self.snake.body[1:]:

if block == self.snake.body[0]:

self.game_over()

def game_over(self):

self.snake.reset()

def draw_score(self):

score_text = str(len(self.snake.body) - 3)

score_surface = game_font.render(score_text,True,(56,74,12))
score_x = int(cell_size * cell_num - 60)

score_y = int(cell_num * cell_size - 40)

score_rect = score_surface.get_rect(center = (score_x,score_y))

apple_rect = APPLE.get_rect(midright =
(score_rect.left,score_rect.centery))

screen.blit(score_surface,score_rect)

screen.blit(APPLE,apple_rect)

main_game = MAIN()

SCREEN_UPDATE = pygame.USEREVENT

pygame.time.set_timer(SCREEN_UPDATE,150)

while True:

for event in pygame.event.get():

if event.type == pygame.QUIT:

pygame.quit()

sys.exit()

if event.type == SCREEN_UPDATE:
main_game.update()

if event.type == pygame.KEYDOWN:

if event.key == pygame.K_UP:

if main_game.snake.direction.y !=1:

main_game.snake.direction = Vector2(0,-1)

if event.key == pygame.K_DOWN:

if main_game.snake.direction.y !=-1:

main_game.snake.direction = Vector2(0,+1)

if event.key == pygame.K_LEFT:

if main_game.snake.direction.x !=1:

main_game.snake.direction = Vector2(-1,0)

if event.key == pygame.K_RIGHT:

if main_game.snake.direction.x !=-1:

main_game.snake.direction = Vector2(+1,0)

screen.fill((175,215,70))

main_game.draw_elements()

pygame.display.update()

clock.tick(60)
Results and Findings
Conclusion

By using the defined technologies, we have created a Snake Game, right


now we are developing new game. By making this snake game we have
get a lot of insight of python language itself. We have gone from no
knowledge to learn basic python to make small basic games to make this
snake game.

You might also like