Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
23 views

Python Project Report

Uploaded by

mr.jhion.adbar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Python Project Report

Uploaded by

mr.jhion.adbar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Department Of,

Computer Science and Engineering

Final Project Report

Course Code : CSE_222


Course Title : Object-Oriented Programming II Lab

Submitted To ,
Md. Asfaqur Rahman
Lecturer
Department of Computer Science and Engineering
Faculty of Science and Information Technology

Submitted By,
Name : Jhion Adbar Opi
ID : 221-15-5948
Section : 61_L
Department of Computer Science and Engineering
Faculty of Science and Information Technology

Submission Date : 23.05.2024 .


Table of Contents
Abstract .................................................................................................................................................................... 3
Introduction ............................................................................................................................................................. 4
Design and Implementation ................................................................................................................................... 5
Software ............................................................................................................................................................... 5
Pygame Install ..................................................................................................................................................... 5
Main.py ................................................................................................................................................................ 5
Player part.. ..................................................................................................................................................... 6
Obstacle part.................................................................................................................................................... 6
Alines part… .................................................................................................................................................... 7
Collision_checks part… .................................................................................................................................. 8
Player Lives….................................................................................................................................................. 9
Display_score.. ................................................................................................................................................. 9
Sound system… ............................................................................................................................................... 9
Victory_message… .......................................................................................................................................... 9
Game_over massage.. ...................................................................................................................................... 9
Run Function.. ............................................................................................................................................... 10
Final Output for main.py. ................................................................................................................................ 10
Player.py ............................................................................................................................................................ 11
Leaser.py ............................................................................................................................................................ 12
Obstacle.py......................................................................................................................................................... 13
Alien.py .............................................................................................................................................................. 14
Results .................................................................................................................................................................... 19
Conclusion.............................................................................................................................................................. 20
Referance ............................................................................................................................................................... 20
Abstract

This project report details the development of a 2D “Target Shooting Space Invaders” game developed
using the Pygame library in Python. The game involves a player-controlled “Aircraft” that shoots
“Lasers” to destroy “Alien spaceships” for points. It also includes features like obtaining extra points for
destroying a special alien. The Player “Aircraft” must avoid collisions with the “Aliens” and their lasers
while trying to destroy them. The game also includes obstacles that the player must navigate around and
take shelter from the “Alien Lasers”. The report covers the game's design, implementation,
functionalities, and concludes by summarizing the project's achievements.
Introduction

The objective of this project is to create the classic Two-dimensional “Target Shooting Space Invaders”
arcade game from the 2007s Utilizing Python's “pygame” library. The game development covers various
aspects such as sprite management, collision detection, and sound integration.
In this game, the player controls a defender “Aircraft” that moves horizontally across ( x_start =
screen_width ) the bottom of the screen and fires missiles at enemy “Alien ships” to destroy alien ships.
The player Aircraft must avoid collisions with the aliens and their lasers while trying to destroy them.
The game is initialized with a Game class that sets up the player, obstacles, aliens, and other game
elements. The player is controlled using keyboard inputs and can move left, right, and shoot lasers. The
game also includes obstacles (Created using A Obstacle class) that are placed randomly on the screen the
player must navigate around and stay under for safety from the alien leaser. The aliens are created using
an Alien class and are arranged in a grid formation. The aliens move horizontally and vertically and shoot
lasers at the player. The game includes several functions to handle collisions between the player, aliens,
lasers, and obstacles. The player's lives are displayed at the top right of the screen, and the score is
displayed at the top left. The game ends when the player loses all their lives or hit by any alien or destroys
all the aliens. The game also includes sound effects for shooting lasers ( Player Aircraft and Aline ships),
explosions, and game over. The game's background music is played on a loop.
To recreate this game on our software controls all of the Space Invaders logic and passes the data to byte-
addressable Visual Studio Code in hardware, which is then displayed on a monitor.
Overall, this project demonstrates the use of Pygame to create a simple yet engaging game. The game
could be improved by adding more levels, power-ups, and enemy types. The code could also be optimized
for better performance and readability.
Design and Implementation
The game is implemented using object-oriented programming principles, with separate classes for the player,
aliens, lasers, and obstacles. The game loop is responsible for updating the game state, handling user input, and
rendering the game graphics. The game uses sprites for all game objects, which are drawn to the screen using
Pygame's built-in sprite rendering functions.

