KEMBAR78
Main Report v1 | PDF | Python (Programming Language) | Software
0% found this document useful (0 votes)
82 views39 pages

Main Report v1

The document introduces a road rush game project created using Python and Pygame. It discusses the objective of creating a single player game where the player controls a car to avoid oncoming traffic. Visual Studio Code and Python were used to code the game, while Pygame provided modules for graphics, sound, and input handling. The methodology section notes that Pygame was installed via pip and imported in Python to access its modules for building the game. Limitations include the beta state of the game and inconsistencies in saving.

Uploaded by

Bharat Goel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views39 pages

Main Report v1

The document introduces a road rush game project created using Python and Pygame. It discusses the objective of creating a single player game where the player controls a car to avoid oncoming traffic. Visual Studio Code and Python were used to code the game, while Pygame provided modules for graphics, sound, and input handling. The methodology section notes that Pygame was installed via pip and imported in Python to access its modules for building the game. Limitations include the beta state of the game and inconsistencies in saving.

Uploaded by

Bharat Goel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

Chapter 1- Introduction

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

a. Visual Studio Code:- Visual Studio Code is a freeware source-code


editor made by Microsoft for Windows, Linux and macOS. Features include support
for debugging, syntax highlighting, intelligent code completion, snippets, code
refactoring, and embedded Git. Users can change the theme, keyboard shortcuts,
preferences, and install extensions that add additional functionality.

VS Code is supported on the following platforms:

 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:

 1.6 GHz or faster processor


 1 GB of RAM or more

b. Python:- Python is a high-level, general-purpose programming language. Its


design philosophy emphasizes code readability with the use of significant indentation.
Python is dynamically-typed and garbage-collected. It supports multiple programming
paradigms, including structured (particularly procedural), object-
oriented and functional programming. It is often described as a "batteries included"
language due to its comprehensive standard library.
Guido van Rossum began working on Python in the late 1980s as a successor to
the ABC programming language and first released it in 1991 as
Python 0.9.0.Python 2.0 was released in 2000 and introduced new features such as list
comprehensions, cycle-detecting garbage collection, reference counting,
and Unicode support. Python 3.0, released in 2008, was a major revision that is not
completely backward-compatible with earlier versions. Python 2 was discontinued
with version 2.7.18 in 2020.
Python consistently ranks as one of the most popular programming languages.

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:

 Beautiful is better than ugly.


 Explicit is better than implicit.
 Simple is better than complex.
 Complex is better than complicated.
 Readability counts.
Rather than building all of its functionality into its core, Python was designed to be
highly extensible via modules. This compact modularity has made it particularly
popular as a means of adding programmable interfaces to existing applications. Van
Rossum's vision of a small core language with a large standard library and easily
extensible interpreter stemmed from his frustrations with ABC, which espoused the
opposite approach.
Python strives for a simpler, less-cluttered syntax and grammar while giving
developers a choice in their coding methodology. In contrast to Perl's "there is more
than one way to do it" motto, Python embraces a "there should be one—and
preferably only one—obvious way to do it" philosophy. Alex Martelli, a Fellow at
the Python Software Foundation and Python book author, wrote: "To describe
something as 'clever' is not considered a compliment in the Python culture."
Python's developers strive to avoid premature optimization and reject patches to non-
critical parts of the CPython reference implementation that would offer marginal
increases in speed at the cost of clarity. When speed is important, a Python
programmer can move time-critical functions to extension modules written in
languages such as C; or use PyPy, a just-in-time compiler. Cython is also available,
which translates a Python script into C and makes direct C-level API calls into the
Python interpreter.
Python's developers aim for it to be fun to use. This is reflected in its name—a tribute
to the British comedy group Monty Python—and in occasionally playful approaches
to tutorials and reference materials, such as examples that refer to spam and eggs (a
reference to a Monty Python sketch) instead of the standard foo, and bar.

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. 

Initializing the Pygame library


Before we can do much with pygame, we first need to initialize it. Just call the
method given below to initialize it. 
pygame.init()
This method initializes all the necessary pygame modules. This method has nothing
like an argument and returns a tuple that returns the no of modules initialized
successfully and the number of modules failed respectively. 

Basic Function used:


 pygame.init(): This command is used to initiate the pygame module.
 pygame.display.set_mode((500,500)): This command is used to make a window
of desired size, (width, height). The return value is a Surface Object which is the
object where we perform different graphical operations.
 pygame.display.set_caption(title = “”): This command is used to set the title of
the window/ board.
 pygame.event.get(): This is used to empty the event queue. If we do not call this,
the window messages will start to pile up and, the game will become
unresponsive in the opinion of the operating system.

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

Pygame Adding Image

To add an image on the window, first, we need to instantiate a blank surface by


calling the Surface constructor with a width and height tuple.

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.

For the transparent initialization of Surface, pass the SRCALPHA argument.

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() function is used to perform changes in the position or size of a rectangle. It


