0% found this document useful (0 votes)
17 views

Python Report 2

The document describes a Python code implementation of a simple 2D car racing game using the Pygame library. Key aspects covered include initializing the game, controlling player input, spawning and moving enemy cars, detecting collisions, scoring, scrolling background, and resetting the game upon collision.

Uploaded by

Shaurya Nikam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Python Report 2

The document describes a Python code implementation of a simple 2D car racing game using the Pygame library. Key aspects covered include initializing the game, controlling player input, spawning and moving enemy cars, detecting collisions, scoring, scrolling background, and resetting the game upon collision.

Uploaded by

Shaurya Nikam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

1

1. Project Abstraction

The Python code implements a simple 2D car racing game using


the Pygame library. The game involves controlling a car to dodge
enemy cars on a scrolling background. The player's score
increases as they successfully avoid collisions with enemy cars.
The game ends when the player's car collides with an enemy car or
hits the boundaries of the road.

Key Features:

1. Game Initialization:
The game initializes with the necessary components such as
display settings, car images, enemy car attributes, background
settings, etc.

2. Game Loop:
The game loop (run_car method) continuously updates the game
state, handling player input, updating car and enemy car positions,
detecting collisions, and rendering graphics.

3. Player Control:
Player control is implemented using keyboard inputs. The player
can move the car left or right to avoid collisions.
2

4. Enemy Car Spawning:


Enemy cars spawn at random positions on the road and move
downwards. When an enemy car moves out of the screen, it
respawns at the top with a new random position.

5. Collision Detection:
Collision detection is implemented to detect when the player's car
collides with an enemy car or hits the road boundaries. Upon
collision, the game ends, and a game over message is displayed.

6. Scoring:
The player's score increases as they survive longer in the game
without colliding with enemy cars. The score is displayed on the
game window.

7. Background Scrolling:
The background image scrolls downwards, creating the illusion of
movement. This adds dynamism to the game environment.

8. Game Over Handling:


When the game ends (due to collision or hitting boundaries), a
game over message is displayed, and the game resets after a short
delay.

9. Credits Display:
3

A credit message is displayed at the end of the game, thanking the


player for playing.

The implemented car racing game provides an entertaining


experience with simple gameplay mechanics. It demonstrates the
use of Pygame for developing 2D games in Python and covers
essential aspects such as game initialization, player control,
collision detection, scoring, and game over handling. This codebase
serves as a foundation for further enhancements and customization
to create more complex and engaging games
4

2. Code

import random
from time import sleep

import pygame

class CarRacing:
def __init__(self):

pygame.init()
self.display_width = 800
self.display_height = 600
self.black = (0, 0, 0)
self.white = (255, 255, 255)
self.clock = pygame.time.Clock()
self.gameDisplay = None

self.initialize()

def initialize(self):

self.crashed = False

self.carImg = pygame.image.load('.\\img\\car.png')
self.car_x_coordinate = (self.display_width * 0.45)
self.car_y_coordinate = (self.display_height * 0.8)
self.car_width = 49

# enemy_car
self.enemy_car = pygame.image.load('.\\img\\enemy_car_1.png')
self.enemy_car_startx = random.randrange(310, 450)
self.enemy_car_starty = -600
self.enemy_car_speed = 5
self.enemy_car_width = 49
self.enemy_car_height = 100

# Background
5

self.bgImg = pygame.image.load(".\\img\\back_ground.jpg")
self.bg_x1 = (self.display_width / 2) - (360 / 2)
self.bg_x2 = (self.display_width / 2) - (360 / 2)
self.bg_y1 = 0
self.bg_y2 = -600
self.bg_speed = 3
self.count = 0

def car(self, car_x_coordinate, car_y_coordinate):


self.gameDisplay.blit(self.carImg, (car_x_coordinate,
car_y_coordinate))

def racing_window(self):
self.gameDisplay = pygame.display.set_mode((self.display_width,
self.display_height))
pygame.display.set_caption('Car Dodge')
self.run_car()

def run_car(self):

while not self.crashed:

for event in pygame.event.get():


if event.type == pygame.QUIT:
self.crashed = True
# print(event)