Software
To recreate this game on our software controls all of the Space Invaders logic and passes the
data to byte-addressable which is Visual Studio Code in hardware, which is then displayed
on a monitor.

Pygame Install
Pygame is a cross-platform set of Python modules designed for writing video games .

Main.py
First, we import the sys and pygame modules. The pygame module contains the functionality we need to
make a game.

We use tools in the sys module to exit the game when the player
quits.

The call to pygame.display.flip() tells Pygame to make the most recently drawn screen visible. In this case, it
simply draws an empty screen on each pass through the while loop, erasing the old screen so only the new screen
is visible. When we move the game elements around, pygame.display .flip() continually updates the display to
show the new positions of game elements and hide the old ones,
creating the illusion of smooth movement. To determine the
screen size screen_width=1500pix and screen_height = 765pix is
set.
At the end of the file, we create an instance of the game and then
call run_game(). We place run_game() in an if block that only
runs if the file is called directly.
When run this main.py file,
should see an empty Pygame
window.
Then to start for actual game interface, we will inherite all of our class as follow,

Classes Player, alien, Extra, Laser and obstacle is import. For


use of choice, randint from random and time is imported for
countdown.

In main.py first Class name “Game” is created and


a __init__ function is used as self parameter.

Player part..

After inheriting Player from player.py , it is set as (screen_width / 2, screen_height ), constraint in


screen_width so that it stay in screen ,with the speed of 5pix per second. It is grouped in the
pygame.sprite.GroupSingle(player_sprite) for pygame to work.
After it is set in run function and
update and draw in screen. We can
See……….

Obstacle part..
First of all in __init__ function obstacle is inherited,
In hear
shape from
obstacle.py
is set and
size of all
block
(block class) is set in 6 . Amount can be given as 4. In x axes the block position is define as [num * (screen_width
/ self.obstacle_amount) for num in range(self.obstacle_amount)] in hear it is offset so that distance is even. For to
define every other block self.create_multiple_obstacles is used which inherit self.obstacle_x_positions . Distance
is set as x axis screen width/2 and y axis in 575 pix.
In “def create_obstacle(self, x_start, y_start,
offset_x):” to define the string in row and
colam enumerate is used.
Offset_x is used in x axis so that it stay
as even as possible in screen size. To set
a block color “ block = obstacle.Block
(self.block_size,(241,79,80),x,y)” is
used as 241,79,80 is a nice charry red
color.
To add multiple block , self.create_multiple_obstacles is
used which inherit self.obstacle_x_positions.
With this block as set. With “self.blocks.draw(screen)” in
run function . This will work as.
Alines part…
In Game class __init__ function alines and aline_leasers are define.
By using aline_setup we could define how many will be added.
self.alien_direction = 1 is used for movement .

For extra one that float in up of screen extra is use, spawn time is
used for random side 400 and 800 ms.

To setup the alien by row and cal enumerate


is used. Every one is offset by define axes.
Red, yellow, green are name and define how
many row will be there.
Alien is added in sprite for indexing.

Under Game class , aline_position_checker function all aliens


are under aliens.sprite. So under rect by secrren_width all alien
will go down by -1 pix. Movement will be in 2ms. As also it
repeats left and right.

This function is for down movement .

By importing laser , this function is for alien laser. Laser


will spawn randomly as it will go down by y axes.
self.gunshot.play() is use for sound.

For the extra alien that goes left-right-left random. def


extra_alien_timer(self) is for it spawn time . it is also
define as it will came up by 400ms and 800ms time
interval.

After every thing is in order, run function is in order and


complement the code.
Well every component is in order , this should work like this…..

Collision_checks part…
Collision_checks is where all the magic happened.
Under Game class, Collision_checks function define player and
alien collision . It also collaid with block.

This part “spritecollide” is used for is used for define


collaidel .
For player aircraft to kill the aliens by leaser is by
“spritecollide” is used hear for alien to kill.

“spritecollide” also can be used to kill the extra in up and can


get 500 point in score.

It this part under Collision_checks function where the alien can


