0% found this document useful (0 votes)
24 views41 pages

Zarton Final

The document is a mini project report titled 'ZARTON' submitted by Jagan M and Jennis Joel L as part of their Python Essentials Laboratory course at MEPCO Schlenk Engineering College. The project involves designing a shooting game using Python and the Pygame library, where players control a cannon to shoot falling balls that split into smaller ones, with a focus on managing limited ammo and achieving high scores. The report includes sections on the project's aim, objectives, system study, design, implementation, results, and future enhancements.

Uploaded by

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

Zarton Final

The document is a mini project report titled 'ZARTON' submitted by Jagan M and Jennis Joel L as part of their Python Essentials Laboratory course at MEPCO Schlenk Engineering College. The project involves designing a shooting game using Python and the Pygame library, where players control a cannon to shoot falling balls that split into smaller ones, with a focus on managing limited ammo and achieving high scores. The report includes sections on the project's aim, objectives, system study, design, implementation, results, and future enhancements.

Uploaded by

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

ZARTON

A Mini Project Report

Submitted by

JAGAN M (REG. NO. 9517202406030)

JENNIS JOEL L (REG. NO. 9517202406034)

in

PYTHON ESSENTIALS LABORATORY

DEPARTMENT OF INFORMATION TECHNOLOGY

MEPCO SCHLENK ENGINEERING COLLEGE, SIVAKASI

(An Autonomous Institution, affiliated to Anna University, Chennai)

June 2025
BONAFIDE CERTIFICATE

Certified that this project report titled (ZARTON) the bonafide work of

Mr.M.JAGAN (Regno:9517202406030)and Mr.L.JENNIS JOEL(Regno:9517202406034),

who carried out the research under my supervision. Certified further, that to the best of my

knowledge the work reported herein does not form part of any other project report or

dissertation on the basis of which a degree or award was conferred on an earlier occasion on

this or any other candidate

Mrs. M. PRASHA MEENA, B.E., M.E., Dr.T.REVATHI, M.E., Ph.D.,

Assistant Professor, Head of the Department,


Department of Information Technology, Senior Professor,
Mepco Schlenk Engineering College, Department of Information Technology,
Sivakasi. Mepco Schlenk Engineering College,
Sivakasi.

Submitted for Viva-Voce Examination held at MEPCO SCHLENK ENGINEERING

COLLEGE (AUTONOMOUS), SIVAKASI on …………………………

Internal Examiner I Internal Examiner II


TABLE OF CONTENTS

CHAPTER CONTENTS PAGE


NO. NO.
CHAPTER 1 INTRODUCTION

1.1 Aim 2

1.2 Objective 2

1.3 Problem Statement 2

1.4 Concepts used 3

1.5 Organization of Report 5

CHAPTER 2 SYSTEM STUDY

2.1 System Overview 8

2.2 System Architecture 9

2.3 Features of the Game 10

CHAPTER 3 SYSTEM DESIGN

3.1 Introduction to Design Methodology 14

3.2 Flowchart 15

3.3 Algorithm used 16

3.4 Dashboard design 18

3.5 Concepts explanation 18

CHAPTER 4 IMPLEMENTATION

4.1 Environmental setup 22

4.2 Module-wise implementation 22

4.3 Coding standard followed 23


4.4 Integration of Modules 23

CHAPTER 5 RESULTS AND DISCUSSION

5.1 Screenshots 25

CHAPTER 6 CONCLUSION AND FUTURE ENHANCEMENT

6.1 Conclusion 28

6.2 Future Enhancement 28

CHAPTER 7 APPENDIX

7.1 Code 30

CHAPTER 8 REFERENCES 37
INTRODUCTION

1
CHAPTER 1

INTRODUCTION

1.1 AIM:

To design and develop a game using Python and the pygame library, where the player
controls a cannon to shoot bullets at falling balls. Each ball splits into smaller ones a limited
number of times when shot. The goal is to destroy all balls before they touch the ground, while
managing a limited number of bullets and obtain the highest possible score.

1.2 OBJECTIVE:

The primary objective of this project is to create a shooting game using Python and pygame
library. The player must:

