# data[].attributes.body
파이게임 코드 제출

# data[].attributes.body
import pygame
import random
import sys

# 초기화
pygame.init()

# 화면 설정
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("새와 비행기 피하기")

# 색상
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)

# 이미지 불러오기
bird_img = pygame.image.load("bird.png")
plane_img = pygame.image.load("plane.png")
background_img = pygame.image.load("background.png")
life_item_img = pygame.image.load("life_item.png")
background_img = pygame.transform.scale(background_img, (WIDTH, HEIGHT))

# 이미지 크기
bird_width, bird_height = bird_img.get_size()
plane_width, plane_height = plane_img.get_size()
life_item_width, life_item_height = life_item_img.get_size()

# 게임 변수
bird_x = 100
bird_y = HEIGHT // 2
bird_speed = 8
bird_score = 0
bird_scale = 0.6
bird_lives = 5

plane_speed = 9
planes = []

# 보너스 아이템 변수
life_items = []
life_item_speed = 8
life_item_spawn_rate = 0.001  # ✅ 생성 확률 낮춤
life_item_scale = 0.5         # ✅ 아이템 크기 축소

# 폰트
font = pygame.font.SysFont("Arial", 30)
game_over_font = pygame.font.SysFont("Arial", 60)

# 새 그리기
def draw_bird():
    scaled_width = int(bird_width * bird_scale)
    scaled_height = int(bird_height * bird_scale)
    scaled_bird = pygame.transform.scale(bird_img, (scaled_width, scaled_height))
    screen.blit(scaled_bird, (bird_x, bird_y))

# 비행기 그리기
def draw_plane(x, y):
    screen.blit(plane_img, (x, y))

# 보너스 아이템 그리기 (크기 축소)
def draw_life_item(x, y):
    scaled_item = pygame.transform.scale(life_item_img, (int(life_item_width * life_item_scale), int(life_item_height * life_item_scale)))
    screen.blit(scaled_item, (x, y))

# 점수 표시
def draw_score():
    score_text = font.render(f"Score: {bird_score}", True, (0, 0, 0))
    screen.blit(score_text, (10, 10))

# 생명 표시
def draw_lives():
    lives_text = font.render(f"Lives: {bird_lives}", True, (0, 0, 0))
    screen.blit(lives_text, (WIDTH - 130, 10))