returns the new copy of the Rect with the affected changes. No modification happens
in the original rectangle.

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:

o key: Key is an integer id which represents every key on the keyword.


o mod: This is a bitmask of all the modifier keys that were in the pressed state
when the event occurred.

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:

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 points(tuple(coordinate) or list(coordinate)): A sequence of 3 or more (x,y)
coordinates that make up the vertices of the polygon. Each coordinate in the
sequence must be tuple/list.

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:

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.

Draw a straight line

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:

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 start_pos- start position of the line(x,y)
o end_pos- End position of the line

Draw a Circle

Below are the functions, which are used to draw a circle on the given surface.

o circle(surface, color, center, radius)


o circle(surface, color, center, radius, width=0)

Parameters:

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 center - The center point of the circle as a sequence of two int/float, e.g. (x,y)
o radius(int or float)- radius of the circle, measured from the center parameter,
if the radius is zero, then it will only draw the center pixel.

Draw an elliptical arc

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:

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 start_angle- Start angle of the arc in radians.
o stop_angle- Stop angle of the arc in radians.

There are three conditions for start_angle and stop_angle parameter:

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.

a.ii If start_angle>stop_angle then tau(tau=2*pi) will be added to the stop angle.

Page | 10
a.iii If start_angle==stop_angle, nothing will be drawn.

Output:

Figure 1: Drawing using pygame

Pygame Text and Font

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()

This function is used to determine the number of space or positioning needed to


render text. It can also be used for word-wrapping and other layout effects. The syntax
is the following:

Page | 11
size(bool)  

set_bold()

This function is used for bold rending of text. The syntax is following:

set_bold(bool)  

Output:

Figure 2: Writing using pygame

all_font = pygame.font.get_fonts()  

There is another function to instantiate the default system font:

font = pygame.font.Font(None,size)  

Using any above functions, we can work with the attractive font in game.

Pygame Sprite and Collision detection

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:

Figure 3: Collision detecting 1

After pressing the arrow keys, one rectangle will collide with another rectangle then
output is:

Figure 4: Collision detecting 2

Page | 13
b. Random Module
Table 1: Random Module Functions

Function Description

Choose a random item from a sequence. Here seq can be a


random.choice(list)
list, tuple, string, or any iterable like range.

Choose multiple random items from a list, set, or any data


random.choices(list, k=3)
structure.

random.choice(range(10,
Pick a single random number from range 1 to 100
101))

random.getrandbits(1) Returns a random Boolean

random.choice(list(dict1)) Choose a random key from a dictionary

np.random.choice() Return random choice from a multidimensional array

secrets.choice(list1) Choose a random item from the list securely

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.

The resources used in the program are as follows:-

1) Background Left

Figure 5: Background piece 1

2) Background Right

Page | 16
Figure 6: Background piece 2

3) Player car

Figure 7: Yellow Car

4) Car 1

Page | 17
Figure 8: Brown Car

5) Car 2

Figure 9: White Car

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 code starts with importing the necessary python libraries

 The we step up the default values of the lifes, window size and car speed
etc.

 Setting up quitting and the game closing option

 Setting up an collision check

 Making the system window

 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.

 Setting the speed of the player car and the enemies

 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

The code of the game is as follows:-

# 1) importing the necessary modules such as pygame, random, sys, os and time
modules along with all the assets of the pygame module

Import pygame, random, sys ,os,time

from pygame.locals import *

# 2) Initializing the values of the background(width as 800 pixels and length as


600 pixels, the text colour is set as white, background colour is set as black and

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

TEXTCOLOR = (255, 255, 255)

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()

# 4) Defining a waitForPlayerToPressKey() function to set up quitting option by


calling the terminate function, the exit paths include tuping quit and pressing the
escape key on the keyboard

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

def playerHasHitBaddie(playerRect, baddies):

for b in baddies:

if playerRect.colliderect(b['rect']):

return True

return False

# 6) Setting up home screen using a function which uses initialized values

def drawText(text, font, surface, x, y):

textobj = font.render(text, 1, TEXTCOLOR)

textrect = textobj.get_rect()

Page | 23
textrect.topleft = (x, y)

surface.blit(textobj, textrect)

# 7) clock initialization to be use for keeping track of score

pygame.init()

mainClock = pygame.time.Clock()

# 8) setting up the pygame window

windowSurface = pygame.display.set_mode((WINDOWWIDTH,
WINDOWHEIGHT))

pygame.display.set_caption('Road Rush Game')

pygame.mouse.set_visible(False)

font = pygame.font.SysFont(None, 30)

# 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

drawText('Press any key to start the game.', font, windowSurface, (WINDOWWIDTH


/ 3) - 30, (WINDOWHEIGHT / 3))

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()

# 12) The game loop in which the game actually runs

while (count>0):

baddies = []

score = 0

playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)

moveLeft = moveRight = moveUp = moveDown = False

