Pygame Code Explanation
1. Imports and Initialization:
import pygame
import random
- import pygame: Imports the Pygame library, which is used to create games and handle graphics.
- import random: Imports the random module, which allows for random number generation, useful
for creating obstacles at random positions.
pygame.init()
- pygame.init(): Initializes all the Pygame modules that are required for the game (e.g., the display,
clock).
2. Screen Setup:
screen_width, screen_height = 800, 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Score-based Obstacle Game")
- screen_width, screen_height: Defines the width and height of the game window (800x600 pixels).
- pygame.display.set_mode(): Creates the window for the game, setting the dimensions to the
values defined above.
- pygame.display.set_caption(): Sets the window's title to "Score-based Obstacle Game".
3. Colors:
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
- Defines color variables in RGB format: white, black, red, and green.
4. Clock and Paddle Setup:
clock = pygame.time.Clock()
- pygame.time.Clock(): Creates a clock object that controls the game's frame rate.
paddle_width, paddle_height = 60, 20
paddle_x = (screen_width - paddle_width) // 2
paddle_y = screen_height - 2 * paddle_height
paddle_speed = 10
paddle = pygame.Rect(paddle_x, paddle_y, paddle_width, paddle_height)
- paddle_width, paddle_height: Dimensions of the paddle (60 pixels wide, 20 pixels tall).
- paddle_x: Initial horizontal position of the paddle, centered on the screen.
- paddle_y: Initial vertical position of the paddle, placed near the bottom of the screen.
- paddle_speed: Speed at which the paddle moves left or right.
- pygame.Rect(): Defines the paddle as a rectangle that will be rendered on the screen.
5. Paddle Length and Obstacle Setup:
paddle_lengths = [paddle_height]
size_increase = 5
obstacle_width, obstacle_height = 30, 20
obstacle_speed = 5
obstacles = []
score = 0
- paddle_lengths: A list that stores the length of the paddle (initially the paddle's height).
- size_increase: The amount by which the paddle increases when a green obstacle is hit.
- obstacle_width, obstacle_height: Dimensions of the obstacles.
- obstacle_speed: The speed at which obstacles fall.
- obstacles: A list to store all the obstacles currently on the screen.
- score: Keeps track of the player's score.
6. Event Handling:
def handle_events():
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
- handle_events(): Checks for game events like quitting the game. If the quit event is triggered (e.g.,
closing the window), the game will exit using pygame.quit().
7. Paddle Movement:
def move_paddle(direction):
global paddle_x
if direction == "left" and paddle_x > 0:
paddle_x -= paddle_speed
elif direction == "right" and paddle_x < screen_width - paddle_width:
paddle_x += paddle_speed
- move_paddle(direction): Moves the paddle left or right. It checks if the paddle is within screen
boundaries and updates its position accordingly.
8. Paddle Size Increase and Decrease:
def increase_size():
new_length = paddle_lengths[-1] + size_increase
paddle_lengths.append(new_length)
print(paddle_lengths)
def size_decrease():
paddle_lengths.pop()
print(paddle_lengths)
if len(paddle_lengths) < 1:
pygame.quit()
- increase_size(): Increases the paddle's size by adding the new size to paddle_lengths each time
the player hits a green obstacle.
- size_decrease(): Decreases the paddle size by removing the last added length when the player
hits a red obstacle. If the paddle size becomes 0, the game quits.
9. Creating Obstacles:
def create_obstacle():
obstacle_x = random.randint(0, screen_width - obstacle_width)
obstacle_y = 0
obstacle_color = random.choice([green, red])
r = pygame.Rect(obstacle_x, obstacle_y, obstacle_width, obstacle_height)
obstacles.append({"rect": r, "color": obstacle_color})
- create_obstacle(): Creates an obstacle at a random horizontal position and at the top of the
screen. The color is randomly chosen to be green or red, and the obstacle is added to the obstacles
list.
10. Drawing Paddle and Obstacles:
def draw_paddle():
global paddle
paddle = pygame.Rect(paddle_x, paddle_y - paddle_lengths[-1], paddle_width,
paddle_lengths[-1])
pygame.draw.rect(screen, green, paddle)
def draw_obstacles():
for obstacle in obstacles:
pygame.draw.rect(screen, obstacle["color"], obstacle["rect"])
- draw_paddle(): Updates the paddle size and draws it on the screen using pygame.draw.rect().
- draw_obstacles(): Draws each obstacle in the obstacles list on the screen with its respective color
and position.
11. Collision Detection and Score Display:
def check_collision():
global score
for obstacle in obstacles[:]:
if obstacle["rect"].colliderect(paddle):
if obstacle["color"] == green:
increase_size()
score += 1
elif obstacle["color"] == red:
size_decrease()
score -= 1
obstacles.remove(obstacle)
elif obstacle["rect"].y > screen_height:
obstacles.remove(obstacle)
- check_collision(): Checks if an obstacle collides with the paddle using colliderect(). If it does, the
paddle size and score are updated depending on the color of the obstacle. If an obstacle goes
off-screen, it is removed from the obstacles list.
def display_score():
font = pygame.font.Font(None, 36)
score_text = font.render(f"Score: {score}", True, white)
screen.blit(score_text, (10, 10))
- display_score(): Displays the current score at the top-left corner of the screen.
12. Main Game Loop:
while True:
handle_events()
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
move_paddle("left")
if keys[pygame.K_RIGHT]:
move_paddle("right")
if random.randint(1, 10) == 1:
create_obstacle()
for obstacle in obstacles:
obstacle["rect"].y += obstacle_speed
check_collision()
screen.fill(black)
draw_paddle()
draw_obstacles()
display_score()
pygame.display.flip()
clock.tick(30)
- Main Game Loop: This is the main game loop that:
1. Handles events like quitting.
2. Checks for key presses (left and right arrow keys) and moves the paddle.
3. Randomly generates obstacles.
4. Updates the obstacle positions and checks for collisions.
5. Clears the screen and redraws all objects (paddle, obstacles, score).
6. Updates the display and ensures the game runs at 30 frames per second (clock.tick(30)).