import pygame
import sys
import random
import math

pygame.init()

# 窗口
WIDTH, HEIGHT = 900, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("模拟快餐厅")

# 颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED   = (255, 80, 80)
GREEN = (80, 200, 80)
BLUE  = (80, 80, 255)
YELLOW = (255, 255, 0)
BROWN = (139, 69, 19)
GRAY  = (200, 200, 200)
DARK_GRAY = (100, 100, 100)

# 字体
font = pygame.font.SysFont("SimHei", 22)
small_font = pygame.font.SysFont("SimHei", 16)

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

# ---------- 食物类型 ----------
FOOD_TYPES = {
    "burger": {"name": "汉堡", "color": (200, 120, 50), "price": 15, "time": 90},
    "fries":  {"name": "薯条", "color": (240, 200, 50), "price": 10, "time": 70},
    "cola":   {"name": "可乐", "color": (180, 50, 50),  "price": 8,  "time": 50}
}

# ---------- 顾客类 ----------
class Customer:
    def __init__(self):
        self.x = -50  # 从左侧进入
        self.y = random.randint(200, 450)  # 随机纵向位置
        self.target_x = random.randint(150, 350)  # 走到柜台前的位置
        self.speed = 1.5
        self.food = random.choice(list(FOOD_TYPES.keys()))  # 想点的食物
        self.waited = 0
        self.max_wait = 500  # 最大等待帧数（约8秒）
        self.served = False
        self.angry = False
        self.paid = False

    def move(self):
        if self.served or self.angry:
            self.x += 3  # 离开
            return
        if self.x < self.target_x:
            self.x += self.speed
        else:
            self.waited += 1
            if self.waited >= self.max_wait:
                self.angry = True  # 等太久生气

    def draw(self, surface):
        if self.served or self.angry:
            return
        # 身体
        pygame.draw.circle(surface, BLUE, (int(self.x), int(self.y)), 18)
        # 头顶食物图标
        food_color = FOOD_TYPES[self.food]["color"]
        pygame.draw.circle(surface, food_color, (int(self.x), int(self.y)-30), 10)
        # 表情
        if self.waited > self.max_wait * 0.7:
            # 生气表情
            pygame.draw.line(surface, RED, (self.x-5, self.y-5), (self.x-2, self.y-3), 2)
            pygame.draw.line(surface, RED, (self.x+5, self.y-5), (self.x+2, self.y-3), 2)