reverseCheat = slowCheat = False

baddieAddCounter = 0

while True:

score += 1

for event in pygame.event.get():

#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

if event.key == K_LEFT or event.key == ord('a'):

moveRight = False

moveLeft = True

if event.key == K_RIGHT or event.key == ord('d'):

moveLeft = False

moveRight = True

if event.key == K_UP or event.key == ord('w'):

moveDown = False

moveUp = True

if event.key == K_DOWN or event.key == ord('s'):

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()

if event.key == K_LEFT or event.key == ord('a'):

moveLeft = False

if event.key == K_RIGHT or event.key == ord('d'):

moveRight = False

if event.key == K_UP or event.key == ord('w'):

moveUp = False

if event.key == K_DOWN or event.key == ord('s'):

moveDown = False

# Setting up a difficulty curve relative to the cheats activated

if not reverseCheat and not slowCheat:

baddieAddCounter += 1

if baddieAddCounter == ADDNEWBADDIERATE:

baddieAddCounter = 0

baddieSize =1

newBaddie = {'rect': pygame.Rect(random.randint(140, 485), 0 - baddieSize,


23, 47),

'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),

'surface':pygame.transform.scale(random.choice(sample), (23, 47)),

baddies.append(newBaddie)

sideLeft= {'rect': pygame.Rect(0,0,126,600),

Page | 28
'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),

'surface':pygame.transform.scale(wallLeft, (126, 599)),

baddies.append(sideLeft)

sideRight= {'rect': pygame.Rect(497,0,303,600),

'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),

'surface':pygame.transform.scale(wallRight, (303, 599)),

baddies.append(sideRight)

#Setting up for Player Rectangle movement

if moveLeft and playerRect.left > 0:

playerRect.move_ip(-1 * PLAYERMOVERATE, 0)

if moveRight and playerRect.right < WINDOWWIDTH:

playerRect.move_ip(PLAYERMOVERATE, 0)

if moveUp and playerRect.top > 0:

playerRect.move_ip(0, -1 * PLAYERMOVERATE)

if moveDown and playerRect.bottom < WINDOWHEIGHT:

playerRect.move_ip(0, PLAYERMOVERATE)

#Setting up for the movement of baddies

for b in baddies:

if not reverseCheat and not slowCheat:

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)

#removing the baddies who have travelled across the screen

for b in baddies[:]:

if b['rect'].top > WINDOWHEIGHT:

baddies.remove(b)

# Draw the game world on the window.

windowSurface.fill(BACKGROUNDCOLOR)

drawText('Score: %s' % (score), font, windowSurface, 128, 0)

drawText('Top Score: %s' % (topScore), font, windowSurface,128, 20)

drawText('Lives: %s' % (count), font, windowSurface,128, 40)

windowSurface.blit(playerImage, playerRect)

for b in baddies:

windowSurface.blit(b['surface'], b['rect'])

Page | 30
pygame.display.update()

#Player collision check and top score updation

if playerHasHitBaddie(playerRect, baddies):

if score > topScore:

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 the player has zero lives remaining

if (count==0):

drawText('Game over', font, windowSurface, (WINDOWWIDTH / 3),


(WINDOWHEIGHT / 3))

Page | 31
#Resetting the game

drawText('Press any key to play again.', font, windowSurface, (WINDOWWIDTH


/ 3) - 80, (WINDOWHEIGHT / 3) + 30)

pygame.display.update()

time.sleep(1)

waitForPlayerToPressKey()

count=3

Chapter 4- Result & Discussion

A. Testing

The “Road Rush” game is put through various testing scenarios. The scenarios are as
follows:-

 Boot up

 Running

 Score tracking

 High score updating

Page | 32
 The updating of the save file data

 Game breaking bugs

 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:

Table 2: Testing Result Score out of five

Test Case Result

 Boot up The game boots up is 4

 Running The game is running 3

 Score tracking The score tracking is 4

 High score updating High score updating is 5

 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

 Cheats activation The cheat activation is 2

 Cheats deactivation The cheat deactivation is 4

 Game reset The game resets is 3.

0- Absent
1- Bad
2- Poor
3- Acceptable
4- Good
5- Excellent

Chapter 5-Conclusion and Future Scope

A. Screenshots
1) The File “Index.py” is to executed to start the game

Page | 34
Figure 11: Screen-shot 1

2) The Execution of “Index.py” in Visual Studio Code

Figure 12: Screen-shot 2

3) The starting Screen

Page | 35
Figure 13: Screen-shot 3

4) The game play of the Road Rush

Figure 14: Screen-shot 4

Page | 36
Figure 15: Screen-shot 5

5) Crashing while on the last life

Figure 16: Screen-shot 6

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

IX. Image Resizer - Crop & Resize Image Online | RedKetchup

X. Pygame - Wikipedia

XI. Python (programming language) - Wikipedia

Page | 39

You might also like