Untitled
unknown
plain_text
9 months ago
2.0 kB
7
Indexable
Game Code:
import pygame
import random
# Initialize pygame
pygame.init()
# Screen settings
WIDTH, HEIGHT = 800, 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("2D Running Game")
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# Player settings
player_width, player_height = 50, 50
player_x, player_y = 100, HEIGHT - player_height - 50
player_velocity = 5
is_jumping = False
jump_height = 10
gravity = 0.5
jump_speed = jump_height
# Obstacle settings
obstacle_width, obstacle_height = 30, 50
obstacle_x = WIDTH
obstacle_y = HEIGHT - obstacle_height - 50
obstacle_speed = 5
# Game loop variables
running = True
clock = pygame.time.Clock()
# Game loop
while running:
screen.fill(WHITE)
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Player jump logic
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE] and not is_jumping:
is_jumping = True
if is_jumping:
player_y -= jump_speed
jump_speed -= gravity
if jump_speed < -jump_height:
is_jumping = False
jump_speed = jump_height
# Move obstacle
obstacle_x -= obstacle_speed
if obstacle_x < -obstacle_width:
obstacle_x = WIDTH + random.randint(100, 300)
# Collision detection
if (player_x < obstacle_x + obstacle_width and
player_x + player_width > obstacle_x and
player_y + player_height > obstacle_y):
print("Game Over!")
running = False
# Draw player and obstacle
pygame.draw.rect(screen, GREEN, (player_x, player_y, player_width, player_height))
pygame.draw.rect(screen, RED, (obstacle_x, obstacle_y, obstacle_width, obstacle_height))
pygame.display.update()
clock.tick(30)
pygame.quit()
---
How to Play:
1. Run the code.
2. Press the Spacebar (␣) to jump over obstacles.
3. If you hit an obstacle, the game ends.
Let me know if you want modifications!
Editor is loading...
Leave a Comment