kill the player.
“pygame.sprite.spritecollide(laser,self.blocks,True):” for the plain
to kill the player. But the player will have extra life. Every time a
player get kill great creator opi_da will print and bomb.play sound
will heard.

Every life is gone then pygame will quit and system will exit.

alien will also can destroy the block and get the player. Then pygame
will quit and system will exit.
Player Lives…
This is under Game class __init__ funtion ,
life is set as 5 which will show in up
right side of screen.

Lives can be shown and it


will go down by -1 every
hit by alien.

Display_score..

This is under Game class __init__ funtion ,


Score text format self.font = pygame.font.Font('../python
project/Pixeled.ttf', 20 ) is inputted.
Using rest the life is offset and
display by “self.display_lives()”.

Sound system…
Under Game class __init__ function all the sound will
generate. It is set as “pygame.mixer.Sound”.
The sound file is in wav format. Only Music is set in loop
that will play all the time. Other are assign as per needed.
Time of play also declare.

Victory_message…

After wining this massage “self.victory

_message()” will show in screen.

Game_over massage..

This is under Game class in hear all ends.


After all life of player end or by hitting the alien
game will end . In ending a massage will show.

The
game window will stay 5 sec and pygame quit,
system exit. Everything ends hear.
Run Function..

All Update All Draw and screen

Final Output for main.py.


Player.py
Let’s add the Aircraft to our game.
Pygame is import for game graphic. Leaser is assigned from
Laser.py.

In player class (pygame.sprite.Sprite) is assigned in __init__ function pos, constraint and speed is used as variable.
After inascient the super () __init__
contractor .
A picture name 221-15-
5948 is used.
Self.speed = speed is for the player to
move accordingly.
For the player to stay in the frame of screen self.max_x_constraint =
constraint is used.
Everything is ready then its “True”.

Key for movement used as


[pygame.K_RIGHT] for move to right in X axes.
[pygame.K_LEFT] for move to left in X axes.
[pygame.K_SPACE] for shoot the leaser in Y axes for given
millisecond.

leaser is added in __init__ then delay is set in 300 ms.


By new shoot_laser function leaser import and work.

in recharge function divided in 1000 ms. As


set as 300ms delay a new laser will fire.

After every thing is set……. update


function will update.. … all function on to
the uzi.wav is used for leaser fire sound
(pygame.sprite.Sprite) define in __init__ function.
and sent to the main.py. player is deployed.
Leaser.py
Leaser is create here ,
After importing pygame in system. Laser class is define. In init
function laser image as define by pygame.Surface with 4 pix
wide and 20 pix hight . speed is define in main.py. It will play
bottom to up from any x axis.

To remove the leaser from screen it is set to go beyond the screen for 50. So they will be kill.

Every thing is in right order then it will be update and send to main.py.

Laser are deployed.


Obstacle.py
Represents an obstacle within the game world after importing pygame,

Class Block is define. With in parameter


(pygame.sprite.Sprite) . In init function self,size,color,x,y is
added as we will use them in main.py . Image if the obstacle
is just pygame.Surface as I will give the shape. For the rect
under xases and y axes topleft is define.

As for the shape , it is a list of string . those are set in a list of


block that every block are a Sprite in Pygame.
It is define a 0 for blank and 1 for x .

After that it will send to main.py .

Thus, this will be the result.


Alien.py
Represents an alien enemy, including its movement, type (based on color), and point value.
After importing pygame, Aline Class is set
with parameter of (pygame.sprite.Sprite) . In
a init function the image of the alien and
position is set. file_path = '../python project/'
+ color + '.png' is use.

red is alien with score value of 100


green is alien with score value is 200
other is define as 300 score value.

If every thing is in order, then send to main.py .

Class Extra is for extra alien that float on top of


screen . It is also a given image.

Then every thing is update and send to Game class.

If every thing is in order. It should be run like this.


Full Code..
Main.py
import pygame, sys self.alien_direction = 1 170,y_distance = 50,x_offset = 100,
y_offset = 80):
from player import Player self.extra =
pygame.sprite.GroupSingle() for row_index, row in
import obstacle enumerate(range(rows)):
self.extra_spawn_time =
from alien import Alien, Extra randint(400,800) for col_index, col in
enumerate(range(cols)):
from random import choice, randint music =
pygame.mixer.Sound('../python x = col_index * x_distance +
from laser import Laser project/Memory Reboot.wav') x_offset
import time music.set_volume(0.5) # ano y = row_index * y_distance
volum + y_offset
class Game:
music.play(loops= -1) # bar bar alien_sprite = Alien('red',x,y)
def __init__(self):
gurbe
if row_index == 0:
player_sprite =
self.gunshot = alien_sprite = Alien('yellow',x,y)
Player((screen_width / 2,
pygame.mixer.Sound('../python
screen_height ),screen_width,5) # 5 is elif 1 <= row_index <= 2:
project/Gunshot.wav') # ai sound alien
player speed alien_sprite = Alien('green',x,y)
ar
self.player = else: alien_sprite =
self.gunshot.set_volume(0.3)
pygame.sprite.GroupSingle(player_spr Alien('red',x,y)
ite)
self.bomb =
pygame.mixer.Sound('../python self.aliens.add(alien_sprite)
self.lives = 5 #life count ja hobe
project/Bomb.wav') # sound ami more
jalem def alien_position_checker(self):
self.live_surf =
pygame.image.load('../python all_aliens = self.aliens.sprites()
self.bomb.set_volume(0.5)
project/22115-
5948.png').convert_alpha() for alien in all_aliens:
self.ex =
pygame.mixer.Sound('../python
self.live_x_start_pos = if alien.rect.right >=
project/ex.wav') # sound alien more
screen_width - screen_width:
galo
(self.live_surf.get_size()[0] * 4 + 40) #
4 ta life show hoi self.alien_direction = -1
self.ex.set_volume(0.5)
self.score = 0 self.alien_move_down(2)
def create_obstacle(self, x_start,
y_start, offset_x): elif alien.rect.left <= 0:
self.font =
pygame.font.Font('../python for row_index, row in
project/Pixeled.ttf', 20 ) self.alien_direction = 1
enumerate(self.shape):
self.shape = obstacle.shape # self.alien_move_down(2)
for col_index, col in
obastacle ar shape anchi class theke enumerate(row): def
self.block_size = 6 alien_move_down(self,distance):
if col == 'x':
self.blocks = if self.aliens:
x = x_start + col_index *
pygame.sprite.Group() self.block_size + offset_x # shape ar for alien in self.aliens.sprites():
modhe check position
self.obstacle_amount = 4 #
alien.rect.y += distance
obstacle number y = y_start + row_index *
self.block_size def alien_shoot(self):
self.obstacle_x_positions = [num
* (screen_width / block = if self.aliens.sprites():
self.obstacle_amount) for num in obstacle.Block(self.block_size,(241,79
range(self.obstacle_amount)] ,80),x,y) random_alien =
choice(self.aliens.sprites())
self.blocks.add(block)
self.create_multiple_obstacles(*self.ob laser_sprite =
stacle_x_positions, x_start = def create_multiple_obstacles(self, Laser(random_alien.rect.center,6,scree
screen_width / 10, y_start = 575) *offset, x_start, y_start ): n_height)

self.aliens = for offset_x in offset:


pygame.sprite.Group() self.alien_lasers.add(laser_sprite)
self.create_obstacle(x_start,
self.alien_lasers = y_start, offset_x) self.gunshot.play() # gunshot
pygame.sprite.Group() play hobe
def
self.alien_setup(rows = 6, cols = alien_setup(self,rows,cols,x_distance = def extra_alien_timer(self):
8) # number of alien ja hobe
self.extra_spawn_time -= 1
if self.extra_spawn_time <= 0: pygame.quit() pygame.time.wait(5000) # 5
second wait korbo
sys.exit()
self.extra.add(Extra(choice(['right','left' pygame.quit()
]),screen_width)) if self.aliens:
sys.exit()
self.extra_spawn_time = for alien in self.aliens:
randint(400,800) def run(self):

def collision_checks(self): pygame.sprite.spritecollide(alien,self.b self.player.update()


locks,True)
# player lasers ta ano theke kaj
korbe if self.aliens.update(self.alien_direction)
pygame.sprite.spritecollide(alien,self.p
if self.player.sprite.lasers: layer,False): self.alien_position_checker()

for laser in pygame.quit() self.alien_lasers.update()


self.player.sprite.lasers:
sys.exit() self.extra_alien_timer()
if
pygame.sprite.spritecollide(laser,self.bl def display_lives(self): # life gula self.extra.update()
ocks,True): ano theke show korbe , +10 use for
offset, -1 kore kumbe, self.collision_checks()
laser.kill()
for live in range(self.lives - 1):
aliens_hit = self.player.sprite.lasers.draw(screen)
pygame.sprite.spritecollide(laser,self.al x = self.live_x_start_pos + (live
* (self.live_surf.get_size()[0] + 10)) self.player.draw(screen)
iens,True)
screen.blit(self.live_surf,(x,8)) self.blocks.draw(screen)
if aliens_hit:
def display_score(self): self.aliens.draw(screen)
for alien in aliens_hit:

score_surf = self.alien_lasers.draw(screen)
self.score += alien.value
self.font.render(f'score:
self.extra.draw(screen)
laser.kill() {self.score}',False,'white')
self.display_lives()
self.ex.play() score_rect =
score_surf.get_rect(topleft = (10,-10)) self.display_score()
if
pygame.sprite.spritecollide(laser,self.e screen.blit(score_surf,score_rect) self.victory_message()
xtra,True):
def victory_message(self): if __name__ == '__main__':
laser.kill()
if not self.aliens.sprites(): pygame.init()
self.score += 500
victory_surf = screen_width = 1500
if self.alien_lasers: self.font.render('GAME DEV
THANKS \n THE screen_height = 765
for laser in self.alien_lasers: WINNER',False,'white')
screen =
# alien ano obastical block victory_rect = pygame.display.set_mode((screen_wid
ke hit korbr victory_surf.get_rect(center = th,screen_height)) # ano theke display
(screen_width / 2, screen_height / 2)) serface hoiche
if
pygame.sprite.spritecollide(laser,self.bl clock = pygame.time.Clock()
ocks,True): screen.blit(victory_surf,victory_rect)
game = Game()
laser.kill() def game_over(self):
ALIENLASER =
if game_over_surf = pygame.USEREVENT + 1
pygame.sprite.spritecollide(laser,self.pl self.font.render('GAME OVER \n
ayer,False): Thanks From GAME DEV Team',
True, 'white') pygame.time.set_timer(ALIENLASER
laser.kill() ,800)
game_over_rect =
print('great creator game_over_surf.get_rect(center = while True:
opi_da') (screen_width / 2, screen_height / 2))
for event in pygame.event.get():
self.bomb.play screen.blit(game_over_surf,
game_over_rect) if event.type == pygame.QUIT:
self.lives -= 1
pygame.display.flip() pygame.quit()
if self.lives <= 0:
sys.exit()
self.game_over()
if event.type == ALIENLASER: game.run() clock.tick(60) # frem ret limit 60
korchi
game.alien_shoot() pygame.display.flip()

screen.fill((30,30,30))

Player.py
import pygame if keys[pygame.K_SPACE] and self.ready:

from laser import Laser self.shoot_laser()

class Player(pygame.sprite.Sprite): self.ready = False

def __init__(self,pos,constraint,speed): self.laser_time = pygame.time.get_ticks()

super().__init__() self.uzi.play()

self.image = pygame.image.load('../python project/221-15- def recharge(self):


5948.png').convert_alpha()
if not self.ready:
self.rect = self.image.get_rect(midbottom = pos)
current_time = pygame.time.get_ticks()
self.speed = speed
if current_time - self.laser_time >= self.laser_cooldown:
self.max_x_constraint = constraint
self.ready = True
self.ready = True
def constraint(self):
self.laser_time = 0
if self.rect.left <= 0:
self.laser_cooldown = 100
self.rect.left = 0
self.lasers = pygame.sprite.Group()
if self.rect.right >= self.max_x_constraint:
self.uzi = pygame.mixer.Sound('../python project/uzi.wav')
self.rect.right = self.max_x_constraint
self.uzi.set_volume(0.2)
def shoot_laser(self):
def get_input(self):
self.lasers.add(Laser(self.rect.center,-8,self.rect.bottom))
keys = pygame.key.get_pressed()
def update(self):

self.get_input()
if keys[pygame.K_RIGHT]:
self.constraint()
self.rect.x += self.speed
self.recharge()
elif keys[pygame.K_LEFT]:
self.lasers.update()
self.rect.x -= self.speed

Alien.Py
import pygame self.rect = self.image.get_rect(topleft =
(x,y))
class Alien(pygame.sprite.Sprite):
if color == 'red': self.value = 100
def __init__(self,color,x,y):
elif color == 'green': self.value = 200
super().__init__()
else: self.value = 300
file_path = '../python project/' + color +
'.png' def update(self,direction):

self.image = self.rect.x += direction


pygame.image.load(file_path).convert_alpha()
class Extra(pygame.sprite.Sprite):
def __init__(self,side,screen_width): else:

super().__init__() x = -50

self.image = self.speed = 3
pygame.image.load('../python
project/extra.png').convert_alpha() self.rect = self.image.get_rect(topleft =
(x,80))
if side == 'right':
def update(self):
x = screen_width + 50
self.rect.x += self.speed
self.speed = - 3

Laser.py
import pygame self.height_y_constraint = screen_height

class Laser(pygame.sprite.Sprite): def destroy(self):

def __init__(self,pos,speed,screen_height): if self.rect.y <= -50 or self.rect.y >=


self.height_y_constraint + 50:
super().__init__()
self.kill()
self.image = pygame.Surface((4,20)) # wide 4
def update(self):
self.image.fill('white') #hight 40 pix
self.rect.y += self.speed
self.rect = self.image.get_rect(center = pos)
self.destroy()
self.speed = speed

Obastacle.py
import pygame

class Block(pygame.sprite.Sprite):

def __init__(self,size,color,x,y):

super().__init__()

self.image = pygame.Surface((size,size))

self.image.fill(color)

self.rect = self.image.get_rect(topleft = (x,y))

shape = [ # ano list of string and size

' xxx x xxx',

' xxxx xxx xxxx',

' xxxxxxxxxxxxxxxxxxxxxxx',

'xxxxxxxxxxxxxxxxxxxxxxxxxxx',

' xxxxxxxxxxxxxxxxxxxxxxx',

' xxxxxxxxxxxxxxx', # this shape is creat by sprite

' xxxx xxxx',

' xx xx' ]
Results
The the classic Two-dimensional “Target Shooting Space Invaders” successfully implements a playable
and enjoyable space shooter experience. It was developed using Python and Pygame.
The game offers the following functionalities:
➢ Player controls a spaceship that can move and fire lasers.
➢ Multiple types of aliens with varying point values appear and move horizontally.
➢ A special alien with a higher point value can appear occasionally on top of the screen.
➢ Collisions between the player and aliens/lasers are detected, affecting lives and score.
➢ The game displays the current score and remaining lives in up right and left.
➢ The inclusion of sound effects and a scoring system adds to the game's immersion.
➢ The game loop ensures consistent frame rates, providing a fluid gaming experience.
➢ The game ends when the player loses all lives or eliminates all aliens, displaying an appropriate
message.

Last of all point which is It Is Fun To Play.


Conclusion

This project demonstrates the use of Python and Pygame to create a simple yet engaging 2D
“Target Shooting Space Invaders” game. The game features intuitive controls, multiple levels, and
a scoring system that rewards players for their performance. The game is fully functional and
playable, with smooth graphics and responsive controls. The use of object-oriented programming
principles and sprites for game objects makes the code easy to read and maintain. Overall, this
project provides a solid foundation for creating more complex games using Python and Pygame.
Whether you are boy or grown up man this kind of small fun project will bring back the memory
of from the 2007. That small window screen and little light , sound of nostalgia will bring back
that smile. Life Parahin.

Referance

Jhion Adbar OPI …………….…ID 221-15-5948…………………Contribution = 45%


Tahsinur Rahaman Tanjim ……ID 221-15-5962………………... .. Contribution = 19.5%
Fazle Rabby Anas …………….ID 221-15-5252………………….. Contribution =19.5%
Shahariar Alom ……………….ID 221-15-4829………………….. Contribution = 16%

You might also like