Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.2 kB
1
Indexable
Never
import pygame
import random

# Initialize pygame
pygame.init()

# Set up game window
WIDTH, HEIGHT = 800, 600
window = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Avoid the Falling Blocks!")

# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)

# Player properties
player_size = 50
player_pos = [WIDTH // 2, HEIGHT - 2 * player_size]
player_speed = 10

# Enemy properties
enemy_size = 50
enemy_pos = [random.randint(0, WIDTH - enemy_size), 0]
enemy_speed = 10

# Game clock
clock = pygame.time.Clock()

# Game over flag
game_over = False

# Score tracker
score = 0
font = pygame.font.SysFont("monospace", 35)

def detect_collision(player_pos, enemy_pos):
    p_x, p_y = player_pos
    e_x, e_y = enemy_pos

    if (e_x >= p_x and e_x < (p_x + player_size)) or (p_x >= e_x and p_x < (e_x + enemy_size)):
        if (e_y >= p_y and e_y < (p_y + player_size)) or (p_y >= e_y and p_y < (e_y + enemy_size)):
            return True
    return False

# Game loop
while not game_over:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True

    # Get key presses
    keys = pygame.key.get_pressed()

    if keys[pygame.K_LEFT] and player_pos[0] > 0:
        player_pos[0] -= player_speed
    if keys[pygame.K_RIGHT] and player_pos[0] < WIDTH - player_size:
        player_pos[0] += player_speed

    # Move the enemy down
    enemy_pos[1] += enemy_speed

    # Respawn enemy if it goes off screen
    if enemy_pos[1] > HEIGHT:
        enemy_pos = [random.randint(0, WIDTH - enemy_size), 0]
        score += 1
        enemy_speed += 0.5  # Increase difficulty as score rises

    # Check for collisions
    if detect_collision(player_pos, enemy_pos):
        game_over = True

    # Draw the game
    window.fill(BLACK)
    pygame.draw.rect(window, RED, (enemy_pos[0], enemy_pos[1], enemy_size, enemy_size))
    pygame.draw.rect(window, WHITE, (player_pos[0], player_pos[1], player_size, player_size))

    # Display score
    score_text = font.render("Score: " + str(score), True, WHITE)
    window.blit(score_text, (10, 10))

    # Update the display
    pygame.display.update()

    # Set the frame rate
    clock.tick(30)

# Quit the game
pygame.quit()

Leave a Comment