#!/usr/bin/env python3
import pygame
import sys
import math

# --- 初期設定 ---
pygame.init()
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 650
FPS = 60  # ← これが漏れていました
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("ブロック崩し - ステージループ版")
clock = pygame.time.Clock()

# 色の定義
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
PADDLE_COLOR = (50, 150, 255)
BALL_COLOR = (255, 200, 0)
BLOCK_COLORS = [(255, 80, 80), (255, 140, 0), (255, 230, 0), (0, 220, 100), (0, 180, 255), (180, 100, 255)]

# フォントの設定
font = pygame.font.SysFont(None, 36)
large_font = pygame.font.SysFont(None, 60)

# --- ゲームの変数 ---
stage = 1
loop_count = 0  # 4面クリアして周回した回数
lives = 3       # 残りラケット数（初期値3）

# ラケットの設定
PADDLE_WIDTH = 100
PADDLE_HEIGHT = 15
paddle_x = (SCREEN_WIDTH - PADDLE_WIDTH) // 2
paddle_y = SCREEN_HEIGHT - 50
paddle_speed = 7

# ボールの設定
BALL_RADIUS = 8
base_speed = 5  # 初期速度
ball_speed = base_speed
ball_x = 0
ball_y = 0
ball_dx = 0
ball_dy = 0

# ブロックの管理リスト
blocks = []

# ゲームの状態
# "START_WAIT" (スペース待機), "PLAYING" (プレイ中), "GAME_OVER" (ゲームオーバー)
game_state = "START_WAIT"

# --- 関数定義 ---
def init_blocks(current_stage):
    """ステージに応じたブロックを生成する"""
    blocks.clear()
    rows = current_stage + 2  # 1面は3行、2面は4行...
    cols = 8
    block_width = SCREEN_WIDTH // cols
    block_height = 25
    
    for r in range(rows):
        color = BLOCK_COLORS[r % len(BLOCK_COLORS)]
        for c in range(cols):
            # 隙間を空けるために少し小さくRectを作る
            rect = pygame.Rect(c * block_width + 2, r * block_height + 50 + 2, block_width - 4, block_height - 4)
            blocks.append({"rect": rect, "color": color})

def reset_ball_and_paddle():
    """ミス時やステージ開始時に位置をリセットする"""
    global paddle_x, ball_x, ball_y, ball_dx, ball_dy
    paddle_x = (SCREEN_WIDTH - PADDLE_WIDTH) // 2
    # ボールはラケットの上に配置
    ball_x = paddle_x + PADDLE_WIDTH // 2
    ball_y = paddle_y - BALL_RADIUS - 5
    # 最初は真上付近に向かって飛ぶように設定
    ball_dx = 0
    ball_dy = -ball_speed

# 最初のステージ構築
init_blocks(stage)
reset_ball_and_paddle()

