Code:
import pygame
import random
# Initialize Pygame
pygame.init()
# Screen dimensions
WIDTH, HEIGHT = 600, 800
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Moving Bike Game")
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (50, 50, 50)
YELLOW = (255, 255, 0)
RED = (200, 0, 0)
# Clock
clock = pygame.time.Clock()
FPS = 60
# Load bike image
bike_img = pygame.image.load("bike.png")
bike_img = pygame.transform.scale(bike_img, (50, 100)) # Resize if needed
bike_width, bike_height = bike_img.get_size()
bike_x = WIDTH // 2 - bike_width // 2
bike_y = HEIGHT - bike_height - 30
bike_speed = 7
# Road
road_width = 300
road_x = WIDTH // 2 - road_width // 2
road_lines = []
line_height = 80
line_width = 10
line_speed = 7
for i in range(0, HEIGHT, line_height * 2):
road_lines.append(pygame.Rect(WIDTH//2 - line_width//2, i, line_width, line_height))
# Obstacles
obstacle_width, obstacle_height = 50, 100
obstacle_speed = 7
obstacles = []
# Score
score = 0
font = pygame.font.SysFont(None, 35)
def draw_bike(x, y):
screen.blit(bike_img, (x, y))
def draw_obstacles(obstacles):
for obs in obstacles:
pygame.draw.rect(screen, RED, obs)
def draw_road():
pygame.draw.rect(screen, GRAY, (road_x, 0, road_width, HEIGHT))
for line in road_lines:
pygame.draw.rect(screen, YELLOW, line)
def move_lines():
for line in road_lines:
line.y += line_speed
if line.y > HEIGHT:
line.y = -line_height
def display_score(score):
text = font.render(f"Score: {score}", True, BLACK)
screen.blit(text, (10, 10))
# Game loop
running = True
while running:
screen.fill(WHITE)
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Bike movement
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and bike_x > road_x:
bike_x -= bike_speed
if keys[pygame.K_RIGHT] and bike_x + bike_width < road_x + road_width:
bike_x += bike_speed
# Create obstacles
if random.randint(1, 50) == 1:
obs_x = random.randint(road_x, road_x + road_width - obstacle_width)
obs_y = -obstacle_height
obstacles.append(pygame.Rect(obs_x, obs_y, obstacle_width, obstacle_height))
# Move obstacles
for obs in obstacles:
obs.y += obstacle_speed
# Remove off-screen obstacles
obstacles = [obs for obs in obstacles if obs.y < HEIGHT]
# Check collision
bike_rect = pygame.Rect(bike_x, bike_y, bike_width, bike_height)
for obs in obstacles:
if bike_rect.colliderect(obs):
running = False # Game over
# Move road lines
move_lines()
# Draw everything
draw_road()
draw_bike(bike_x, bike_y)
draw_obstacles(obstacles)
display_score(int(score))
# Update score
score += 1 / FPS
pygame.display.update()
clock.tick(FPS)
pygame.quit()
Output:
Code Explanation:
1) Importing Modules
import pygame
import random
pygame → game library for graphics, input, sound.
random → used for generating random obstacle positions.
2) Initialize Pygame
pygame.init()
Starts all pygame modules (graphics, events, fonts, etc.).
Required before using most pygame functions.
3) Screen Setup
WIDTH, HEIGHT = 600, 800
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Moving Bike Game")
Defines game window size: 600px wide × 800px tall.
pygame.display.set_mode → creates the window.
set_caption → gives window a title.
4) Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (50, 50, 50)
YELLOW = (255, 255, 0)
RED = (200, 0, 0)
RGB tuples for different colors used (background, road, obstacles, lines).
5) Clock & FPS
clock = pygame.time.Clock()
FPS = 60
Clock regulates speed of the game loop.
FPS = 60 → 60 frames per second target.
6) Bike Setup
bike_img = pygame.image.load("bike.png")
bike_img = pygame.transform.scale(bike_img, (50, 100))
bike_width, bike_height = bike_img.get_size()
bike_x = WIDTH // 2 - bike_width // 2
bike_y = HEIGHT - bike_height - 30
bike_speed = 7
Loads the bike image.
Resizes to 50×100 pixels.
Gets size → (bike_width, bike_height).
Places bike near bottom center of screen.
bike_speed = 7 → movement per key press.
7) Road Setup
road_width = 300
road_x = WIDTH // 2 - road_width // 2
road_lines = []
line_height = 80
line_width = 10
line_speed = 7
Road is 300px wide, centered horizontally.
Road divider lines defined with height 80px, width 10px, moving speed 7.
Initial Divider Lines
for i in range(0, HEIGHT, line_height * 2):
road_lines.append(pygame.Rect(WIDTH//2 - line_width//2, i, line_width, line_height))
Creates vertical dashed yellow lines down the middle.
Each line is a Rect object (rectangle).
Placed every 160px apart (line_height * 2).
8) Obstacles
obstacle_width, obstacle_height = 50, 100
obstacle_speed = 7
obstacles = []
Obstacles are red rectangles (50×100).
They move down at speed 7.
Stored in list obstacles.
9) Score Setup
score = 0
font = pygame.font.SysFont(None, 35)
Score starts at 0.
Font object created to draw score text on screen.
10) Helper Functions
Draw Bike
def draw_bike(x, y):
screen.blit(bike_img, (x, y))
Renders bike image at given (x, y) position.
Draw Obstacles
def draw_obstacles(obstacles):
for obs in obstacles:
pygame.draw.rect(screen, RED, obs)
Draws each red obstacle rectangle.
Draw Road
def draw_road():
pygame.draw.rect(screen, GRAY, (road_x, 0, road_width, HEIGHT))
for line in road_lines:
pygame.draw.rect(screen, YELLOW, line)
Draws gray road and yellow divider lines.
Move Road Lines
def move_lines():
for line in road_lines:
line.y += line_speed
if line.y > HEIGHT:
line.y = -line_height
Moves yellow lines downward.
If a line goes off screen → reset above screen.
Display Score
def display_score(score):
text = font.render(f"Score: {score}", True, BLACK)
screen.blit(text, (10, 10))
Creates score text image.
Draws at top-left corner.
11) Game Loop
running = True
while running:
Main loop that keeps the game running until player quits or crashes.
Event Handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
Checks for window close event.
If closed → stop game loop.
Bike Movement
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and bike_x > road_x:
bike_x -= bike_speed
if keys[pygame.K_RIGHT] and bike_x + bike_width < road_x + road_width:
bike_x += bike_speed
Left arrow → move bike left (within road bounds).
Right arrow → move bike right (within road bounds).
Create Obstacles
if random.randint(1, 50) == 1:
obs_x = random.randint(road_x, road_x + road_width - obstacle_width)
obs_y = -obstacle_height
obstacles.append(pygame.Rect(obs_x, obs_y, obstacle_width, obstacle_height))
Random chance (1/50) each frame to spawn an obstacle.
Obstacle appears above screen (-obstacle_height) and moves downward.
Move Obstacles
for obs in obstacles:
obs.y += obstacle_speed
Shifts each obstacle downward every frame.
Remove Off-Screen Obstacles
obstacles = [obs for obs in obstacles if obs.y < HEIGHT]
Keeps only those obstacles still on screen.
Collision Check
bike_rect = pygame.Rect(bike_x, bike_y, bike_width, bike_height)
for obs in obstacles:
if bike_rect.colliderect(obs):
running = False
Converts bike to rectangle.
If bike overlaps any obstacle → crash → game ends.
Move Road Lines
move_lines()
Keeps divider lines scrolling.
Draw Everything
draw_road()
draw_bike(bike_x, bike_y)
draw_obstacles(obstacles)
display_score(int(score))
Renders road, bike, obstacles, and score text.
Update Score
score += 1 / FPS
Score increases gradually with time.
Dividing by FPS ensures score = time in seconds.
Update Screen
pygame.display.update()
clock.tick(FPS)
pygame.display.update() → refresh screen with new frame.
clock.tick(FPS) → controls speed so game runs at 60 FPS.
12) Quit Game
pygame.quit()
Closes pygame window when game ends.


0 Comments:
Post a Comment