• Control a movable cannon to shoot falling balls.


• Destroy all balls by shooting them before they reach the ground or hit the cannon.

• Efficiently using the ammo (maximum 100 bullets).


• Earn points by breaking balls, with higher scores for breaking smaller, higher-level
balls.
• Win the game by eliminating all spawned balls, or lose if ammo runs out or a ball
hits the cannon or ground.

1.3 PROBLEM STATEMENTS:

1. Real-Time Object Interaction


How can we simulate real-time movement and interaction between the cannon,
bullets, and falling balls using Python and pygame?
2. Ball Division Logic
How can we design the program such that the balls split into smaller ones upon being
shot, up to a certain number of divisions?
3. Collision Detection
What is the most efficient way to detect collisions between bullets and balls, as well
as between balls and the cannon or ground?

2
4. Resource Limitation
How can we implement and manage a limited number of bullets, adding strategy to
shooting rather than unlimited firing?
5. Game Over and Victory Conditions
How can we define clear game-over and victory conditions, such as when a ball hits
the ground, the cannon, or when all balls are destroyed?
6. Score and High Score Management
How can we accurately track the player's score and store the highest score
consistently between game sessions?
7. User Interface and Feedback
How can we display key information (score, high score, ammo) clearly during
gameplay, and show appropriate messages when the game is won or lost?

1.4 CONCEPTS USED:

1. Python Programming

• Core syntax, loops, functions, conditionals, and file handling (e.g., reading/writing
high scores).

2. Pygame Library

• Initialization, display handling, game loops, image loading and rendering.


• Event handling (keyboard inputs, quitting the game).
• Time and frame rate management (pygame.time.Clock()).

3. 2D Graphics & Game Rendering

• Drawing images and shapes (cannon, bullets, balls).


• Layered rendering of background and images.
• Collision rectangles (pygame.Rect) for hit detection.

3
4. Object Movement and Physics Simulation

• Continuous movement of falling balls and flying bullets.


• Gravity-like downward motion of balls.
• Splitting mechanism where balls divide into smaller versions upon shooting them.

5. Collision Detection

• Using colliderect() to detect overlaps between objects’ co-ordinates in axes.

6. Game Logic & State Management

• Game state control (running, game over, game won).


• Managing ammo and scoring system.
• Logic to limit the number of original balls and ammo.

7. File I/O

• Saving and loading high scores using text files (highscore.txt).

8. User Interface Design

• Displaying score, high score, ammo count.


• Game over and win messages based on gameplay outcome.

9. Randomization

• Random spawning position and delay for new balls using random.randint().

4
1.5 ORGANIZATION OF REPORT:

1. Introduction

• Aim: Develop a shooting game in Python using Pygame where a cannon shoots
falling, splitting balls.
• Objectives: Control the cannon, manage limited ammo, destroy balls before they
reach the ground, and achieve high scores.
• Key Problems: Real-time interaction, ball splitting logic, collision detection, game
conditions, UI, and score tracking.
• Technologies: Python, Pygame, 2D graphics, game loops, file I/O, and randomness.

2. System Study

• Overview: Modular structure includes input handling, rendering, game logic, score
management, state control, and timing.
• Architecture: Six key modules – Input, Game Logic, Rendering, Data Storage,
Timing, Main Loop.
• Features: Cannon movement, 100 bullet limit, ball splitting (3 levels), point system
(10/20/30), high score saving, random ball spawning, win/loss conditions, 70 FPS
smooth gameplay.

3. System Design

• Methodology: Modular and iterative approach to simplify development and


debugging.
• Game Algorithm: Initialize → Load assets → Event handling → Update positions →
Check collisions → Display updates → Repeat until quit.
• UI Layout: Top-left: Score/High Score; Top-right: Ammo; Center: Game area,
cannon, and messages.
• Concepts: Game loop, object movement, collision detection (Rect), randomness for
ball spawning, modular functions, and persistent high score using files.

5
4. Implementation

