Main Report v1
Main Report v1
A. Basic Introduction
a. Objective of the project: The end-goal of this project is to utilize the skills
developed during the training and implement them in developing a “Road
Rush” visual game with use of pygame module of python.
b. Our role in the project: I was the main planner and coder of this project. I
was responsible for deciding how the game was going to function and the
aesthetic choices for the game. After the planning phase, I imported all the
necessary modules and start coding the main program while Achint was the
tester and main debugger.
c. Concept of the Project: The project is developed using the pygame module
of the python language. The game gives the player the control of an car in the
oncoming lane on a freeway, leading to an wild environment where the player
needs to avoid the oncoming car for as long as possible to build up a score.
The number of oncoming cars and their positions are randomly generated
making for an interesting challenge for the user.
d. Limitations of the project: The game after completion is still in beta stage
with many place holders and may be susceptible to frequent lag on an
incompatible system and is held back by the single player only environment.
The loading of the cars is not smooth and the recording of the saves may be
inconsistent.
Page | 1
B. Software Used
OS X El Capitan (10.11+)
Windows 8.0, 8.1 and 10, 11 (32-bit and 64-bit)
Linux (Debian): Ubuntu Desktop 16.04, Debian 9
Linux (Red Hat): Red Hat Enterprise Linux 7, CentOS 7, Fedora 34
Visual Studio Code is a small download (< 200 MB) and has a disk footprint of <
500 MB. VS Code is lightweight and should easily run on today's
hardware.We recommend:
Page | 2
Python is a multi-paradigm programming language. Object-oriented
programming and structured programming are fully supported, and many of their
features support functional programming and aspect-oriented
programming (including metaprogramming and metaobjects). Many other paradigms
are supported via extensions, including design by contract and logic programming.
Python uses dynamic typing and a combination of reference counting and a cycle-
detecting garbage collector for memory management. It uses dynamic name
resolution (late binding), which binds method and variable names during program
execution.
Its design offers some support for functional programming in the Lisp tradition. It
has filter , map and reduce functions; list comprehensions, dictionaries, sets,
and generator expressions. The standard library has two modules
( itertools and functools ) that implement functional tools borrowed
from Haskell and Standard ML.
Its core philosophy is summarized in the document The Zen of Python (PEP 20),
which includes aphorisms such as:
Page | 3
A common neologism in the Python community is pythonic, which has a wide range
of meanings related to program style. "Pythonic" code may use Python idioms well,
be natural or show fluency in the language, or conform with Python's minimalist
philosophy and emphasis on readability. Code that is difficult to understand or reads
like a rough transcription from another programming language is called unpythonic.
Python users and admirers, especially those considered knowledgeable or
experienced, are often referred to as Pythonistas.
Operating Systems:
Windows 7 or 10
Mac OS X 10.11 or higher, 64-bit
Linux: RHEL 6/7, 64-bit (almost all libraries also work in Ubuntu)
CPU Architecture:
Dual-core Intel Core i5 or similar
Graphics card
x86 64-bit CPU (Intel / AMD architecture)
RAM and free disk space:
4 GB RAM
5 GB free disk space
c. Pygame:-
Pygame is a set of Python modules designed for writing video games. Pygame
adds functionality on top of the excellent SDL library. This allows you to
create fully featured games and multimedia programs in the python language.
Pygame is highly portable and runs on nearly every platform and operating
system.
Pygame itself has been downloaded millions of times.
Pygame is free. Released under the LGPL licence, you can create open source,
freeware, shareware, and commercial games with it.
Pygame was originally written by Pete Shinners to replace PySDL after its
development stalled. It has been a community project since 2000 and is
released under the free software GNU Lesser General Public License (which
"provides for Pygame to be distributed with open source and commercial
software").
Pygame uses the Simple DirectMedia Layer (SDL) library, with the intention
of allowing real-time computer game development without the low-
level mechanics of the C programming language and its derivatives. This is
based on the assumption that the most expensive functions inside games can
be abstracted from the game logic, making it possible to use a high-level
programming language, such as Python, to structure the game.
Other features that SDL does have include vector math, collision detection, 2D
sprite scene graph management, MIDI support, camera, pixel-array
Page | 4
manipulation, transformations, filtering, advanced freetype font support, and
drawing.
Applications using Pygame can run on Android phones and tablets with the
use of Pygame Subset for Android (pgs4a). Sound, vibration, keyboard, and
accelerometer are supported on Android.
C. Methodology
Page | 5
a. Python PyGame
PyGame library is used to create video games. This library includes several modules
for playing sound, drawing graphics, handling mouse inputs, etc. It is also used to
create client-side applications that can be wrapped in standalone executables.
Installation
The best way to install pygame is with the pip tool, we can install pygame by using
the below command:
pip install pygame
Importing the Pygame library
To import the pygame library, make sure you have installed pygame already. Open
the terminal or the IDE which you want to work upon and import this library to
check whether pygame is installed or not by using the command given below:
import pygame
This library imports all the available pygame modules into the pygame package.The
below image how to perform it with the help of a command prompt. If you don’t
find any error and get the message as shown in the image means the pygame library
is imported successfully, and now you are good to proceed.
Page | 6
pygame.QUIT: This is used to terminate the event when we click on the close
button at the corner of the window.
tick():Pygame clock is used to track the time.
tick_busy_loop():The tick_busy_loop() is same as the tick(). By calling
the Clock.tick_busy_loop(20) once per frame, the program will never run at more
than 20 frames per second.
get_time():The get_time() is used to get the previous tick. The number of a
millisecond that isdra passed between the last two calls in Clock.tick().
Advanced Functions
surface = pygame.Surface((100,100))
The above line creates a blank 24-bit RGB image that's 100*100 pixels with the
default black color.
surface = pygame.Surface((100,100), pygame.SRCALPHA)
Pygame Rect
Rect is used to draw a rectangle in Pygame. Pygame uses Rect objects to store and
manipulate rectangular areas. A Rect can be formed from a combination of left, top,
width, and height values. It can also be created from Python objects that are already a
Rect or have an attribute named "rect".
The Rect object has various virtual attributes which can be used to move and align the
Rect:
x,y
top, left, right, bottom
topleft, bottomleft, topright, bottomright
Page | 7
midtop, midleft, midbottom, midright
center, centerx, centery
size, width, height
w,h
The dimension of the rectangle can be changed by assigning the size, width, or height.
All other assignment moves the rectangle without resizing it.
If the width or height is a non-zero value of Rect, then it will return True for a non-
zero test. Some methods return a Rect with 0 sizes to represent an invalid rectangle.
Pygame Keydown
Pygame KEYDOWN and KEYUP detect the event if a key is physically pressed and
released. KEYDOWN detects the key press and, KEYUP detects the key release.
Both events (Key press and Key release) have two attributes which are the following:
Pygame Draw
Pygame provides geometry functions to draw simple shapes to the surface. These
functions will work for rendering to any format to surfaces. Most of the functions
accept a width argument to signify the size of the thickness around the edge of the
shape. If the width is passed 0, then the shape will be solid(filled).
All the drawing function takes the color argument that can be one of the following
formats:
o A pygame.Color objects
o An (RGB) triplet(tuple/list)
o An (RGBA) quadruplet(tuple/list)
o An integer value that has been mapped to the surface's pixel format
Draw a rectangle
The following functions are used to draw a rectangle on the given surface.
1. pygame.draw.rect(surface, color, rect)
2. pygame.draw.rect(surface, color, rect, width=0)
Parameters:
Page | 8
o surface - Screen to draw on.
o color- This argument is used to color the given shape. The alpha value is
optional if we are using a tuple.
o rect(Rect)- Draw rectangle, position, and dimensions.
o width(int)- This is optional to use the line thickness or to indicate that the
rectangle is filled.
1. if width == 0, (default) fill the rectangle
2. if width > 0, used for line0 thickness
3. if width < 0, nothing will be drawn
Draw a polygon
The following functions are used to draw a polygon on the given surface.
o pygame.draw.polygon(surface,color,points)
o pygame.draw.polygon(surface, color, points, width=0)
Parameters:
Draw an ellipse
The following functions are used to draw an ellipse on the given surface.
1. pygame.draw.ellipse(surface, color, rect)
2. pygame.draw.ellipse(surface, color, rect, width=0)
Parameters:
This method is used to draw a straight line on the given surface. There are no endcaps.
1. pygame.draw.line(surface,color,start_pos,end_pos,width)
2. pygame.draw.line(surface,color,start_pos,end_pos,width=1)
Page | 9
Parameters:
Draw a Circle
Below are the functions, which are used to draw a circle on the given surface.
Parameters:
Below functions are used to draw an elliptical arc on the given surface.
1. ? arc(surface, color, rect, start_angle, stop_angle)
2. ? arc(surface, color, rect, start_angle, stop_angle, width=1)
Parameters:
a.i. If start_angle < stop_angle then the arc will be drawn in a counter-clock direction
from the start_angle to end_angle.
Page | 10
a.iii If start_angle==stop_angle, nothing will be drawn.
Output:
Pygame also provides facilities to render the font and text. We can load fonts from the
system by using the pygame.font.SysFont() function. Pygame comes with the built-
in default font which can be accessed by passing the font name or None. There are
many functions to help to work with the font.
The font objects are created with pygame.font.Font().The actual font objects do most
of the works done with fonts. Font objects are generally used to render the text into
new Surface objects. Few important font functions are the following:
render()
This function is used to draw text on a new Surface. Pygame has no facility to draw
text on the existing Surface. This creates a new Surface with the specified text render
on it. The syntax is the following:
render(text, antialias, color, background=None)
size()
Page | 11
size(bool)
set_bold()
This function is used for bold rending of text. The syntax is following:
set_bold(bool)
Output:
all_font = pygame.font.get_fonts()
font = pygame.font.Font(None,size)
Using any above functions, we can work with the attractive font in game.
A pygame sprite is a two-dimensional image that is part of the large graphical scene.
Usually, a sprite will be some object in the scene.One of the most advantages of
working with sprites is the ability to work with them in groups. We can easily move
and draw all the sprites with the one command if they are in the group.
The Sprite module contains the various simple classes to be used within the games. It
is optional to use Sprite classes and different group classes when using pygame.
Pygame provides sprites and sprite groups that help for collision detection. Collision
detection is the process when two objects on the screen collide each other. For
Page | 12
example, if a player is hit by the enemy's bullet, then it may lose a life or, the program
need to know when the player touches a coin so that they automatically picked up.
Output:
After pressing the arrow keys, one rectangle will collide with another rectangle then
output is:
Page | 13
b. Random Module
Table 1: Random Module Functions
Function Description
random.choice(range(10,
Pick a single random number from range 1 to 100
101))
c. OS Module
The OS module in Python provides functions for interacting with the operating
system. OS comes under Python’s standard utility modules. This module provides a
portable way of using operating system-dependent functionality. The *os* and
*os.path* modules include many functions to interact with the file system.
Page | 14
d. System Module
The sys module in Python provides various functions and variables that are used to
manipulate different parts of the Python runtime environment. It allows operating on
the interpreter as it provides access to the variables and functions that interact
strongly with the interpreter.
e. Time Module
As the name suggests Python time module allows to work with time in Python. It
allows functionality like getting the current time, pausing the Program from
executing, etc.
Page | 15
Chapter 2- Project Design
A. The sprites
The sprites are obtained from www.kindpng.com and are used for backgrounds,
obstacles and the player character.
1) Background Left
2) Background Right
Page | 16
Figure 6: Background piece 2
3) Player car
4) Car 1
Page | 17
Figure 8: Brown Car
5) Car 2
6) Baddie Car
Page | 18
Figure 10: Pink Car
B. Code Design
The game works in an while loop which is executed till it ends or is broken
out off.
The we step up the default values of the lifes, window size and car speed
etc.
Initialize the clock for the game and make the system window for the game
Page | 19
Then we load the image resources from the image folder and set them in
variables.
Then we make the start screen which is the screen the player will see before
starting the game.
Now, we set up s path for saving the score in data folder when the high
score changes
After, all of this is done we start the while loop of the game when the player
presses any key
As the loop starts baddies begin to appear on the field and the count of
enemies gets appended with each loop.
The cheats are inserted in the code mainly for slowing the enemies and
sending them in reverse, the key board mapping for the game is done here,
and the difficulty is increased depending on whether cheats are on or not.
The enemies that reach the end of the screen are removed.
The game constantly does a collision check if the check is true the count is
decreased by one , if the user scored is higher than the high score than it
replaces it and the clock resets.
If the user count reaches zero we reset the on the “Press any key to play
again.” screen.
Page | 20
Chapter 3- Implementation
# 1) importing the necessary modules such as pygame, random, sys, os and time
modules along with all the assets of the pygame module
Page | 21
frames per second is set to 30) and the obstacle size and speed values(minimum
size is 2 while maximum size is 8 pixels and the baddy speed is set to be 8 pixels
per second)
WINDOWWIDTH = 800
WINDOWHEIGHT = 600
BACKGROUNDCOLOR = (0, 0, 0)
FPS = 30
BADDIEMINSIZE = 2
BADDIEMAXSIZE = 5
BADDIEMINSPEED = 8
BADDIEMAXSPEED = 8
ADDNEWBADDIERATE = 6
PLAYERMOVERATE = 5
count=3
# 3) Defining a terminate() function to terminate the game and exit the pygame
window
def terminate():
pygame.quit()
sys.exit()
def waitForPlayerToPressKey():
while True:
Page | 22
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
terminate()
return
# 5) setting a function to check if the player has hit any baddie car using the
player rectangle and the baddies as parameters
for b in baddies:
if playerRect.colliderect(b['rect']):
return True
return False
textrect = textobj.get_rect()
Page | 23
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH,
WINDOWHEIGHT))
pygame.mouse.set_visible(False)
# 9) loading the sprites from the image folder and setting up the player rectangle
Page | 24
playerImage = pygame.image.load('image/car1.png')
car3 = pygame.image.load('image/car3.png')
car4 = pygame.image.load('image/car4.png')
playerRect = playerImage.get_rect()
baddieImage = pygame.image.load('image/car2.png')
sample = [car3,car4,baddieImage]
wallLeft = pygame.image.load('image/left.png')
wallRight = pygame.image.load('image/right.png')
# 10) Setting up the first screen and check if the player wants to quit
pygame.display.update()
waitForPlayerToPressKey()
zero=0
# 11) Setting up the path for saving the score in data folder when the high score
changes
if not os.path.exists("data/save.dat"):
f=open("data/save.dat",'w')
f.write(str(zero))
f.close()
v=open("data/save.dat",'r')
Page | 25
topScore = int(v.readline())
v.close()
while (count>0):
baddies = []
score = 0
baddieAddCounter = 0
while True:
score += 1
#Closing
if event.type == QUIT:
terminate()
#cheat settings
if event.type == KEYDOWN:
if event.key == ord('z'):
Page | 26
reverseCheat = True
if event.key == ord('x'):
slowCheat = True
#Control Setting
moveRight = False
moveLeft = True
moveLeft = False
moveRight = True
moveDown = False
moveUp = True
moveUp = False
moveDown = True
#cheat removal
if event.type == KEYUP:
if event.key == ord('z'):
reverseCheat = False
score = 0
if event.key == ord('x'):
slowCheat = False
score = 0
if event.key == K_ESCAPE:
Page | 27
terminate()
moveLeft = False
moveRight = False
moveUp = False
moveDown = False
baddieAddCounter += 1
if baddieAddCounter == ADDNEWBADDIERATE:
baddieAddCounter = 0
baddieSize =1
baddies.append(newBaddie)
Page | 28
'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
baddies.append(sideLeft)
baddies.append(sideRight)
playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
playerRect.move_ip(PLAYERMOVERATE, 0)
playerRect.move_ip(0, -1 * PLAYERMOVERATE)
playerRect.move_ip(0, PLAYERMOVERATE)
for b in baddies:
b['rect'].move_ip(0, b['speed'])
Page | 29
elif reverseCheat:
b['rect'].move_ip(0, -5)
elif slowCheat:
b['rect'].move_ip(0, 1)
for b in baddies[:]:
baddies.remove(b)
windowSurface.fill(BACKGROUNDCOLOR)
windowSurface.blit(playerImage, playerRect)
for b in baddies:
windowSurface.blit(b['surface'], b['rect'])
Page | 30
pygame.display.update()
if playerHasHitBaddie(playerRect, baddies):
g=open("data/save.dat",'w')
g.write(str(score))
g.close()
topScore = score
break
#clock reseting
mainClock.tick(FPS)
#lives reduction
count=count-1
#time reset
time.sleep(1)
if (count==0):
Page | 31
#Resetting the game
pygame.display.update()
time.sleep(1)
waitForPlayerToPressKey()
count=3
A. Testing
The “Road Rush” game is put through various testing scenarios. The scenarios are as
follows:-
Boot up
Running
Score tracking
Page | 32
The updating of the save file data
Cheats activation
Cheats deactivation
Game reset
B. Results
The “Road Rush” game is fully functional and works without any errors, the
following features are checked and confirmed through testing:
The updating of the save file data The save files updated with each change in
high score is 5
Page | 33
Game breaking bugs The game breaking bugs are 0
0- Absent
1- Bad
2- Poor
3- Acceptable
4- Good
5- Excellent
A. Screenshots
1) The File “Index.py” is to executed to start the game
Page | 34
Figure 11: Screen-shot 1
Page | 35
Figure 13: Screen-shot 3
Page | 36
Figure 15: Screen-shot 5
B. Conclusion
Page | 37
Through intensive testing, the game is checked on the boot up, control mapping,
alignment, running, score counting, score updating, saving the data, cheats, presence
of game-breaking bugs and game reset.
It clears all the tests with flying scores, we can conclude that-
this “Road Rush” game’s beta project is working without any problems
this “Road Rush” game’s beta is ready for public testing
C. Future Scope
The beta is complete but it still requires further testing, after public beta-testing we
could gather live player response and make changes to it for the final product .The
final product may have a theme change but the main structure of the code will remain
same only the assets may be need to be replaced. The animation is needed to be
smoothed out, it can be done with the help of someone who specialises in computer
graphics art.
After the necessary changes are made the game can be made available on the open
market for more consumers to download and play. We can use the user reviews to
further enhance the users experience with the final product through periodical
updates.
The game can also be made online so users can race and compete with each other for
the higher score.
References
Page | 38
The references are from the following sites:-
I. https://www.scribd.com/document/423079060
II. https://www.geeksforgeeks.org
III. www.kindpng.com
IV. https://www.javatpoint.com
V. https://stackoverflow.com
VI. https://www.pygame.org
VII. https://www.tutorialandexample.com
VIII. https://code.visualstudio.com/Docs
X. Pygame - Wikipedia
Page | 39