import pygame
import random
import sys

pygame.init()

W, H = 900, 600
screen = pygame.display.set_mode((W, H))
pygame.display.set_caption("简易潜水员戴夫")
clock = pygame.time.Clock()
FPS = 60

# 颜色
BG_OCEAN = (20, 60, 100)
SURFACE = (80, 160, 220)
PLAYER = (30, 180, 220)
FISH_COLORS = [(255, 180, 60), (80, 220, 140), (220, 90, 130)]
TEXT_COLOR = (255, 255, 255)

def get_font(size):
    try:
        return pygame.font.SysFont("arial", size)
    except Exception:
        return pygame.font.Font(None, size)

font = get_font(20)
font_big = get_font(28)

STATE_DIVE = "dive"
STATE_RESTAURANT = "restaurant"
STATE_UPGRADE = "upgrade"
game_state = STATE_DIVE

player = {
    "x": 100,
    "y": 100,
    "speed": 4,
    "oxygen": 100,
    "max_oxygen": 100,
    "gold": 100,
    "inventory": [],
    "max_carry": 5
}

fish_list = []
harpoon = None

class Fish:
    def __init__(self):
        self.x = random.randint(200, W - 100)
        self.y = random.randint(150, H - 80)
        self.w = random.randint(24, 45)
        self.h = random.randint(14, 26)
        self.color = random.choice(FISH_COLORS)
        self.hp = random.randint(1, 3)
        self.value = random.randint(10, 40)
        self.dir = random.choice([-1, 1])
        self.speed = random.uniform(0.6, 1.6)

    def update(self):
        self.x += self.dir * self.speed
        if self.x < 50 or self.x > W - 50:
            self.dir *= -1

    def draw(self):
        pygame.draw.ellipse(screen, self.color, (self.x, self.y, self.w, self.h))

    def hit(self):
        self.hp -= 1
        return self.hp <= 0

def spawn_fish(count=6):
    fish_list.clear()
    for _ in range(count):
        fish_list.append(Fish())

spawn_fish()

def shoot_harpoon(from_x, from_y, target_x, target_y):
    dx = target_x - from_x
    dy = target_y - from_y
    dist = max((dx**2 + dy**2)**0.5, 1)
    return {"x": from_x, "y": from_y, "vx": dx / dist * 12, "vy": dy / dist * 12}

def draw_ui():
    pygame.draw.rect(screen, (40, 40, 40), (15, 15, 204, 24))
    o2_w = int(200 * (player["oxygen"] / player["max_oxygen"]))
    pygame.draw.rect(screen, (60, 180, 255), (17, 17, o2_w, 20))
    o2_text = font.render(f"O2 {int(player['oxygen'])}", True, TEXT_COLOR)
    screen.blit(o2_text, (225, 15))

    gold_text = font.render(f"Gold: {player['gold']}", True, TEXT_COLOR)
    screen.blit(gold_text, (15, 45))

    inv_text = font.render(f"Bag {len(player['inventory'])}/{player['max_carry']}", True, TEXT_COLOR)
    screen.blit(inv_text, (15, 75))

def draw_dive_scene():
    global harpoon
    screen.fill(BG_OCEAN)
    pygame.draw.rect(screen, SURFACE, (0, 0, W, 40))
    for f in fish_list:
        f.update()
        f.draw()

    pygame.draw.circle(screen, PLAYER, (int(player["x"]), int(player["y"])), 18)

    if harpoon is not None:
        pygame.draw.circle(screen, (255, 255, 100), (int(harpoon["x"]), int(harpoon["y"])), 5)
        harpoon["x"] += harpoon["vx"]
        harpoon["y"] += harpoon["vy"]
        hit = False
        for f in fish_list[:]:
            fx, fy, fw, fh = f.x, f.y, f.w, f.h
            if fx < harpoon["x"] < fx + fw and fy < harpoon["y"] < fy + fh:
                if f.hit():
                    if len(player["inventory"]) < player["max_carry"]:
                        player["inventory"].append(f.value)
                    fish_list.remove(f)
                hit = True
                break
        if hit or harpoon["x"] < 0 or harpoon["x"] > W or harpoon["y"] < 0 or harpoon["y"] > H:
            harpoon = None

    draw_ui()
    tip = font.render("WASD move | Click shoot | ESC next", True, TEXT_COLOR)
    screen.blit(tip, (15, H - 35))