• Setup: Requires Python 3, Pygame, and image assets. Run via terminal.
• Modules: Initialization, assets/constants, ball/bullet logic, collisions, player control,
UI, high score handling, game state, and main loop.
• Coding Standards: Clean, modular, with reusable functions and structured constants.
• Integration: Pygame manages graphics/input; Random controls variability in
spawning.

5. Conclusion & Future Work

• Conclusion: Demonstrates interactive gameplay with limited ammo and scoring.


Encourages replay with high score tracking.
• Future Enhancements: Power-ups, increasing difficulty, diverse enemies, and
enhanced visuals to improve engagement.

6
SYSTEM STUDY

7
CHAPTER 2

SYSTEM STUDY

2.1 SYSTEM OVERVIEW:

1. User Input Module

• Handles keyboard input (left/right arrow keys to move cannon, spacebar to shoot).

2. Rendering Engine

• Uses Pygame to load, scale, and render images (cannon, bullet) and shapes (balls).
• Displays text (score, high score, ammo) and game messages (win/lose).

3. Game Logic Controller

• The logic of this game is managed by :


o Ball spawning and movement
o Ball splitting upon being shot
o Bullet movement
o Collision detection between objects
o Win/lose conditions

4. State Management

• Controls the game states: running, game over, game won.


• Tracks key variables: score, ammo, high score, number of balls left.

5. Scoring & Persistence

• Calculates score based on ball level.


• Saves and loads high score using a text file (highscore.txt).

6. Timing System

• Controls frame rate (60 FPS).


• Adds delays between ball spawns using timestamps (pygame.time.get_ticks()).

8
2.2 SYSTEM ARCHITECTURE:

The System Architecture of the game “ZARTON” primarily involves the game
engine, input handling, rendering and game logic. It includes:

1. Input Module

• Function: Capturing and processing user inputs.


• Handles:
o Left/Right arrow keys for cannon movement.
o Spacebar for firing bullets.
o Quit event to exit the game.

2. Game Logic Module

• Function: Managing game rules and mechanics.


• Handles:
o Cannon position updates.
o Bullet firing, movement, and removal.
o Ball generation, falling, and splitting.
o Collision detection (bullet-ball, ball-cannon, ball-ground).
o Score calculation.
o Game over and win conditions.

3. Rendering Module

• Function: Drawing all visual elements to the screen frame by frame.


• Handles:
o Background and walls.
o Cannon, bullets, and balls.
o Graphical elements (score, high score, ammo count).
o Game result message (win/lose).

9
4. Data Storage Module

• Function: Managing persistent storage.


• Handles:
o Loading high score from a file at startup.
o Saving new high score at the end of the game (if beaten).

5.Timing and Control Module

• Function: Controlling game timing and frame updates.


• Handles:
o Frame rate (via pygame.time.Clock()).
o Ball spawn delay management.

6.Main Game Loop (Controller)

• Function:
o Repeats the game cycle (input → logic → render).
o Manages the running state and transitions between game phases.

2.3 FEATURES OF THE GAME:

1. Cannon Control

• Player controls a cannon using the left and right arrow keys.
• Fires bullets using the spacebar.

2. Limited Ammo System

• The player has a maximum of 100 bullets.


• Ammo count is shown on-screen.
• Game ends if the player runs out of ammo and no bullets are left in the air.

10
3. Ball Spawning and Splitting

• Balls fall from the top and split into smaller balls when hit.
• There are 3 levels of ball sizes:
o Level 1: Large
o Level 2: Medium
o Level 3: Small
• Splitting stops at level 3 (smallest).

4. Score System

• Player earns points for destroying balls:


o Level 1: 10 points
o Level 2: 20 points
o Level 3: 30 points
• Current score and high score are displayed during gameplay.

5. High Score Persistence

• The highest score is saved to a file (highscore.txt) and loaded every time the game
starts.

6. Win and Game-Over Conditions

• Win: Player destroys all balls before any touch the ground or cannon.
• Game Over:
o A ball hits the cannon.
o A ball reaches the ground.
o Player runs out of ammo and bullets.

7. Random Ball Spawning

• New balls spawn at random intervals (2–5 seconds).


• A maximum of 10 original balls are generated per game.

11
8. Simple 2D Graphics