# 게임 오버 메시지
def draw_game_over():
    lose_text = game_over_font.render("Lose", True, RED)
    screen.blit(lose_text, (WIDTH // 2 - 80, HEIGHT // 2 - 30))
    reset_text = font.render("Game Over! Restarting in 30 seconds...", True, GREEN)
    screen.blit(reset_text, (WIDTH // 2 - 200, HEIGHT // 2 + 50))

# 게임 상태 초기화
def reset_game():
    global bird_x, bird_y, bird_score, bird_lives, planes, life_items, bird_speed, plane_speed
    bird_x = 100
    bird_y = HEIGHT // 2
    bird_score = 0
    bird_lives = 5
    planes.clear()
    life_items.clear()
    bird_speed = 6
    plane_speed = 4

# 게임 루프
def game_loop():
    global bird_x, bird_y, bird_score, bird_lives, bird_speed, plane_speed

    clock = pygame.time.Clock()
    running = True
    game_over = False

    collision_margin = 0.5
    reduced_width = int(bird_width * bird_scale * (1 - collision_margin))
    reduced_height = int(bird_height * bird_scale * (1 - collision_margin))

    plane_collision_margin = 0.5
    reduced_plane_width = int(plane_width * (1 - plane_collision_margin))
    reduced_plane_height = int(plane_height * (1 - plane_collision_margin))

    while running:
        screen.blit(background_img, (0, 0))

        if game_over:
            draw_game_over()
            pygame.display.update()
            pygame.time.delay(30000)
            reset_game()
            game_over = False

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        keys = pygame.key.get_pressed()
        if not game_over:
            if keys[pygame.K_UP] and bird_y > 0:
                bird_y -= bird_speed
            if keys[pygame.K_DOWN] and bird_y < HEIGHT - bird_height * bird_scale:
                bird_y += bird_speed

            if random.random() < 0.02:
                plane_x = WIDTH
                plane_y = random.randint(0, HEIGHT - plane_height)
                planes.append([plane_x, plane_y])

            if random.random() < life_item_spawn_rate:
                item_y = random.randint(0, HEIGHT - int(life_item_height * life_item_scale))
                life_items.append([WIDTH, item_y])

            for life_item in life_items[:]:
                life_item[0] -= life_item_speed

                bird_rect = pygame.Rect(
                    bird_x + (bird_width * bird_scale - reduced_width) // 2,
                    bird_y + (bird_height * bird_scale - reduced_height) // 2,
                    reduced_width,
                    reduced_height
                )
                item_rect = pygame.Rect(
                    life_item[0], life_item[1],
                    int(life_item_width * life_item_scale),
                    int(life_item_height * life_item_scale)
                )

                if bird_rect.colliderect(item_rect):
                    bird_lives += 1
                    life_items.remove(life_item)
                elif life_item[0] < 0:
                    life_items.remove(life_item)

            for plane in planes[:]:
                plane[0] -= plane_speed
                plane_rect = pygame.Rect(plane[0], plane[1], reduced_plane_width, reduced_plane_height)
                bird_rect = pygame.Rect(
                    bird_x + (bird_width * bird_scale - reduced_width) // 2,
                    bird_y + (bird_height * bird_scale - reduced_height) // 2,
                    reduced_width,
                    reduced_height
                )

                if bird_rect.colliderect(plane_rect):
                    bird_lives -= 1
                    planes.remove(plane)
                    if bird_lives <= 0:
                        game_over = True
                elif plane[0] + reduced_plane_width < bird_x:
                    bird_score += 1
                    planes.remove(plane)
            if bird_score >= 30:
                bird_speed = 10
                plane_speed = 17

            draw_bird()
            for plane in planes:
                draw_plane(plane[0], plane[1])
            for life_item in life_items:
                draw_life_item(life_item[0], life_item[1])
            draw_score()
            draw_lives()

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

# 게임 시작
game_loop()
pygame.quit()

# data[].attributes.body
import pygame
import random

# 초기화
pygame.init()

# 화면 설정
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("슈팅 게임")

# 색상
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)

# FPS
FPS = 60
clock = pygame.time.Clock()


# 플레이어
class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((50, 50))
        self.image.fill(RED)
        self.rect = self.image.get_rect()
        self.rect.center = (WIDTH // 2, HEIGHT - 50)
        self.speed = 5

    def update(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT] and self.rect.left > 0:
            self.rect.x -= self.speed
        if keys[pygame.K_RIGHT] and self.rect.right < WIDTH:
            self.rect.x += self.speed


# 플레이어 총알
class Bullet(pygame.sprite.Sprite):
    def __init__(self, x, y, speed, size):
        super().__init__()
        self.image = pygame.Surface((size, size * 2))
        self.image.fill(RED)
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.speed = speed

    def update(self):
        self.rect.y -= self.speed
        if self.rect.bottom < 0:
            self.kill()


# 적 총알
class EnemyBullet(pygame.sprite.Sprite):
    def __init__(self, x, y, speed=5):
        super().__init__()
        self.image = pygame.Surface((5, 10))
        self.image.fill(BLACK)
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.speed = speed

    def update(self):
        self.rect.y += self.speed
        if self.rect.top > HEIGHT:
            self.kill()


# 적
class Enemy(pygame.sprite.Sprite):
    def __init__(self, level):
        super().__init__()
        size = 50 + (level - 1) * 10
        self.image = pygame.Surface((size, size))
        self.image.fill(BLACK)
        self.rect = self.image.get_rect()
        self.rect.x = random.randint(0, WIDTH - size)
        self.rect.y = random.randint(-100, -40)
        self.speed = random.randint(1 + level, 2 + level)

    def update(self):
        self.rect.y += self.speed
        if self.rect.top > HEIGHT:
            self.kill()


# 게임 루프
def game_loop():
    # 초기 상태 변수
    bullet_level = 1
    enemy_level = 1
    enemy_upgrade_timer = 0
    game_time = 0
    game_over = False
    score = 0

    # 폰트
    font = pygame.font.SysFont("Arial", 30)
    over_font = pygame.font.SysFont("Arial", 50)

    # 그룹 초기화
    player = Player()
    bullets = pygame.sprite.Group()
    enemy_bullets = pygame.sprite.Group()
    enemies = pygame.sprite.Group()
    all_sprites = pygame.sprite.Group()
    all_sprites.add(player)

    for _ in range(5):
        enemy = Enemy(enemy_level)
        enemies.add(enemy)
        all_sprites.add(enemy)

    while True:
        dt = clock.tick(FPS)
        game_time += dt
        screen.fill(WHITE)

        if game_over:
            text = over_font.render("게임 오버!", True, RED)
            score_text = font.render(f"점수: {score}", True, BLACK)
            screen.blit(text, (WIDTH // 2 - 120, HEIGHT // 2 - 25))
            screen.blit(score_text, (WIDTH // 2 - 50, HEIGHT // 2 + 30))
            pygame.display.flip()
            pygame.time.wait(2000)
            return  # 루프 종료 → while True에서 재시작됨

        # 이벤트 처리
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()
            if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                if bullet_level == 1:
                    bullet = Bullet(player.rect.centerx, player.rect.top, 7, 5)
                    bullets.add(bullet)
                    all_sprites.add(bullet)
                elif bullet_level == 2:
                    for offset in (-10, 10):
                        bullet = Bullet(player.rect.centerx + offset, player.rect.top, 9, 7)
                        bullets.add(bullet)
                        all_sprites.add(bullet)
                elif bullet_level == 3:
                    for offset in (-10, 0, 10):
                        bullet = Bullet(player.rect.centerx + offset, player.rect.top, 11, 10)
                        bullets.add(bullet)
                        all_sprites.add(bullet)

        # 적 레벨 업
        if game_time - enemy_upgrade_timer > 10000:
            enemy_level += 1
            enemy_upgrade_timer = game_time

        # 업데이트
        all_sprites.update()

        # 적 총알 발사
        for enemy in enemies:
            if random.random() < 0.01:
                bullet = EnemyBullet(enemy.rect.centerx, enemy.rect.bottom)
                enemy_bullets.add(bullet)
                all_sprites.add(bullet)

        # 충돌 체크
        if pygame.sprite.spritecollide(player, enemy_bullets, True) or \
           pygame.sprite.spritecollide(player, enemies, False):
            game_over = True
            continue

        # 플레이어 총알이 적 명중
        for bullet in bullets:
            hits = pygame.sprite.spritecollide(bullet, enemies, True)
            for hit in hits:
                bullet.kill()
                score += 10
                bullet_level += 1
                if bullet_level > 3:
                    bullet_level = 3
                new_enemy = Enemy(enemy_level)
                enemies.add(new_enemy)
                all_sprites.add(new_enemy)

        # 적 수 보충
        while len(enemies) < 5:
            enemy = Enemy(enemy_level)
            enemies.add(enemy)
            all_sprites.add(enemy)

        # 점수 표시
        score_display = font.render(f"점수: {score}", True, BLACK)
        screen.blit(score_display, (10, 10))

        # 그리기
        all_sprites.draw(screen)
        pygame.display.flip()


# 메인 루프: 게임 오버 시 자동 재시작
while True:
    game_loop()

# data[].attributes.body
import pygame
import random

# 초기화
pygame.init()
WIDTH, HEIGHT = 600, 800
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Galaga Style - Image Edition")
clock = pygame.time.Clock()

# 이미지 로딩
player_img = pygame.transform.scale(pygame.image.load("spaceship.png").convert_alpha(), (50, 40))
enemy_img = pygame.transform.scale(pygame.image.load("spaceship2.png").convert_alpha(), (40, 30))
boss_img = pygame.transform.scale(pygame.image.load("boss.png").convert_alpha(), (200, 60))
bullet_img = pygame.transform.scale(pygame.image.load("bullet.png").convert_alpha(), (40, 15))
try:
    star_img = pygame.transform.scale(pygame.image.load("star.png").convert_alpha(), (2, 2))
except:
    star_img = None

# 색상
WHITE = (255, 255, 255)
RED = (255, 80, 80)
GREEN = (80, 255, 80)
YELLOW = (255, 255, 100)
BLACK = (0, 0, 0)

# Bullet 클래스
class Bullet:
    def __init__(self, x, y, size, damage):
        self.rect = pygame.Rect(x, y, *size)
        self.damage = damage

    def move(self):
        self.rect.y -= 10

    def draw(self):
        screen.blit(pygame.transform.scale(bullet_img, (self.rect.width, self.rect.height)), self.rect)

# Player 클래스
class Player:
    def __init__(self):
        self.rect = pygame.Rect(WIDTH//2 - 25, HEIGHT - 60, 50, 40)
        self.speed = 7
        self.bullets = []
        self.special_used = False
        self.bullet_size = (15, 15)
        self.bullet_damage = 1
        self.special_active = False
        self.special_timer = 0

    def move(self, direction):
        if direction == "left" and self.rect.left > 0:
            self.rect.x -= self.speed
        elif direction == "right" and self.rect.right < WIDTH:
            self.rect.x += self.speed

    def shoot(self):
        w, h = self.bullet_size
        bullet = Bullet(self.rect.centerx - w//2, self.rect.top - 40, (w, h), self.bullet_damage)
        self.bullets.append(bullet)

    def special_attack(self):
        if not self.special_used:
            self.special_used = True
            self.special_active = True
            self.special_timer = pygame.time.get_ticks()
            self.bullet_size = (75, 75)
            self.bullet_damage = 4
            return True
        return False

    def update_special(self):
        if self.special_active and pygame.time.get_ticks() - self.special_timer > 3000:
            self.bullet_size = (15, 15)
            self.bullet_damage = 1
            self.special_active = False

    def draw(self):
        screen.blit(player_img, self.rect)
        for bullet in self.bullets:
            bullet.draw()

# 적 클래스
class Enemy:
    def __init__(self):
        self.rect = pygame.Rect(random.randint(0, WIDTH - 40), -40, 40, 30)
        self.speed = random.randint(2, 4)

    def move(self):
        self.rect.y += self.speed

    def draw(self):
        screen.blit(enemy_img, self.rect)

# 보스 클래스
class Boss:
    def __init__(self, wave):
        self.rect = pygame.Rect(WIDTH//2 - 100, 60, 200, 60)
        self.max_health = 30 + wave * 10
        self.health = self.max_health
        self.speed = 2 + wave * 0.5
        self.direction = 1
        self.bullets = []
        self.cooldown = 0

    def move(self):
        self.rect.x += self.speed * self.direction
        if self.rect.left <= 0 or self.rect.right >= WIDTH:
            self.direction *= -1
            # 보스가 경계를 넘지 않도록 보정
            self.rect.x = max(0, min(self.rect.x, WIDTH - self.rect.width))

        self.cooldown += 1
        if self.cooldown > 60:
            self.shoot()
            self.cooldown = 0

        for bullet in self.bullets[:]:
            bullet.y += 6
            if bullet.top > HEIGHT:
                self.bullets.remove(bullet)

    def shoot(self):
        bullet = pygame.Rect(self.rect.centerx - 50, self.rect.bottom, 100, 15)
        self.bullets.append(bullet)

    def draw(self):
        screen.blit(boss_img, self.rect)
        pygame.draw.rect(screen, RED, (self.rect.x, self.rect.y - 10, self.rect.width, 8))
        pygame.draw.rect(screen, GREEN, (self.rect.x, self.rect.y - 10, self.rect.width * (self.health / self.max_health), 8))
        for bullet in self.bullets:
            pygame.draw.rect(screen, YELLOW, bullet)

# 별 배경
class Star:
    def __init__(self):
        self.x = random.randint(0, WIDTH)
        self.y = random.randint(0, HEIGHT)
        self.speed = random.uniform(0.5, 1.5)

    def move(self):
        self.y += self.speed
        if self.y > HEIGHT:
            self.y = 0
            self.x = random.randint(0, WIDTH)

    def draw(self):
        if star_img:
            screen.blit(star_img, (int(self.x), int(self.y)))
        else:
            pygame.draw.circle(screen, WHITE, (int(self.x), int(self.y)), 1)

# 게임 초기화
def reset_game():
    global player, enemies, stars, enemy_spawn_timer, score, wave, boss, game_over
    player = Player()
    enemies = []
    stars = [Star() for _ in range(100)]
    enemy_spawn_timer = 0
    score = 0
    wave = 1
    boss = None
    game_over = False

# 게임 변수 초기화
reset_game()
font = pygame.font.SysFont("arial", 24)

# 게임 루프
running = True
while running:
    clock.tick(60)
    screen.fill(BLACK)

    # 별 배경
    for star in stars:
        star.move()
        star.draw()

    # 이벤트 처리
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1 and not game_over:
                if len(player.bullets) < 5:
                    player.shoot()
            elif event.button == 3 and not game_over:
                player.special_attack()
        elif event.type == pygame.KEYDOWN and game_over:
            if event.key == pygame.K_SPACE:
                reset_game()

    # 키 입력
    keys = pygame.key.get_pressed()
    if keys[pygame.K_a]:
        player.move("left")
    if keys[pygame.K_d]:
        player.move("right")

    player.update_special()

    # 총알 이동
    for bullet in player.bullets[:]:
        bullet.move()
        if bullet.rect.bottom < 0:
            player.bullets.remove(bullet)

    # 적 생성
    if not boss:
        enemy_spawn_timer += 1
        if enemy_spawn_timer > max(10, 40 - wave * 2):
            enemies.append(Enemy())
            enemy_spawn_timer = 0

    # 적 이동 및 충돌
    for enemy in enemies[:]:
        enemy.move()
        if enemy.rect.top > HEIGHT:
            enemies.remove(enemy)
        for bullet in player.bullets[:]:
            if enemy.rect.colliderect(bullet.rect):
                enemies.remove(enemy)
                player.bullets.remove(bullet)
                score += 1
                break

    # 보스 등장
    if score >= wave * 15 and boss is None:
        boss = Boss(wave)

    # 보스 처리
    if boss:
        boss.move()
        for bullet in player.bullets[:]:
            if boss.rect.colliderect(bullet.rect):
                boss.health -= bullet.damage
                player.bullets.remove(bullet)
                if boss.health <= 0:
                    boss = None
                    wave += 1
                    player.special_used = False
                    break

    # 충돌 검사
    for enemy in enemies:
        if enemy.rect.colliderect(player.rect):
            game_over = True
    if boss:
        if boss.rect.colliderect(player.rect):
            game_over = True
        for bullet in boss.bullets:
            if bullet.colliderect(player.rect):
                game_over = True

    # 그리기
    if not game_over:
        player.draw()
        for enemy in enemies:
            enemy.draw()
        if boss:
            boss.draw()
    else:
        screen.blit(font.render("GAME OVER - SPACE TO RESTART", True, RED), (WIDTH // 2 - 150, HEIGHT // 2 - 30))

    screen.blit(font.render(f"Score: {score}", True, WHITE), (10, 10))
    screen.blit(font.render(f"Wave: {wave}", True, WHITE), (10, 40))
    if not player.special_used and not game_over:
        screen.blit(font.render("RIGHT CLICK: SPECIAL ATTACK (BIG BULLET x2 DMG)", True, YELLOW), (WIDTH - 360, 10))

    pygame.display.flip()

pygame.quit()

# data[].attributes.body
import pygame
import sys
import random
import time
import math

# 초기 설정
pygame.init()
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("바운스볼 - 자동조준 총")
clock = pygame.time.Clock()

# 색상
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BALL_COLOR = (255, 100, 100)
PLATFORM_COLOR = (100, 200, 255)
BULLET_COLOR = (0, 0, 0)

# 공 클래스
class Ball:
    def __init__(self):
        self.x = WIDTH // 4
        self.y = HEIGHT // 2
        self.radius = 20
        self.dy = 0
        self.gravity = 0.5
        self.jump_force = -10
        self.alive = True

    def update(self, platforms):
        self.dy += self.gravity
        self.y += self.dy

        for p in platforms:
            if (p.x - self.radius < self.x < p.x + p.width + self.radius and
                p.y - self.radius < self.y < p.y + p.height + self.radius and self.dy > 0):
                self.dy = self.jump_force

        if self.y - self.radius > HEIGHT:
            self.alive = False

    def draw(self, surface):
        color = BALL_COLOR if self.alive else RED
        pygame.draw.circle(surface, color, (int(self.x), int(self.y)), self.radius)

# 바닥 클래스
class Platform:
    def __init__(self, x):
        self.x = x
        self.y = random.randint(300, 550)
        self.width = 100
        self.height = 10

    def draw(self, surface):
        pygame.draw.rect(surface, PLATFORM_COLOR, (self.x, self.y, self.width, self.height))

    def is_offscreen(self):
        return self.x + self.width < -200 or self.x > WIDTH + 200

# 총알 클래스
class Bullet:
    def __init__(self, x, y, target_x, target_y):
        self.x = x
        self.y = y
        self.radius = 5
        speed = 6

        dx = target_x - x
        dy = target_y - y
        dist = math.hypot(dx, dy)
        if dist == 0:
            dist = 1
        self.vx = speed * dx / dist
        self.vy = speed * dy / dist

    def update(self):
        self.x += self.vx
        self.y += self.vy

    def draw(self, surface):
        pygame.draw.circle(surface, BULLET_COLOR, (int(self.x), int(self.y)), self.radius)

    def is_offscreen(self):
        return self.x < -10 or self.x > WIDTH + 10 or self.y > HEIGHT + 10

# 총 클래스
class Gun:
    def __init__(self, offset):
        self.screen_x = WIDTH // 2 + offset
        self.screen_y = 50
        self.cooldown = 1.0
        self.last_shot = 0

    def auto_shoot(self, bullets, target_x, target_y, current_time):
        if current_time - self.last_shot >= self.cooldown:
            bullets.append(Bullet(self.screen_x, self.screen_y, target_x, target_y))
            self.last_shot = current_time

    def draw(self, surface):
        pygame.draw.rect(surface, (0, 0, 0), (self.screen_x - 10, self.screen_y - 10, 20, 20))

# 게임 초기화
ball = Ball()
platforms = [Platform(i * 120) for i in range(10)]
bullets = []
guns = [Gun(0)]
max_platforms = 30
scroll_speed = 5
camera_offset_x = 0
font = pygame.font.SysFont(None, 48)
start_time = time.time()
final_score = 0
score_frozen = False

# 게임 루프
running = True
while running:
    screen.fill(WHITE)
    current_time = time.time()
    if not score_frozen:
        elapsed_time = int(current_time - start_time)

        # 총 개수 조절
        required_guns = elapsed_time // 30 + 1
        if len(guns) < required_guns:
            spacing = 80  # 더 넓은 간격
            offset = (len(guns) - (required_guns - 1) / 2) * spacing
            guns.append(Gun(offset))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        camera_offset_x += scroll_speed
        for p in platforms:
            p.x += scroll_speed
        for b in bullets:
            b.x += scroll_speed
    elif keys[pygame.K_RIGHT]:
        camera_offset_x -= scroll_speed
        for p in platforms:
            p.x -= scroll_speed
        for b in bullets:
            b.x -= scroll_speed

    if ball.alive:
        ball.update(platforms)
    ball.draw(screen)

    platforms = [p for p in platforms if not p.is_offscreen()]
    rightmost_x = max(p.x for p in platforms) if platforms else WIDTH
    leftmost_x = min(p.x for p in platforms) if platforms else 0

    if len(platforms) < max_platforms:
        if rightmost_x < WIDTH:
            platforms.append(Platform(rightmost_x + 120))
        if leftmost_x > -100:
            platforms.append(Platform(leftmost_x - 120))

    for p in platforms:
        p.draw(screen)

    for gun in guns:
        gun.auto_shoot(bullets, ball.x, ball.y, current_time)
        gun.draw(screen)

    for bullet in bullets:
        bullet.update()
        bullet.draw(screen)

        dx = bullet.x - ball.x
        dy = bullet.y - ball.y
        distance = math.hypot(dx, dy)
        if distance < bullet.radius + ball.radius:
            ball.alive = False

    bullets = [b for b in bullets if not b.is_offscreen()]

    if ball.alive:
        score_text = font.render(f"Score: {elapsed_time}", True, (0, 0, 0))
        screen.blit(score_text, (10, 10))
    else:
        if not score_frozen:
            final_score = elapsed_time
            score_frozen = True
        msg = font.render("Game Over", True, RED)
        score_text = font.render(f"Final Score: {final_score}", True, (0, 0, 0))
        screen.blit(msg, (WIDTH // 2 - msg.get_width() // 2, HEIGHT // 2 - 30))
        screen.blit(score_text, (WIDTH // 2 - score_text.get_width() // 2, HEIGHT // 2 + 10))

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

pygame.quit()
sys.exit()

# data[].attributes.body
import pygame
import random
import sys

# 초기 설정
pygame.init()
WIDTH, HEIGHT = 800, 600
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("우주 쓰레기 슈팅 게임")
CLOCK = pygame.time.Clock()

# 색상
WHITE = (255, 255, 255)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
BLACK = (0, 0, 0)
GRAY = (200, 200, 200)

# 플레이어
player = pygame.Rect(WIDTH//2 - 25, HEIGHT - 60, 50, 30)
bullets = []
trash_list = []

score = 0
game_over = False
trash_speed = 2
trash_hit_count = 0

font = pygame.font.SysFont("Arial", 24)
big_font = pygame.font.SysFont("Arial", 36)

def draw_text(text, size, color, x, y):
    font = pygame.font.SysFont("Arial", size)
    surface = font.render(text, True, color)
    SCREEN.blit(surface, (x, y))

def draw_restart_button():
    button_rect = pygame.Rect(WIDTH//2 - 100, HEIGHT//2 + 40, 200, 50)
    pygame.draw.rect(SCREEN, GRAY, button_rect)
    pygame.draw.rect(SCREEN, WHITE, button_rect, 2)
    text = big_font.render("다시 시작", True, BLACK)
    SCREEN.blit(text, (button_rect.x + 25, button_rect.y + 5))
    return button_rect

def reset_game():
    global bullets, trash_list, score, game_over, player, trash_speed, trash_hit_count
    bullets = []
    trash_list = []
    score = 0
    game_over = False
    trash_speed = 2
    trash_hit_count = 0
    player.x = WIDTH // 2 - 25

def game_loop():
    global score, game_over, trash_speed, trash_hit_count

    restart_button = None

    while True:
        CLOCK.tick(60)
        SCREEN.fill(BLACK)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit(); sys.exit()
            if game_over and event.type == pygame.MOUSEBUTTONDOWN:
                if restart_button and restart_button.collidepoint(event.pos):
                    reset_game()

        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT] and player.x > 0:
            player.x -= 5
        if keys[pygame.K_RIGHT] and player.x < WIDTH - player.width:
            player.x += 5
        if keys[pygame.K_SPACE] and not game_over:
            if len(bullets) < 5:
                bullets.append(pygame.Rect(player.centerx - 2, player.y, 4, 10))

        if not game_over:
            if random.randint(1, 30) == 1:
                x = random.randint(0, WIDTH - 20)
                trash = pygame.Rect(x, 0, 20, 20)
                trash_list.append(trash)

            for bullet in bullets[:]:
                bullet.y -= 10
                if bullet.y < 0:
                    bullets.remove(bullet)

            for trash in trash_list[:]:
                trash.y += trash_speed

                # 플레이어에 부딪히면 게임 오버
                if trash.colliderect(player):
                    game_over = True

                # 총알에 맞으면 점수 +3
                for bullet in bullets[:]:
                    if trash.colliderect(bullet):
                        bullets.remove(bullet)
                        trash_list.remove(trash)
                        score += 3
                        trash_hit_count += 1
                        if trash_hit_count % 15 == 0:
                            trash_speed = min(trash_speed + 1, 10)
                        break

                # 화면 아래에 닿으면 감점
                if trash.y > HEIGHT:
                    if trash in trash_list:
                        trash_list.remove(trash)
                        score -= 1

        # 그리기
        pygame.draw.rect(SCREEN, WHITE, player)
        for bullet in bullets:
            pygame.draw.rect(SCREEN, YELLOW, bullet)
        for trash in trash_list:
            pygame.draw.rect(SCREEN, RED, trash)

        draw_text(f"점수: {score}", 24, WHITE, 10, 10)

        if game_over:
            draw_text("게임 오버!", 36, RED, WIDTH // 2 - 100, HEIGHT // 2 - 60)
            restart_button = draw_restart_button()

        pygame.display.flip()

if __name__ == "__main__":
    game_loop()

# data[].attributes.body
import pygame
import random
import os

pygame.init()
pygame.font.init()

# 화면 설정
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("벽돌 깨기 게임")
clock = pygame.time.Clock()

# 색상
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
PINK = (255, 105, 180)

# 패들
PADDLE_WIDTH, PADDLE_HEIGHT = 100, 20
paddle = pygame.Rect(WIDTH // 2 - PADDLE_WIDTH // 2, HEIGHT - 40, PADDLE_WIDTH, PADDLE_HEIGHT)
paddle_color = (0, 200, 255)

# 공
BALL_SIZE = 20
ball = pygame.Rect(WIDTH // 2, HEIGHT // 2, BALL_SIZE, BALL_SIZE)
ball_speed = [6.0, -6.0]

# 벽돌
brick_rows = 5
brick_cols = 10
brick_width = WIDTH // brick_cols
brick_height = 30
bricks = []

# 점수
font = pygame.font.SysFont(None, 36)
score = 0
high_score = 0
game_over = False
win = False
frame_counter = 0
SCORE_FILE = "highscore.txt"

# 아이템
power_ups = []  # 여러 개의 아이템을 리스트로 관리
power_up_active = False

# 함수 정의
def random_color():
    return (random.randint(50, 255), random.randint(50, 255), random.randint(50, 255))

def create_bricks(rows=5):
    for row in range(rows):
        for col in range(brick_cols):
            brick_rect = pygame.Rect(col * brick_width + 2, row * brick_height + 2, brick_width - 4, brick_height - 4)
            bricks.append((brick_rect, random_color()))

def add_brick_row():
    for i in range(len(bricks)):
        bricks[i] = (bricks[i][0].move(0, brick_height), bricks[i][1])
    for col in range(brick_cols):
        new_brick = pygame.Rect(col * brick_width + 2, 2, brick_width - 4, brick_height - 4)
        bricks.append((new_brick, random_color()))

def get_high_score():
    if os.path.exists(SCORE_FILE):
        with open(SCORE_FILE, 'r') as f:
            return int(f.read())
    return 0

def save_high_score(score):
    with open(SCORE_FILE, 'w') as f:
        f.write(str(score))

def spawn_power_up(brick_rect):
    global power_up_active
    power_up_type = random.choice(["paddle", "speed"])
    power_up = {
        "rect": pygame.Rect(brick_rect.centerx - 15, brick_rect.centery, 30, 30),
        "type": power_up_type
    }
    power_ups.append(power_up)

def activate_power_up(power_up):
    global paddle, ball_speed
    if power_up["type"] == "paddle":
        paddle.width += 30
    elif power_up["type"] == "speed":
        ball_speed = [s * 1.1 for s in ball_speed]
    power_ups.remove(power_up)  # 아이템 사용 후 제거

# 초기 벽돌 생성 및 최고 점수 불러오기
create_bricks()
high_score = get_high_score()

# 게임 루프
running = True
while running:
    clock.tick(60)
    screen.fill(BLACK)
    frame_counter += 1

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    if not game_over:
        if frame_counter >= 500:
            add_brick_row()
            frame_counter = 0

        mouse_x = pygame.mouse.get_pos()[0]
        paddle.x = mouse_x - paddle.width // 2
        paddle.clamp_ip(screen.get_rect())

        ball.x += ball_speed[0]
        ball.y += ball_speed[1]

        if ball.left <= 0 or ball.right >= WIDTH:
            ball_speed[0] *= -1
        if ball.top <= 0:
            ball_speed[1] *= -1
        if ball.bottom >= HEIGHT:
            game_over = True

        if ball.colliderect(paddle) and ball_speed[1] > 0:
            ball.bottom = paddle.top
            ball_speed[1] *= -1
            ball_speed = [s * 1.02 for s in ball_speed]  # 패들에 닿을 때만 속도 증가

        hit_index = -1
        for i, (brick, _) in enumerate(bricks):
            if ball.colliderect(brick):
                hit_index = i
                break

        if hit_index != -1:
            brick_rect, _ = bricks.pop(hit_index)
            ball_speed[1] *= -1
            score += 10
            if random.random() < 0.25:
                spawn_power_up(brick_rect)

        if power_ups:
            for power_up in power_ups:
                power_up["rect"].y += 5
                if paddle.colliderect(power_up["rect"]):
                    activate_power_up(power_up)
                elif power_up["rect"].top > HEIGHT:
                    power_ups.remove(power_up)

        # 그리기
        pygame.draw.ellipse(screen, (255, 0, 0), ball)
        pygame.draw.rect(screen, paddle_color, paddle)
        for brick, color in bricks:
            pygame.draw.rect(screen, color, brick)

        if power_ups:
            for power_up in power_ups:
                if power_up["type"] == "paddle":
                    pygame.draw.polygon(screen, PINK, [
                        (power_up["rect"].centerx, power_up["rect"].top),
                        (power_up["rect"].right, power_up["rect"].centery),
                        (power_up["rect"].centerx, power_up["rect"].bottom),
                        (power_up["rect"].left, power_up["rect"].centery)
                    ])
                elif power_up["type"] == "speed":
                    pygame.draw.circle(screen, GREEN, power_up["rect"].center, 15)

        screen.blit(font.render(f"Score: {score}", True, WHITE), (10, 10))
        screen.blit(font.render(f"High Score: {high_score}", True, WHITE), (WIDTH - 220, 10))

        if not bricks:
            game_over = True
            win = True

    else:
        if score > high_score:
            high_score = score
            save_high_score(score)

        msg = "You Win!" if win else "Game Over!"
        screen.blit(font.render(msg + " Press R to Restart", True, WHITE), (WIDTH // 2 - 180, HEIGHT // 2))

        keys = pygame.key.get_pressed()
        if keys[pygame.K_r]:
            # 재시작
            paddle = pygame.Rect(WIDTH // 2 - PADDLE_WIDTH // 2, HEIGHT - 40, PADDLE_WIDTH, PADDLE_HEIGHT)
            ball = pygame.Rect(WIDTH // 2, HEIGHT // 2, BALL_SIZE, BALL_SIZE)
            ball_speed = [6.0, -6.0]
            bricks.clear()
            create_bricks()
            score = 0
            frame_counter = 0
            power_ups.clear()
            power_up_active = False
            game_over = False
            win = False

    pygame.display.flip()

pygame.quit()

# data[].attributes.body
import pygame
import sys
import random

pygame.init()
WIDTH, HEIGHT = 800, 600
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("🎾 멀티볼 2인용 벽돌 테니스")

RED = (255, 255, 255)
BLACK = (0, 0, 0)
RED   = (255, 60, 60)
BLUE  = (60, 60, 255)
GREEN = (0, 200, 0)

font = pygame.font.SysFont("malgungothic", 24)

# 공 정보
BALL_SIZE = 20
NUM_BALLS = 2
balls = []

def create_ball():
    rect = pygame.Rect(WIDTH//2, HEIGHT//2, BALL_SIZE, BALL_SIZE)
    dx = 4 * random.choice([-1, 1])
    dy = 4 * random.choice([-1, 1])
    return {"rect": rect, "dx": dx, "dy": dy}

for _ in range(NUM_BALLS):
    balls.append(create_ball())

# 패들
PADDLE_WIDTH, PADDLE_HEIGHT = 80, 15
paddle1 = pygame.Rect(WIDTH//2 - 50, HEIGHT - 30, PADDLE_WIDTH, PADDLE_HEIGHT)
paddle2 = pygame.Rect(WIDTH//2 - 50, 15, PADDLE_WIDTH, PADDLE_HEIGHT)

# 벽돌
brick_rows = 5
brick_cols = 10
brick_width = WIDTH // brick_cols
brick_height = 25
bricks_top = []
bricks_bottom = []

for row in range(brick_rows):
    for col in range(brick_cols):
        top = pygame.Rect(col * brick_width + 2, row * brick_height + 50, brick_width - 4, brick_height - 4)
        bottom = pygame.Rect(col * brick_width + 2, HEIGHT - 50 - (row + 1) * brick_height, brick_width - 4, brick_height - 4)
        bricks_top.append(top)
        bricks_bottom.append(bottom)

# 점수
score1 = 0
score2 = 0

def draw():
    win.fill(BLACK)
    pygame.draw.rect(win, RED, paddle1)
    pygame.draw.rect(win, BLUE, paddle2)

    for ball in balls:
        pygame.draw.ellipse(win, RED, ball["rect"])

    for brick in bricks_top:
        pygame.draw.rect(win, GREEN, brick)
    for brick in bricks_bottom:
        pygame.draw.rect(win, GREEN, brick)

    s1 = font.render(f"Player 1 (RED): {score1}", True, RED)
    s2 = font.render(f"Player 2 (BLUE): {score2}", True, BLUE)
    win.blit(s1, (10, HEIGHT - 30))
    win.blit(s2, (10, 10))
    pygame.display.update()

def reset_ball(ball):
    ball["rect"].center = (WIDTH//2, HEIGHT//2)
    ball["dx"] = 4 * random.choice([-1, 1])
    ball["dy"] = 4 * random.choice([-1, 1])
    pygame.time.wait(500)

def game_loop():
    global score1, score2

    clock = pygame.time.Clock()
    running = True

    while running:
        clock.tick(60)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        # 패들 조작
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT] and paddle1.left > 0:
            paddle1.x -= 7
        if keys[pygame.K_RIGHT] and paddle1.right < WIDTH:
            paddle1.x += 7
        if keys[pygame.K_a] and paddle2.left > 0:
            paddle2.x -= 7
        if keys[pygame.K_d] and paddle2.right < WIDTH:
            paddle2.x += 7

        # 각 공 처리
        for ball in balls:
            rect = ball["rect"]
            rect.x += ball["dx"]
            rect.y += ball["dy"]

            # 벽 충돌
            if rect.left <= 0 or rect.right >= WIDTH:
                ball["dx"] *= -1

            # 상하 충돌 = 실점
            if rect.top <= 0:
                score1 += 1
                reset_ball(ball)
                continue
            elif rect.bottom >= HEIGHT:
                score2 += 1
                reset_ball(ball)
                continue

            # 패들 충돌
            if rect.colliderect(paddle1) and ball["dy"] > 0:
                ball["dy"] *= -1
            if rect.colliderect(paddle2) and ball["dy"] < 0:
                ball["dy"] *= -1

            # 벽돌 충돌
            for i, brick in enumerate(bricks_top):
                if rect.colliderect(brick):
                    del bricks_top[i]
                    ball["dy"] *= -1
                    ball["dx"] += random.choice([-1, 1])
                    score2 += 5
                    break
            for i, brick in enumerate(bricks_bottom):
                if rect.colliderect(brick):
                    del bricks_bottom[i]
                    ball["dy"] *= -1
                    ball["dx"] += random.choice([-1, 1])
                    score1 += 5
                    break

            # 속도 제한
            ball["dx"] = max(-10, min(10, ball["dx"]))
            ball["dy"] = max(-10, min(10, ball["dy"]))

        draw()

# 실행
game_loop()

# data[].attributes.body
설명: 테트리스

a,d로 움직이기

w로 회전

s로 빠르게 내려가기

한줄이 완성되면 없어지고 너무 높이 올라가면 게임오버

스코어는 블럭 설치는 1p, 한줄 완성은 2p

import pygame
import random
import time

# 초기 설정
pygame.init()
SCREEN_WIDTH, SCREEN_HEIGHT = 420, 720
BLOCK_SIZE = 30
COLUMNS = 10
ROWS = SCREEN_HEIGHT // BLOCK_SIZE
FPS = 60

# 색상 정의
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
COLORS = {
    "I": (173, 216, 230),
    "J": (0, 0, 255),
    "L": (255, 165, 0),
    "O": (255, 255, 0),
    "S": (0, 255, 0),
    "T": (128, 0, 128),
    "Z": (255, 0, 0)
}

# 블록 모양
SHAPES = {
    "I": [(0, 0), (0, 1), (0, 2), (0, 3)],
    "J": [(0, 0), (1, 0), (1, 1), (1, 2)],
    "L": [(0, 2), (0, 1), (0, 0), (1, 0)],
    "O": [(0, 0), (0, 1), (1, 1), (1, 0)],
    "S": [(0, 0), (1, 0), (1, 1), (2, 1)],
    "T": [(0, 1), (1, 1), (1, 0), (2, 1)],
    "Z": [(0, 1), (1, 1), (1, 0), (2, 0)]
}

# 화면 설정
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Tetris')

clock = pygame.time.Clock()
font = pygame.font.Font(None, 36)
game_over_font = pygame.font.Font(None, 72)

# 테트리스 블록 클래스
class Tetromino:
    def __init__(self, x, y, shape_type):
        self.x = x
        self.y = y
        self.shape = SHAPES[shape_type]
        self.color = COLORS[shape_type]

    def draw(self):
        for coord in self.shape:
            block_x = self.x + coord[0] * BLOCK_SIZE
            block_y = self.y + coord[1] * BLOCK_SIZE
            pygame.draw.rect(screen, self.color, (block_x, block_y, BLOCK_SIZE, BLOCK_SIZE))
            pygame.draw.rect(screen, WHITE, (block_x, block_y, BLOCK_SIZE, BLOCK_SIZE), 1)

    def move(self, dx, dy, fixed_blocks):
        new_x = self.x + dx * BLOCK_SIZE
        new_y = self.y + dy * BLOCK_SIZE

        for coord in self.shape:
            block_x = new_x + coord[0] * BLOCK_SIZE
            block_y = new_y + coord[1] * BLOCK_SIZE
            if block_x < 0 or block_x >= COLUMNS * BLOCK_SIZE:
                return False
            if block_y >= SCREEN_HEIGHT or (block_x, block_y) in fixed_blocks:
                return False

        self.x = new_x
        self.y = new_y
        return True

    def rotate(self, fixed_blocks):
        new_shape = [(-y, x) for x, y in self.shape]
        for coord in new_shape:
            block_x = self.x + coord[0] * BLOCK_SIZE
            block_y = self.y + coord[1] * BLOCK_SIZE
            if block_x < 0 or block_x >= COLUMNS * BLOCK_SIZE or block_y >= SCREEN_HEIGHT or (block_x, block_y) in fixed_blocks:
                return
        self.shape = new_shape

def clear_lines(fixed_blocks):
    block_positions = list(fixed_blocks.keys())
    rows = [y for _, y in block_positions]
    cleared_rows = []

    for y in range(0, SCREEN_HEIGHT, BLOCK_SIZE):
        if rows.count(y) == COLUMNS:
            cleared_rows.append(y)

    # 깜빡이는 줄 처리
    for _ in range(3):
        for row in cleared_rows:
            for x in range(0, COLUMNS * BLOCK_SIZE, BLOCK_SIZE):
                pygame.draw.rect(screen, WHITE, (x, row, BLOCK_SIZE, BLOCK_SIZE))
        pygame.display.flip()
        time.sleep(0.1)

    # 줄 제거
    for row in cleared_rows:
        for (x, y) in list(fixed_blocks.keys()):
            if y == row:
                del fixed_blocks[(x, y)]

    # 위에 있는 블록들을 한 칸 아래로 이동
    cleared_rows.sort()
    for row in cleared_rows:
        for (x, y) in list(fixed_blocks.keys()):
            if y < row:
                fixed_blocks[(x, y + BLOCK_SIZE)] = fixed_blocks.pop((x, y))

    return len(cleared_rows)

def main():
    running = True
    active_tetromino = None
    fixed_blocks = {}
    frame_count = 0
    score = 0
    fast_drop = False

    while running:
        screen.fill(BLACK)
        pygame.draw.line(screen, WHITE, (COLUMNS * BLOCK_SIZE, 0), (COLUMNS * BLOCK_SIZE, SCREEN_HEIGHT), 2)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                if active_tetromino:
                    if event.key == pygame.K_a:
                        active_tetromino.move(-1, 0, fixed_blocks)
                    if event.key == pygame.K_d:
                        active_tetromino.move(1, 0, fixed_blocks)
                    if event.key == pygame.K_w:
                        active_tetromino.rotate(fixed_blocks)
                    if event.key == pygame.K_s:
                        fast_drop = True
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_s:
                    fast_drop = False

        if active_tetromino is None:
            shape_type = random.choice(list(SHAPES.keys()))
            active_tetromino = Tetromino(COLUMNS // 2 * BLOCK_SIZE, 0, shape_type)

        frame_count += 1
        drop_speed = 3 if fast_drop else 10
        if frame_count % drop_speed == 0:
            if not active_tetromino.move(0, 1, fixed_blocks):
                for coord in active_tetromino.shape:
                    block_x = active_tetromino.x + coord[0] * BLOCK_SIZE
                    block_y = active_tetromino.y + coord[1] * BLOCK_SIZE
                    fixed_blocks[(block_x, block_y)] = active_tetromino.color
                active_tetromino = None
                score += 1  # 블록 고정 시 점수 증가
                score += clear_lines(fixed_blocks) * 2  # 한 줄 제거 시 점수 추가
                if any(y < 3 * BLOCK_SIZE for _, y in fixed_blocks.keys()):
                    screen.fill(BLACK)
                    game_over_text = game_over_font.render("GAME OVER!", True, WHITE)
                    score_text = font.render(f"Final Score: {score}", True, WHITE)
                    screen.blit(game_over_text, (SCREEN_WIDTH // 4, SCREEN_HEIGHT // 2 - 50))
                    screen.blit(score_text, (SCREEN_WIDTH // 4, SCREEN_HEIGHT // 2 + 20))
                    pygame.display.flip()
                    while True:
                        for event in pygame.event.get():
                            if event.type == pygame.QUIT:
                                pygame.quit()
                                return

        for (block_x, block_y), block_color in fixed_blocks.items():
            pygame.draw.rect(screen, block_color, (block_x, block_y, BLOCK_SIZE, BLOCK_SIZE))
            pygame.draw.rect(screen, WHITE, (block_x, block_y, BLOCK_SIZE, BLOCK_SIZE), 1)

        if active_tetromino:
            active_tetromino.draw()

        score_text = font.render(f"Score: {score}", True, WHITE)
        screen.blit(score_text, (COLUMNS * BLOCK_SIZE + 10, 10))

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

    pygame.quit()

if __name__ == "__main__":
    main()

# data[].attributes.body
import pygame

import random

import sys

# 초기화

pygame.init()

WIDTH, HEIGHT = 500, 700

screen = pygame.display.set_mode((WIDTH, HEIGHT))

pygame.display.set_caption("Falling Object Game with Shell and Bonobono")

clock = pygame.time.Clock()

# 색상

WHITE = (255, 255, 255)

BLACK = (0, 0, 0)

BLUE = (0, 150, 255)

RED = (255, 0, 0)

GREEN = (0, 200, 0)

# 글꼴

font = pygame.font.SysFont("Arial", 28)

input_font = pygame.font.SysFont("Arial", 24)

# 기본 설정

player_size = 50

player_speed = 7

object_size = 50 # 물체 크기 줄이기

object_speed = 6 # 물체 속도 높이기

# 위치

player_x = WIDTH // 2 - player_size // 2

player_y = HEIGHT - player_size - 10

object_x = random.randint(0, WIDTH - object_size)

object_y = 0

# 게임 변수

score = 0

misses = 0

level = 1

quiz_asked = False

quiz_active = False

quiz_answer = ""

quiz_result = None

correct_answers = ["usa", "united states", "america", "u.s.a."] # 정답 리스트

level_up_shown = False

level_up_message = ""

# 게임 루프

running = True

while running:

screen.fill(WHITE)

for event in pygame.event.get():

if event.type == pygame.QUIT:

running = False

if quiz_active:

if event.type == pygame.KEYDOWN:

if event.key == pygame.K_RETURN:

if quiz_answer.strip().lower() in correct_answers: # 정답 처리

score += 2

quiz_result = "correct"

else:

score -= 2

quiz_result = "wrong"

quiz_active = False

elif event.key == pygame.K_BACKSPACE:

quiz_answer = quiz_answer[:-1]

else:

quiz_answer += event.unicode

# 키 조작

if not quiz_active:

keys = pygame.key.get_pressed()

if keys[pygame.K_LEFT] and player_x > 0:

player_x -= player_speed

if keys[pygame.K_RIGHT] and player_x < WIDTH - player_size:

player_x += player_speed

object_y += object_speed

# 충돌 감지

player_rect = pygame.Rect(player_x, player_y, player_size, player_size)

object_rect = pygame.Rect(object_x, object_y, object_size, object_size)

if player_rect.colliderect(object_rect):

score += 1

object_x = random.randint(0, WIDTH - object_size)

object_y = 0

object_speed += 0.2 # 물체 속도 상승

# 놓침 감지

if object_y > HEIGHT:

misses += 1

object_x = random.randint(0, WIDTH - object_size)

object_y = 0

object_speed += 0.2 # 물체 속도 상승

# 레벨 업 조건

if score >= 20 and level < 4:

level = 4

object_speed += 2

object_size = 30

player_size = 40

level_up_message = "Level 4 - Max Speed!"

level_up_shown = True

elif score >= 15 and level < 3:

level = 3

object_speed += 2

object_size = 40

player_size = 45

level_up_message = "Level 3 - Even Faster!"

level_up_shown = True

elif score >= 10 and level < 2:

level = 2

object_speed += 1

object_size = 45

player_size = 50

level_up_message = "Level 2 - Faster Objects!"

level_up_shown = True

# 퀴즈 출제

if score >= 5 and not quiz_asked:

quiz_active = True

quiz_asked = True

quiz_answer = ""

object_y = 0

# 게임 오버 조건

if misses >= 3:

game_over_text = font.render("Game Over: Too many misses!", True, RED)

screen.blit(game_over_text, (60, HEIGHT // 2))

pygame.display.flip()

pygame.time.delay(2000)

running = False

# 게임 클리어

if score > 25:

win_text = font.render("You Win! Well Done!", True, GREEN)

screen.blit(win_text, (100, HEIGHT // 2))

pygame.display.flip()

pygame.time.delay(2000)

running = False

# 그리기

pygame.draw.rect(screen, BLUE, (player_x, player_y, player_size, player_size)) # 플레이어 그리기 (보노보노 대신 사각형)

pygame.draw.rect(screen, BLACK, (object_x, object_y, object_size, object_size)) # 물체 그리기 (조개 대신 사각형)

# HUD

screen.blit(font.render(f"Score: {score}", True, BLACK), (10, 10))

screen.blit(font.render(f"Misses: {misses}/3", True, RED), (10, 50))

screen.blit(font.render(f"Level: {level}", True, BLACK), (10, 90))

# 레벨 업 메시지 표시

if level_up_shown:

msg = font.render(level_up_message, True, RED)

screen.blit(msg, (60, HEIGHT // 2 - 100))

pygame.display.flip()

pygame.time.delay(1500)

level_up_shown = False

# 퀴즈 UI

if quiz_active:

question = font.render("Which country will host the next Olympics?", True, BLACK)

input_box = pygame.Rect(40, HEIGHT // 2, 420, 40)

pygame.draw.rect(screen, WHITE, input_box)

pygame.draw.rect(screen, BLACK, input_box, 2)

input_text = input_font.render(quiz_answer, True, BLACK)

screen.blit(question, (20, HEIGHT // 2 - 50))

screen.blit(input_text, (input_box.x + 5, input_box.y + 5))

if quiz_result == "correct":

result_text = font.render("Correct! +2 points", True, GREEN)

screen.blit(result_text, (140, HEIGHT // 2 + 80))

elif quiz_result == "wrong":

result_text = font.render("Wrong! -2 points", True, RED)

screen.blit(result_text, (140, HEIGHT // 2 + 80))

pygame.display.flip()

clock.tick(60)

pygame.quit()

sys.exit()