# --- メインループ ---
running = True
while running:
    screen.fill(BLACK)
    
    # 1. イベント処理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:  # ← event.type に修正
            running = False
            
        if event.type == pygame.KEYDOWN:  # ← event.type に修正
            if event.key == pygame.K_SPACE:
                if game_state == "START_WAIT":
                    game_state = "PLAYING"
                elif game_state == "GAME_OVER":
                    # ゲームオーバーからの完全リセット
                    stage = 1
                    loop_count = 0
                    lives = 3
                    ball_speed = base_speed
                    init_blocks(stage)
                    reset_ball_and_paddle()
                    game_state = "START_WAIT"

    # 2. 更新処理（移動や衝突判定）
    if game_state == "PLAYING":
        # キー入力によるラケット移動
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT] and paddle_x > 0:
            paddle_x -= paddle_speed
        if keys[pygame.K_RIGHT] and paddle_x < SCREEN_WIDTH - PADDLE_WIDTH:
            paddle_x += paddle_speed
            
        # ボールの移動
        ball_x += ball_dx
        ball_y += ball_dy
        
        # ボールと壁の衝突判定
        if ball_x - BALL_RADIUS <= 0 or ball_x + BALL_RADIUS >= SCREEN_WIDTH:
            ball_dx *= -1
        if ball_y - BALL_RADIUS <= 0:
            ball_dy *= -1
            
        # ボールが画面下に落ちた（ミス）
        if ball_y + BALL_RADIUS >= SCREEN_HEIGHT:
            lives -= 1
            if lives <= 0:
                game_state = "GAME_OVER"
            else:
                reset_ball_and_paddle()
                game_state = "START_WAIT"
                
        # ボールとラケットの衝突判定
        ball_rect = pygame.Rect(ball_x - BALL_RADIUS, ball_y - BALL_RADIUS, BALL_RADIUS * 2, BALL_RADIUS * 2)
        paddle_rect = pygame.Rect(paddle_x, paddle_y, PADDLE_WIDTH, PADDLE_HEIGHT)
        
        if ball_rect.colliderect(paddle_rect) and ball_dy > 0:
            # 当たった位置によって反射角を変える
            relative_intersect_x = (paddle_x + (PADDLE_WIDTH / 2)) - ball_x
            normalized_intersect_x = relative_intersect_x / (PADDLE_WIDTH / 2)
            bounce_angle = normalized_intersect_x * (math.pi / 3)  # 最大60度
            
            ball_dx = -ball_speed * math.sin(bounce_angle)
            ball_dy = -ball_speed * math.cos(bounce_angle)

        # ボールとブロックの衝突判定
        for block in blocks[:]:
            if ball_rect.colliderect(block["rect"]):
                overlap_left = ball_rect.right - block["rect"].left
                overlap_right = block["rect"].right - ball_rect.left
                overlap_top = ball_rect.bottom - block["rect"].top
                overlap_bottom = block["rect"].bottom - block["rect"].top
                
                min_overlap = min(overlap_left, overlap_right, overlap_top, overlap_bottom)
                
                if min_overlap == overlap_left or min_overlap == overlap_right:
                    ball_dx *= -1
                else:
                    ball_dy *= -1
                    
                blocks.remove(block)
                break
                
        # ステージクリア判定
        if len(blocks) == 0:
            stage += 1
            if stage > 4:
                stage = 1
                loop_count += 1
                ball_speed = base_speed + (loop_count * 1.5)
                lives += 1
                
            init_blocks(stage)
            reset_ball_and_paddle()
            game_state = "START_WAIT"

    # 3. 描画処理
    pygame.draw.rect(screen, PADDLE_COLOR, (paddle_x, paddle_y, PADDLE_WIDTH, PADDLE_HEIGHT))
    
    if game_state == "START_WAIT":
        ball_x = paddle_x + PADDLE_WIDTH // 2
        ball_y = paddle_y - BALL_RADIUS - 5
    pygame.draw.circle(screen, BALL_COLOR, (int(ball_x), int(ball_y)), BALL_RADIUS)
    
    for block in blocks:
        pygame.draw.rect(screen, block["color"], block["rect"])
        
    ui_text = font.render(f"Stage: {stage} (Loop: {loop_count})  Lives: {lives}", True, WHITE)
    screen.blit(ui_text, (10, 10))
    
    if game_state == "START_WAIT":
        msg = font.render("PRESS SPACE TO START", True, WHITE)
        screen.blit(msg, (SCREEN_WIDTH // 2 - msg.get_width() // 2, SCREEN_HEIGHT // 2 + 50))
    elif game_state == "GAME_OVER":
        over_text = large_font.render("GAME OVER", True, (255, 0, 0))
        retry_text = font.render("PRESS SPACE TO RESTART", True, WHITE)
        screen.blit(over_text, (SCREEN_WIDTH // 2 - over_text.get_width() // 2, SCREEN_HEIGHT // 2 - 30))
        screen.blit(retry_text, (SCREEN_WIDTH // 2 - retry_text.get_width() // 2, SCREEN_HEIGHT // 2 + 30))

    pygame.display.flip()
    clock.tick(FPS)  # ← ここで上で定義したFPS（60）を使います

pygame.quit()
sys.exit()