• Clean and colorful 2D visuals using basic shapes and images.


• Includes visual boundaries (walls, ground) and themed cannon/bullet sprites.

9. Smooth Gameplay

• Runs at a stable 70 frames per second (FPS) using pygame.time.Clock.

12
SYSTEM DESIGN

13
CHAPTER 3

SYSTEM DESIGN

3.1 INTRODUCTION TO DESIGN METHODOLOGY:

Designing a game, even a relatively simple one, requires a structured and thoughtful
approach to ensure that all parts of the system work together smoothly. For this project, we
followed a modular and iterative design methodology, focusing on clarity, functionality, and
ease of development.

We began by outlining the core gameplay idea: a player-controlled cannon that shoots bullets
at falling balls which split into smaller ones, with limited ammo and scoring mechanics. From
there, we identified the key components of the game such as the player (cannon), bullets, balls,
collision detection, user interface, and win/loss conditions.

To manage complexity, we broke the project down into manageable modules—each


responsible for a specific function (like input handling, game logic, rendering, etc.). This
modular approach made it easier to test, debug, and update each part individually without
affecting the rest of the game.

By combining planning with flexibility, we were able to create a functional, responsive, and
enjoyable game experience using Python and Pygame.

14
3.2 FLOWCHART:

15
3.3 ALGORITHM USED:

1.Start the program


Initialize the Pygame library and create the game window (800×600).

2. Load assets
Load and scale the cannon, bullet, and ball images.
Load fonts for displaying score, ammo, and messages.

3. Initialize variables
Set cannon position, bullet list, ball list, ammo = 100, score = 0, etc.
Load high score from a text file.

4. Create the first ball


Generate a level-1 ball and add it to the list of balls.

5 Enter the main game loop

6 Handle events
a. Check if the quit button is clicked → exit game.
b. If the spacebar is pressed AND the game is not over AND ammo > 0:

• Fire a bullet
• Decrease ammo by 1

7 Handle key input for cannon movement


a. If LEFT key is pressed → move cannon left
b. If RIGHT key is pressed → move cannon right

8 Spawn new balls over time


If the timer has passed and the original ball limit isn’t reached:

• Generate a new level-1 ball


• Increase spawned ball count

16
9. Move game objects
a. Move balls downward
b. Move bullets upward
c. Remove bullets that move off the screen

10. Check collisions


a. If a bullet hits a ball:

• Remove both
• Increase score (based on level)
• If the ball can split, add two smaller balls
b. If a ball touches the cannon or the ground:
• Set game over

11 Check win/loss conditions


a. If all balls are destroyed and no more to spawn → win
b. If ammo = 0 and bullets = 0 → game over

12 Draw everything on the screen


a. Background, cannon, bullets, balls
b. Score, high score, ammo
c. Border walls and ground

13 If game is over
a. Show "Game Over" or "You Win"
b. If score > high score → save new high score

14 Update the screen


Refresh display and limit frame rate to 70 FPS

15 Repeat steps 6 to 14 until user quits

16 End the game


Quit pygame and close the window

17
3.4 DASHBOARD DESIGN:

The game dashboard consists of the following:

COMPONENT DESCRIPTION
SCORE Top-left corner. Shows player's current score in smaller font.
DISPLAY
HIGH SCORE Next to score. Shows highest score stored from past plays.
AMMO Top-right corner. Shows remaining bullets (starts at 100).
COUNT
GAME Center of screen (when game over or won).
MESSAGE Displays “Game Over” or “You Win”.
GAME AREA Center of screen. Falling balls and bullets interact here.
CANNON Fixed at bottom center. Player moves it left/right and shoots from it.
WALLS & Black side/top walls and brown bottom ground for visual
GROUND boundaries.

3.5 CONCEPT EXPLANATION:

3.5.1 Pygame Library

The foundation of the game is built on the Pygame library, a powerful module designed
for making video games in Python. It simplifies many of the complex tasks involved in game
development, such as rendering graphics, handling sound, and managing user input. In this
project, Pygame is used extensively for everything from creating the game window and
drawing images to updating the display and capturing keyboard inputs.

3.5.2 Event Handling

