Untitled

 avatar
unknown
plain_text
13 days ago
2.7 kB
3
Indexable
import pygame
import sys

# Initialize Pygame
pygame.init()

# Screen settings
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Circle vs Squares")

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

# Floor settings
FLOOR_HEIGHT = 50
FLOOR_Y = SCREEN_HEIGHT - FLOOR_HEIGHT

# Player settings
PLAYER_RADIUS = 20
player_x = 100
player_y = FLOOR_Y - PLAYER_RADIUS
player_speed = 7
jump_force = -15
gravity = 0.5
vel_y = 0
is_jumping = False

# Enemy settings
ENEMY_SIZE = 35
enemies = [
    {"x": 500, "y": FLOOR_Y - ENEMY_SIZE, "dir": 1, "speed": 4},
    {"x": 300, "y": FLOOR_Y - ENEMY_SIZE, "dir": -1, "speed": 3}
]

# Game loop
clock = pygame.time.Clock()
running = True

while running:
    # Event handling
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE and not is_jumping:
                vel_y = jump_force
                is_jumping = True

    # Continuous movement handling
    keys = pygame.key.get_pressed()
    if keys[pygame.K_q]:
        player_x -= player_speed
    if keys[pygame.K_d]:
        player_x += player_speed

    # Keep player in bounds
    player_x = max(PLAYER_RADIUS, min(player_x, SCREEN_WIDTH - PLAYER_RADIUS))

    # Jump physics
    if is_jumping:
        player_y += vel_y
        vel_y += gravity
        if player_y + PLAYER_RADIUS >= FLOOR_Y:
            player_y = FLOOR_Y - PLAYER_RADIUS
            is_jumping = False
            vel_y = 0

    # Enemy movement
    for enemy in enemies:
        enemy["x"] += enemy["dir"] * enemy["speed"]
        if enemy["x"] <= 0 or enemy["x"] >= SCREEN_WIDTH - ENEMY_SIZE:
            enemy["dir"] *= -1

    # Collision detection
    player_rect = pygame.Rect(
        player_x - PLAYER_RADIUS, player_y - PLAYER_RADIUS,
        2 * PLAYER_RADIUS, 2 * PLAYER_RADIUS
    )
    
    for enemy in enemies:
        enemy_rect = pygame.Rect(enemy["x"], enemy["y"], ENEMY_SIZE, ENEMY_SIZE)
        if player_rect.colliderect(enemy_rect):
            running = False

    # Drawing
    screen.fill(WHITE)
    # Draw floor
    pygame.draw.rect(screen, BLACK, (0, FLOOR_Y, SCREEN_WIDTH, FLOOR_HEIGHT))
    # Draw player
    pygame.draw.circle(screen, RED, (int(player_x), int(player_y)), PLAYER_RADIUS)
    # Draw enemies
    for enemy in enemies:
        pygame.draw.rect(screen, BLUE, (enemy["x"], enemy["y"], ENEMY_SIZE, ENEMY_SIZE))

    pygame.display.flip()
    clock.tick(60)

pygame.quit()
sys.exit()
Leave a Comment