def draw_restaurant():
    screen.fill((60, 35, 25))
    title = font_big.render("Sushi Shop - Sell Fish", True, TEXT_COLOR)
    screen.blit(title, (W//2 - 140, 60))
    total = sum(player["inventory"])
    sell_btn = pygame.Rect(W//2 - 90, 160, 180, 50)
    pygame.draw.rect(screen, (180, 120, 60), sell_btn)
    sell_text = font.render(f"Sell All (+{total})", True, (0,0,0))
    screen.blit(sell_text, (W//2 - 75, 175))

    info = font.render(f"Fish total: {total} | Gold: {player['gold']}", True, TEXT_COLOR)
    screen.blit(info, (W//2 - 160, 250))
    back_text = font.render("ESC -> Upgrade", True, TEXT_COLOR)
    screen.blit(back_text, (W//2 - 80, 320))
    return sell_btn

def draw_upgrade():
    screen.fill((30, 50, 40))
    title = font_big.render("Upgrade", True, TEXT_COLOR)
    screen.blit(title, (W//2 - 60, 50))

    btn_o2 = pygame.Rect(W//2 - 110, 130, 220, 45)
    btn_bag = pygame.Rect(W//2 - 110, 200, 220, 45)
    pygame.draw.rect(screen, (80, 140, 100), btn_o2)
    pygame.draw.rect(screen, (80, 140, 100), btn_bag)
    t1 = font.render(f"Oxygen +20 (50G) Now:{player['max_oxygen']}", True, (0,0,0))
    t2 = font.render(f"Bag +1 (80G) Now:{player['max_carry']}", True, (0,0,0))
    screen.blit(t1, (W//2 - 100, 142))
    screen.blit(t2, (W//2 - 100, 212))
    back_text = font.render("ESC -> Dive", True, TEXT_COLOR)
    screen.blit(back_text, (W//2 - 40, 280))
    return btn_o2, btn_bag

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                if game_state == STATE_DIVE:
                    game_state = STATE_RESTAURANT
                elif game_state == STATE_RESTAURANT:
                    game_state = STATE_UPGRADE
                elif game_state == STATE_UPGRADE:
                    player["oxygen"] = player["max_oxygen"]
                    spawn_fish()
                    game_state = STATE_DIVE
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            mx, my = pygame.mouse.get_pos()
            if game_state == STATE_DIVE:
                if harpoon is None:
                    harpoon = shoot_harpoon(player["x"], player["y"], mx, my)
            elif game_state == STATE_RESTAURANT:
                sell_btn = draw_restaurant()
                if sell_btn.collidepoint(mx, my):
                    earn = sum(player["inventory"])
                    player["gold"] += earn
                    player["inventory"].clear()
            elif game_state == STATE_UPGRADE:
                b1, b2 = draw_upgrade()
                if b1.collidepoint(mx, my) and player["gold"] >= 50:
                    player["gold"] -= 50
                    player["max_oxygen"] += 20
                if b2.collidepoint(mx, my) and player["gold"] >= 80:
                    player["gold"] -= 80
                    player["max_carry"] += 1

    # 每一帧都读取按键，专门处理移动
    keys = pygame.key.get_pressed()
    if game_state == STATE_DIVE:
        if keys[pygame.K_w]:
            player["y"] -= player["speed"]
        if keys[pygame.K_s]:
            player["y"] += player["speed"]
        if keys[pygame.K_a]:
            player["x"] -= player["speed"]
        if keys[pygame.K_d]:
            player["x"] += player["speed"]

        # 边界限制
        player["x"] = max(20, min(W - 20, player["x"]))
        player["y"] = max(45, min(H - 20, player["y"]))
        player["oxygen"] -= 0.04
        if player["oxygen"] <= 0:
            player["oxygen"] = 0
            game_state = STATE_RESTAURANT
        draw_dive_scene()
    elif game_state == STATE_RESTAURANT:
        draw_restaurant()
    elif game_state == STATE_UPGRADE:
        draw_upgrade()

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

pygame.quit()
sys.exit()