A core part of interactive applications is event handling, which refers to detecting and
responding to player actions. In this game, event handling captures key events such as pressing
the spacebar to fire a bullet, using the left or right arrow keys to move the cannon, or closing
the game window. These inputs are constantly monitored in the game loop, ensuring responsive
and real-time gameplay.

18
3.5.3 Game Loop

The game operates through a continuous cycle known as the game loop. This loop is
responsible for maintaining the flow of the game—it keeps checking for player inputs, updating
the positions of objects (like bullets and balls), handling collisions, drawing updated elements
on the screen, and controlling the game's timing. It runs until the game ends, ensuring that the
screen refreshes smoothly at the desired frame rate.

3.5.4 Collision Detection

To make the game interactive and realistic, collision detection plays a crucial role. It
checks whether two objects overlap—in this case, whether a bullet has hit a ball or if a ball
touches the cannon or the ground. Using Pygame’s built-in rectangle collision detection
(colliderect()), the game can determine when to destroy a ball, split it into smaller balls, or end
the game based on a hit.

3.5.5 Object Movement

The animation in the game is achieved by updating object positions over time. Balls
fall downward by incrementing their vertical position every frame, while bullets move upward
by reducing their Y-coordinates. The cannon itself shifts left or right in response to the arrow
keys, allowing the player to aim and shoot strategically. This constant position adjustment
creates the illusion of smooth movement.

3.5.6 Randomization

To make the game more dynamic and unpredictable, randomization is applied in


spawning the balls. Each ball appears at a random horizontal position at the top of the screen,
and the timing between their appearances is randomized using Python’s random.randint()
function. This keeps the gameplay fresh and challenging every time it's played.

19
3.5.7 Data Structures

Efficient use of data structures makes the game logic manageable. Lists are used to
store all active bullets and balls, while dictionaries represent individual balls with attributes
such as position, radius, and level. This structured approach allows for easier updates,
manipulation, and collision checks of each game object.

3.5.8 Functions

The code is organized into reusable functions to improve readability and modularity.
Functions such as create_ball(), draw_ui(), and handle_collision() encapsulate specific tasks,
making it easier to understand and manage the game’s logic. This modular design also allows
for easier debugging and future updates to the game.

3.5.9 File I/O

File input and output are used to maintain a persistent high score. When the game starts,
it attempts to read the highest score from a file named highscore.txt. If the player achieves a
new high score, the game writes this updated value back to the file. This ensures that progress
is not lost between sessions.

3.5.10 Game States

The concept of game states is crucial for controlling different phases of the game, such
as playing, game over, and game won. Boolean flags like game_over and game_won help in
determining what logic to execute, what UI elements to show, and when to stop or reset the
game. This structure adds clarity and control to the game flow.

20
IMPLEMENTATION

21
CHAPTER 4

IMPLEMENTATION

4.1 ENVIRONMENTAL SETUP:

To run the cannon shooting game, you need Python installed (version 3 or above) on
your computer. You also need to install the Pygame library using the command pip install
pygame. A code editor like VS Code or PyCharm can be used to write and run the code. Make
sure the game image files (cannon.png, bullet.png, mpl.png) are in the same folder as the
Python script. Once everything is ready, you can start the game by running the script with
python filename.py in your terminal or command prompt.

4.2 MODULE-WISE IMPLEMENTATION:

The game is built using two primary Python modules: pygame and random. The
pygame module handles all visual and interactive components of the game. It is responsible for
creating the game window, drawing and updating the cannon, bullets, and balls, as well as
detecting user input like key presses for movement and shooting. It also manages the main
game loop, event handling, collision detection, score display, and screen refreshing. Through
pygame, images are loaded and scaled appropriately, and different game elements are rendered
on the screen with real-time responsiveness.

On the other hand, the random module is used to bring unpredictability to the game. It
determines the timing and position of new ball spawns by generating random intervals and
coordinates. This randomness adds challenge and variation, ensuring the gameplay remains
engaging and non-repetitive. While pygame controls the structure and visuals, random
influences the gameplay dynamics. Together, these modules make the game functional,
interactive, and enjoyable.