if (event.type == pygame.KEYDOWN):
if (event.key == pygame.K_LEFT):
self.car_x_coordinate -= 50
print ("CAR X COORDINATES: %s" %
self.car_x_coordinate)
if (event.key == pygame.K_RIGHT):
self.car_x_coordinate += 50
print ("CAR X COORDINATES: %s" %
self.car_x_coordinate)
print ("x: {x}, y:
{y}".format(x=self.car_x_coordinate, y=self.car_y_coordinate))

self.gameDisplay.fill(self.black)
self.back_ground_raod()
6

self.run_enemy_car(self.enemy_car_startx,
self.enemy_car_starty)
self.enemy_car_starty += self.enemy_car_speed

if self.enemy_car_starty > self.display_height:


self.enemy_car_starty = 0 - self.enemy_car_height
self.enemy_car_startx = random.randrange(310, 450)

self.car(self.car_x_coordinate, self.car_y_coordinate)
self.highscore(self.count)
self.count += 1
if (self.count % 100 == 0):
self.enemy_car_speed += 1
self.bg_speed += 1
if self.car_y_coordinate < self.enemy_car_starty +
self.enemy_car_height:
if self.car_x_coordinate > self.enemy_car_startx and
self.car_x_coordinate < self.enemy_car_startx + self.enemy_car_width or
self.car_x_coordinate + self.car_width > self.enemy_car_startx and
self.car_x_coordinate + self.car_width < self.enemy_car_startx +
self.enemy_car_width:
self.crashed = True
self.display_message("Game Over !!!")

if self.car_x_coordinate < 310 or self.car_x_coordinate >


460:
self.crashed = True
self.display_message("Game Over !!!")

pygame.display.update()
self.clock.tick(60)

def display_message(self, msg):


font = pygame.font.SysFont("comicsansms", 72, True)
text = font.render(msg, True, (255, 255, 255))
self.gameDisplay.blit(text, (400 - text.get_width() // 2, 240 -
text.get_height() // 2))
self.display_credit()
pygame.display.update()
self.clock.tick(60)
sleep(1)
car_racing.initialize()
car_racing.racing_window()
7

def back_ground_raod(self):
self.gameDisplay.blit(self.bgImg, (self.bg_x1, self.bg_y1))
self.gameDisplay.blit(self.bgImg, (self.bg_x2, self.bg_y2))

self.bg_y1 += self.bg_speed
self.bg_y2 += self.bg_speed

if self.bg_y1 >= self.display_height:


self.bg_y1 = -600

if self.bg_y2 >= self.display_height:


self.bg_y2 = -600

def run_enemy_car(self, thingx, thingy):


self.gameDisplay.blit(self.enemy_car, (thingx, thingy))

def highscore(self, count):


font = pygame.font.SysFont("arial", 20)
text = font.render("Score : " + str(count), True, self.white)
self.gameDisplay.blit(text, (0, 0))

def display_credit(self):
font = pygame.font.SysFont("lucidaconsole", 14)
text = font.render("Thanks for playing!", True, self.white)
self.gameDisplay.blit(text, (600, 520))

if __name__ == '__main__':
car_racing = CarRacing()
car_racing.racing_window()
8

3. Explanation

The given Python code implements a simple car racing


game using the Pygame library. Explaining each part's
purpose and functionality.

1. Importing Libraries

import random
from time import sleep

import pygame

random: This library is used for generating random


numbers, which is utilized in determining the starting
position of enemy cars.
sleep from time: It allows the program to pause execution
for a specified amount of time, which can be useful for
controlling game pacing.
pygame: Pygame is a set of Python modules designed for
writing video games. It provides functionalities for handling
graphics, sounds, and user input.

2. CarRacing Class

class CarRacing:
def __init__(self):

# Initialize Pygame
9

pygame.init()

# Screen dimensions
self.display_width = 800
self.display_height = 600

# Colors

self.black = (0, 0, 0)
self.white = (255, 255, 255)

# Clock for controlling FPS

self.clock = pygame.time.Clock()

# Initialize the game display

self.gameDisplay = None

# Call the initialization function


self.initialize()

The CarRacing class is initialized. This class encapsulates


all the functionalities related to the game.

3. Initialization Function
10

def initialize(self):

# Flag to track if the car has crashed


self.crashed = False

# Car properties

self.car_x_coordinate = (self.display_width * 0.45)


self.car_y_coordinate = (self.display_height * 0.8)
self.car_width = 49

# Enemy car properties

self.enemy_car = pygame.image.load('.\\img\\enemy_car_1.png')
self.enemy_car_startx = random.randrange(310, 450)
self.enemy_car_starty = -600
self.enemy_car_speed = 5
self.enemy_car_width = 49
self.enemy_car_height = 100

# Background properties

self.bgImg = pygame.image.load(".\\img\\back_ground.jpg")
self.bg_x1 = (self.display_width / 2) - (360 / 2)
self.bg_x2 = (self.display_width / 2) - (360 / 2)
self.bg_y1 = 0
self.bg_y2 = -600
self.bg_speed = 3
self.count = 0
11

The initialize function sets up initial parameters for the


game such as car and enemy car positions, speeds, and
dimensions, as well as background properties.

4. Car and Racing Window Functions

def car(self, car_x_coordinate, car_y_coordinate):


self.gameDisplay.blit(self.carImg, (car_x_coordinate,
car_y_coordinate))

def racing_window(self):
self.gameDisplay = pygame.display.set_mode((self.display_width,
self.display_height))
pygame.display.set_caption('Car Dodge')
self.run_car()

car: This function is responsible for drawing the player's car


on the game display.
racing_window: This function sets up the game window with
the specified dimensions and title and starts the game loop
(run_car function).

5. Game Loop and Event Handling


def run_car(self):

while not self.crashed:

for event in pygame.event.get():


if event.type == pygame.QUIT:
self.crashed = True
# print(event)

if (event.type == pygame.KEYDOWN):
12

if (event.key == pygame.K_LEFT):
self.car_x_coordinate -= 50
print ("CAR X COORDINATES: %s" %
self.car_x_coordinate)

if (event.key == pygame.K_RIGHT):
self.car_x_coordinate += 50

# Other game logic goes here...


run_car: This function contains the main game loop where
the game logic is executed. It continuously checks for user
input events such as quitting the game or moving the car
left or right using the arrow keys.

6. Game Logic

self.gameDisplay.fill(self.black)
self.back_ground_raod()

self.run_enemy_car(self.enemy_car_startx, self.enemy_car_starty)

# Other game logic goes here...


gameDisplay.fill: This function fills the game display with a
black color, essentially clearing the screen for the next
frame.
back_ground_road: This function handles the scrolling
background, creating the illusion of movement.
run_enemy_car: This function draws the enemy car on the
screen.

7. Collision Detection
13

if self.car_y_coordinate < self.enemy_car_starty +


self.enemy_car_height:
if self.car_x_coordinate > self.enemy_car_startx and
self.car_x_coordinate < self.enemy_car_startx + self.enemy_car_width or
self.car_x_coordinate + self.car_width > self.enemy_car_startx and
self.car_x_coordinate + self.car_width < self.enemy_car_startx +
self.enemy_car_width:
self.crashed = True
self.display_message("Game Over !!!")

if self.car_x_coordinate < 310 or self.car_x_coordinate > 460:


self.crashed = True
self.display_message("Game Over !!!")

These conditions check for collisions between the player's


car and the enemy car or the boundaries of the road. If a
collision is detected, the game ends.

8. Displaying Messages and Credits

def display_message(self, msg):

# Function to display a message on the screen when


the game ends
# It also calls display_credit to show a credit message
# Restarts the game after a delay
# Other game logic goes here...

def display_credit(self):

# Function to display a credit message on the screen


# Other game logic goes here...
14

display_message: This function displays a message (e.g.,


"Game Over") on the screen when the game ends, along
with a credit message. It then restarts the game after a brief
delay.
display_credit: This function displays a credit message on
the screen.

9. Main Function

if __name__ == '__main__':
car_racing = CarRacing()
car_racing.racing_window()

This block of code initializes an instance of the CarRacing


class and starts the game by calling the racing_window
method.
This explanation provides an overview of the code structure
and its functionalities. Each part of the code contributes to
creating a simple car racing game using the Pygame library.
15

4. Interface

In this picture, game is start.


16

In this picture enemy car is come from front side.

In this picture enemy car is come from front side and it seems too close
to our car.
17

In this picture car is is crashed with enemy car. And game is over.

In this picture, Game is over by another way by crashing to road side.


18

5. Technology used

● Graphics Handling: Pygame facilitates loading and rendering


of images onto the game display. In the code, images
representing the player's car, enemy cars, and background
are loaded using Pygame's image loading functionality. These
images are then blitted (drawn) onto the game display surface.

● Event Handling: Pygame allows for the detection and handling


of various events, such as keyboard input, mouse input, and
window events. The code utilizes Pygame's event loop to
continuously check for user input events, specifically keyboard
events for controlling the player's car.

● Game Loop Management: Pygame enables the creation of a


game loop that continuously updates the game state, handles
user input, and renders the game graphics. The main game
loop in the provided code is responsible for updating the
positions of game elements, detecting collisions, updating the
score, and rendering graphics.

● Collision Detection: Pygame provides functionality for


detecting collisions between game objects. In the given code,
collision detection logic is implemented to detect when the
player's car collides with enemy cars or hits the road
boundaries, resulting in the game ending.
19

● Text Rendering: Pygame supports rendering text onto the


game display. In the code, text messages such as the game
over message, score display, and credit message are
rendered using Pygame's font rendering functionality.

● Timing and Clock Management: Pygame offers functionality


for managing time and frame rates. The code utilizes
Pygame's clock object to control the frame rate and ensure
smooth gameplay by limiting the game's execution to a
specific number of frames per second (FPS).

The code utilizes the Pygame library, which is a set of Python


modules designed for writing video games. Pygame provides
functionality for handling various aspects of game
development, including graphics, sound, input handling, and
event management. Here are the key points regarding the
technology used in the provided code.
20

6. Summary

The Car Racing Game is a simple yet engaging arcade-style game


developed using the Pygame library in Python. In this game,
players control a car on a busy road while avoiding collisions with
randomly moving enemy cars. The objective is to survive as long as
possible and achieve the highest score.

The Car Racing Game offers a fun and challenging gaming


experience for players of all ages. With its simple controls, dynamic
gameplay, and engaging visuals, it provides hours of entertainment
and excitement. Whether you're a casual gamer looking for a quick
distraction or a hardcore gamer aiming for the highest score, this
game is sure to keep you entertained.
21

7. Conclusion

In this mini project a basic car racing game using Pygame in Python
is implemented. The game features include player control of a car
using left and right arrow keys, avoidance of randomly moving
enemy cars, scoring based on the duration of survival, collision
detection, and a "Game Over" message displayed upon crashing.
The game window displays the score and a message of
appreciation after the game ends. Overall, it's a simple yet
functional implementation suitable for further customization and
expansion to create more complex gameplay features and
enhancements.

You might also like