Untitled

 avatar
unknown
plain_text
a month ago
1.6 kB
2
Indexable
import pygame
import random

# Initialize Pygame
pygame.init()

# Game Constants
WIDTH, HEIGHT = 500, 600
PLAYER_SIZE = 50
OBSTACLE_SIZE = 50
SPEED = 5
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
RED = (255, 0, 0)

# Set up the display
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Avoid the Falling Blocks")

# Load player
player = pygame.Rect(WIDTH // 2, HEIGHT - PLAYER_SIZE - 10, PLAYER_SIZE, PLAYER_SIZE)

# Obstacles list
obstacles = []

# Game loop flag
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 movement
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and player.x > 0:
        player.x -= SPEED
    if keys[pygame.K_RIGHT] and player.x < WIDTH - PLAYER_SIZE:
        player.x += SPEED
    
    # Spawn obstacles
    if random.randint(1, 30) == 1:  # Randomly spawn
        obstacles.append(pygame.Rect(random.randint(0, WIDTH - OBSTACLE_SIZE), 0, OBSTACLE_SIZE, OBSTACLE_SIZE))
    
    # Move obstacles
    for obstacle in obstacles:
        obstacle.y += SPEED
        if obstacle.y > HEIGHT:
            obstacles.remove(obstacle)
        if player.colliderect(obstacle):  # Collision detection
            running = False
    
    # Draw player and obstacles
    pygame.draw.rect(screen, BLUE, player)
    for obstacle in obstacles:
        pygame.draw.rect(screen, RED, obstacle)

    pygame.display.update()
    clock.tick(30)  # Control FPS

pygame.quit()
Editor is loading...
Leave a Comment