22
4.3 CODING STANDARD FOLLOWED:

The game code follows clean, readable, and organized Python coding practices to
ensure maintainability and ease of understanding. Constants such as screen dimensions, speeds,
and limits are defined at the beginning for easy configuration. The code is separated into blocks:
for image loading, event handling, drawing, updates, and collision detection. Functions are kept
short and focused on a single task, following the Single Responsibility Principle. The script
avoids repeated values by using variables or dictionaries (e.g., ball radius). PEP 8 guidelines
are generally followed, making the code neat and Pythonic.

4.4 INTEGRATION OF MODULES:

The pygame module serves as the core framework for building and running the game.
It is responsible for creating the game window, handling user inputs like keyboard events,
rendering the cannon, bullets, and falling balls, and updating the display during each frame of
the game loop. Additionally, pygame manages the game's timing using Clock, supports
drawing shapes like circles (for the balls), and uses Rect objects for detecting collisions
between bullets and balls, or balls and the cannon. The game's visual feedback, including score
display, ammo count, and game-over messages, is also handled using pygame's font rendering
capabilities.

The random module plays a supportive yet important role by introducing unpredictability into
the game. It is mainly used to randomize the horizontal spawning position of the falling balls
and to determine the delay between their appearances. This randomness ensures that each game
session feels different, as the timing and positions of the balls vary with each run. By adding
variability to when and where balls appear, random increases the challenge of the game,
making it less repetitive and more engaging for the player.

23
RESULT AND DISCUSSION

24
CHAPTER 5

RESULT AND DISCUSSION

5.1 SCREENSHOTS:

5.1.1. Starting of the game

5.1.2. While playing the game

25
5.1.3. Winning State

5.1.4. Game-Over State

26
CONCLUSION AND FUTURE
ENHANCEMENT

27
CHAPTER 6

CONCLUSION AND FUTURE ENHANCEMENT

6.1 CONCLUSION:

This game is a fun and interactive shooting challenge made with Python and Pygame.
Players control a cannon to shoot falling balls that split into smaller ones, making the game
progressively harder. It uses core game features like handling player input, detecting collisions,
tracking scores, and smoothly updating the screen in real-time.

With limited ammo and a set number of balls, the game keeps things balanced and engaging.
The high score feature encourages players to keep improving. Overall, this project shows how
to build a simple yet enjoyable game while learning important programming and game
development skills.

6.2 FUTURE ENHANCEMENT:

The game provides a solid foundation for understanding core game development
concepts using Python and Pygame. It features fundamental mechanics like real-time
movement, shooting, collision detection, and score tracking. In its current form, the game is
enjoyable and interactive, with falling balls that split into smaller ones, limited ammo, and a
high score system to increase replay value.

Future enhancements like increasing ball speed over time, adding random power-ups, and
introducing different enemy types can make the game more engaging and challenging. These
additions would elevate the gameplay experience while also offering opportunities to explore
more advanced programming and design techniques.

28
APPENDIX

29
CHAPTER 7

APPENDIX

7.1 CODE:

import pygame

import random

pygame.init()

screen = pygame.display.set_mode((800, 600))

pygame.display.set_caption("Zarton")

pygame.display.set_icon(pygame.image.load('mpl.png'))

def load_scaled(img_path, size):

return pygame.transform.scale(pygame.image.load(img_path).convert_alpha(), size)

cannon_img = load_scaled("cannon.png", (60, 80))

bullet_img = load_scaled("bullet.png", (40, 20))

cannon_width, cannon_height = cannon_img.get_size()

ball_radii = {1: 50, 2: 25, 3: 12}

cannon_speed, bullet_speed, ball_fall_speed = 5, 7, 2

max_original_balls, ammo = 10, 100

cannon_x, cannon_y = 370, 600 - cannon_height

bullets, balls = [], []

30
spawned_balls = 0

score = 0

game_over = game_won = False

last_spawn, next_delay = pygame.time.get_ticks(), random.randint(2000, 5000)

font, small_font = pygame.font.SysFont(None, 60), pygame.font.SysFont(None, 36)

clock = pygame.time.Clock()

def load_highscore():