# ---------- 厨房食物制作槽 ----------
class CookingSlot:
    def __init__(self, pos):
        self.pos = pos
        self.food_type = None
        self.progress = 0      # 0~1
        self.cooking = False
        self.ready = False
        self.rect = pygame.Rect(pos[0]-25, pos[1]-25, 50, 50)

    def start_cook(self, food_type):
        if not self.cooking and not self.ready:
            self.food_type = food_type
            self.cooking = True
            self.progress = 0
            self.ready = False

    def update(self):
        if self.cooking and not self.ready:
            total_time = FOOD_TYPES[self.food_type]["time"]
            self.progress += 1 / total_time
            if self.progress >= 1:
                self.progress = 1
                self.cooking = False
                self.ready = True

    def take_food(self):
        if self.ready:
            self.ready = False
            self.food_type = None
            self.progress = 0
            return True
        return False

    def draw(self, surface):
        # 绘制背景
        color = GRAY
        if self.cooking:
            color = YELLOW
        elif self.ready:
            color = GREEN
        pygame.draw.rect(surface, color, self.rect)
        pygame.draw.rect(surface, BLACK, self.rect, 2)

        if self.food_type:
            # 进度条
            if self.cooking:
                bar_width = 40
                bar_height = 6
                bar_x = self.pos[0] - bar_width//2
                bar_y = self.pos[1] + 25
                pygame.draw.rect(surface, DARK_GRAY, (bar_x, bar_y, bar_width, bar_height))
                fill_width = int(bar_width * self.progress)
                pygame.draw.rect(surface, GREEN, (bar_x, bar_y, fill_width, bar_height))

            # 食物名称
            name = FOOD_TYPES[self.food_type]["name"]
            txt = small_font.render(name, True, BLACK)
            surface.blit(txt, (self.pos[0]-txt.get_width()//2, self.pos[1]+32))

# ---------- 游戏主类 ----------
class Game:
    def __init__(self):
        self.customers = []
        self.spawn_timer = 0
        self.spawn_delay = 120  # 每2秒可能生成顾客
        self.gold = 100
        self.reputation = 100   # 好评度
        self.game_over = False
        self.selected_customer = None  # 当前服务的目标顾客
        self.carrying_food = None      # 手上拿的食物类型

        # 厨房制作台（3个槽位）
        self.slots = [
            CookingSlot((600, 200)),
            CookingSlot((700, 200)),
            CookingSlot((800, 200))
        ]

    def spawn_customer(self):
        if len(self.customers) < 8 and random.random() < 0.4:
            self.customers.append(Customer())

    def update(self):
        if self.game_over:
            return

        # 生成顾客
        if self.spawn_timer <= 0:
            self.spawn_customer()
            self.spawn_timer = self.spawn_delay
        else:
            self.spawn_timer -= 1

        # 更新顾客
        for c in self.customers:
            c.move()

        # 处理离开的顾客
        for c in self.customers[:]:
            if c.angry and c.x > WIDTH + 50:
                self.customers.remove(c)
                self.reputation -= 10
                if self.reputation <= 0:
                    self.game_over = True
            elif c.served and c.x > WIDTH + 50:
                self.customers.remove(c)
                self.gold += FOOD_TYPES[c.food]["price"]
                self.reputation = min(100, self.reputation + 2)

        # 更新厨房
        for slot in self.slots:
            slot.update()

        # 检查好评度
        if self.reputation <= 0:
            self.game_over = True

    def handle_click(self, pos):
        if self.game_over:
            return

        # 检查是否点击了厨房制作台
        for slot in self.slots:
            if slot.rect.collidepoint(pos):
                if slot.ready and self.carrying_food is None:
                    # 拿起制作完成的食物
                    food = slot.food_type
                    slot.take_food()
                    self.carrying_food = food
                    return
                elif not slot.cooking and not slot.ready and self.carrying_food is None:
                    # 开始制作：如果没有选中食物，则提示；这里简化：随机做一种？
                    # 实际逻辑：应基于顾客需求，我们可以让玩家先选择顾客再看制作。
                    pass  # 为了简化，我们允许直接点击空槽开始制作随机食物（练习模式）
                    # 但更合理的是根据选中的顾客来制作，所以暂时忽略空槽点击

        # 检查是否点击了顾客
        for c in self.customers:
            if c.served or c.angry:
                continue
            cx, cy = int(c.x), int(c.y)
            if math.hypot(pos[0]-cx, pos[1]-cy) < 20:
                if self.carrying_food is not None:
                    # 手中拿着食物，尝试上菜
                    if self.carrying_food == c.food:
                        c.served = True
                        self.carrying_food = None
                        self.selected_customer = None
                    else:
                        # 食物不对
                        pass
                else:
                    # 选中顾客，准备为其制作
                    self.selected_customer = c
                    # 自动在空闲制作台开始制作对应食物
                    for slot in self.slots:
                        if not slot.cooking and not slot.ready:
                            slot.start_cook(c.food)
                            break
                return

        # 点击空白取消选择
        self.selected_customer = None

    def draw(self, surface):
        surface.fill((240, 230, 210))  # 米色背景

        # 绘制厨房区域
        pygame.draw.rect(surface, (220, 200, 180), (550, 100, 300, 200))  # 厨房底板
        for slot in self.slots:
            slot.draw(surface)

        # 绘制柜台
        pygame.draw.rect(surface, BROWN, (100, 100, 20, 400))
        pygame.draw.line(surface, BLACK, (120, 100), (120, 500), 2)

        # 绘制顾客
        for c in self.customers:
            c.draw(surface)

        # 手上拿的食物
        if self.carrying_food:
            mx, my = pygame.mouse.get_pos()
            food_color = FOOD_TYPES[self.carrying_food]["color"]
            pygame.draw.circle(surface, food_color, (mx, my), 12)
            pygame.draw.circle(surface, WHITE, (mx, my), 12, 2)

        # UI
        gold_text = font.render(f"金币: {self.gold}", True, BLACK)
        rep_text = font.render(f"好评: {self.reputation}/100", True, BLACK)
        surface.blit(gold_text, (20, 20))
        surface.blit(rep_text, (20, 50))

        # 提示
        if self.selected_customer:
            tip = font.render(f"为顾客制作{FOOD_TYPES[self.selected_customer.food]['name']}中...", True, BLUE)
            surface.blit(tip, (350, 20))

        if self.game_over:
            over_text = font.render("游戏结束！按R重新开始", True, RED)
            surface.blit(over_text, (WIDTH//2-150, HEIGHT//2-20))

def main():
    game = Game()
    running = True
    while running:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r and game.game_over:
                    game = Game()
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    game.handle_click(pygame.mouse.get_pos())

        game.update()
        game.draw(screen)
        pygame.display.flip()

    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()