try: return int(open("highscore.txt").read())

except: return 0

def save_highscore(score):

with open("highscore.txt", "w") as f: f.write(str(score))

highscore = load_highscore()

def create_ball(level=1):

r = ball_radii[level]

return {"x": random.randint(r, 800 - r), "y": 0, "radius": r, "level": level}

def draw_ui():

for i, text in enumerate([f"Score: {score}", f"High Score: {highscore}", f"Ammo:


{ammo}"]):

screen.blit(small_font.render(text, True, (0, 0, 0)), (20, 20 + i * 30))

31
def draw_walls():

wall_color, gnd_color = (33, 33, 33), (110, 44, 0)

pygame.draw.rect(screen, wall_color, (0, 0, 800, 10))

pygame.draw.rect(screen, gnd_color, (0, 590, 800, 10))

pygame.draw.rect(screen, wall_color, (0, 0, 10, 600))

pygame.draw.rect(screen, wall_color, (790, 0, 10, 600))

def ball_rect(ball):

r = ball["radius"]

return pygame.Rect(ball["x"] - r, ball["y"] - r, 2 * r, 2 * r)

def handle_collision():

global score

for bullet in bullets[:]:

b_rect = pygame.Rect(bullet[0], bullet[1], bullet_img.get_width(),


bullet_img.get_height())

for ball in balls[:]:

if ball_rect(ball).colliderect(b_rect):

bullets.remove(bullet)

balls.remove(ball)

score += 10 * ball["level"]

if ball["level"] < 3:

lvl, r = ball["level"] + 1, ball_radii[ball["level"] + 1]

offset = r + 5

32
balls.extend([

{"x": max(ball["x"] - offset, r), "y": ball["y"], "radius": r, "level": lvl},

{"x": min(ball["x"] + offset, 800 - r), "y": ball["y"], "radius": r,"level": lvl}])

break

balls.append(create_ball())

spawned_balls += 1

run = True

while run:

screen.fill((200, 220, 255))

now = pygame.time.get_ticks()

for event in pygame.event.get():

if event.type == pygame.QUIT:

run = False

elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE and not


game_over and ammo > 0:

bullets.append([cannon_x + cannon_width // 2 - bullet_img.get_width() // 2,


cannon_y])

ammo -= 1

keys = pygame.key.get_pressed()

if not game_over:

if keys[pygame.K_LEFT] and cannon_x > 0: cannon_x -= cannon_speed

if keys[pygame.K_RIGHT] and cannon_x < 800 - cannon_width: cannon_x +=


cannon_speed

33
if spawned_balls < max_original_balls and now - last_spawn >= next_delay:

balls.append(create_ball())

spawned_balls += 1

last_spawn = now

next_delay = random.randint(2000, 5000)

for ball in balls:

ball["y"] += ball_fall_speed

pygame.draw.circle(screen, (200, 0, 0), (int(ball["x"]), int(ball["y"])), ball["radius"])

for bullet in bullets[:]:

bullet[1] -= bullet_speed

if bullet[1] < 0:

bullets.remove(bullet)

else:

screen.blit(bullet_img, bullet)

handle_collision()

screen.blit(cannon_img, (cannon_x, cannon_y))

cannon_rect = pygame.Rect(cannon_x, cannon_y, cannon_width, cannon_height)

for ball in balls:

if ball_rect(ball).colliderect(cannon_rect) or ball["y"] + ball["radius"] >= 590:

game_over = True

if not game_over and spawned_balls == max_original_balls and not balls:

game_won = game_over = True

if not game_over and ammo == 0 and not bullets:

game_over = True

34
draw_ui()

draw_walls()

if game_over:

if score > highscore:

highscore = score

save_highscore(highscore)

msg = font.render("You Win!" if game_won else "Game Over!", True, (0, 150, 0) if
game_won else (255, 0, 0))

screen.blit(msg, (300, 250))

pygame.display.update()

clock.tick(70)

pygame.quit()

35
REFERENCES

36
CHAPTER 8

REFERENCES

• Python Official Documentation


• Pygame Documentation
• Python- Random Library Documentation

37

You might also like