# -*- coding: utf-8 -*-
"""
开心农家乐 · 20种作物成长版
运行：python main.py
玩法：开局只有萝卜，卖菜赚钱 → 点击未解锁种子卡片付费解锁 → 滚雪球
"""

import tkinter as tk
import random
import math
import time

# ==================== 参数 ====================
COLS, ROWS = 5, 4
CELL = 100
PAD = 14
CANVAS_W = COLS * CELL + PAD * 2
CANVAS_H = ROWS * CELL + PAD * 2

# 20 种作物（按解锁顺序）
CROPS = [
    dict(name="萝卜",     seed=10,       sell=28,        grow=8,  unlock=0,           color="#FF7043", dark="#E64A19", leaf="#66BB6A", shape="round"),
    dict(name="白菜",     seed=18,       sell=52,        grow=9,  unlock=30,          color="#AED581", dark="#558B2F", leaf="#7CB342", shape="big"),
    dict(name="番茄",     seed=35,       sell=105,       grow=10, unlock=100,         color="#E53935", dark="#B71C1C", leaf="#43A047", shape="round"),
    dict(name="土豆",     seed=70,       sell=220,       grow=11, unlock=280,         color="#D7CCC8", dark="#8D6E63", leaf="#558B2F", shape="round"),
    dict(name="玉米",     seed=130,      sell=440,       grow=12, unlock=750,         color="#FFC107", dark="#FF8F00", leaf="#558B2F", shape="long"),
    dict(name="茄子",     seed=240,      sell=860,       grow=13, unlock=2000,        color="#7B1FA2", dark="#4A148C", leaf="#43A047", shape="long"),
    dict(name="草莓",     seed=450,      sell=1750,      grow=14, unlock=5500,        color="#E91E63", dark="#AD1457", leaf="#66BB6A", shape="bunch"),
    dict(name="辣椒",     seed=850,      sell=3500,      grow=15, unlock=15000,       color="#F44336", dark="#C62828", leaf="#2E7D32", shape="long"),
    dict(name="西瓜",     seed=1600,     sell=7000,      grow=16, unlock=40000,       color="#2E7D32", dark="#1B5E20", leaf="#388E3C", shape="big"),
    dict(name="南瓜",     seed=3000,     sell=14000,     grow=17, unlock=110000,      color="#FF9800", dark="#E65100", leaf="#33691E", shape="big"),
    dict(name="葡萄",     seed=5500,     sell=28000,     grow=18, unlock=300000,      color="#8E24AA", dark="#4A148C", leaf="#43A047", shape="bunch"),
    dict(name="菠萝",     seed=10000,    sell=55000,     grow=19, unlock=800000,      color="#FFB300", dark="#FF6F00", leaf="#2E7D32", shape="pineapple"),
    dict(name="人参",     seed=19000,    sell=110000,    grow=20, unlock=2200000,     color="#FFF176", dark="#F9A825", leaf="#2E7D32", shape="ginseng"),
    dict(name="火龙果",   seed=35000,    sell=220000,    grow=21, unlock=6000000,     color="#F06292", dark="#AD1457", leaf="#2E7D32", shape="dragon"),
    dict(name="灵芝",     seed=65000,    sell=440000,    grow=22, unlock=16000000,    color="#8D6E63", dark="#5D4037", leaf="#33691E", shape="lingzhi"),
    dict(name="榴莲",     seed=120000,   sell=880000,    grow=23, unlock=45000000,    color="#C0CA33", dark="#827717", leaf="#33691E", shape="spiky"),
    dict(name="蓝莓",     seed=220000,   sell=1800000,   grow=24, unlock=120000000,   color="#3F51B5", dark="#1A237E", leaf="#43A047", shape="bunch"),
    dict(name="冬虫夏草", seed=400000,   sell=3600000,   grow=25, unlock=330000000,   color="#BCAAA4", dark="#6D4C41", leaf="#558B2F", shape="worm"),
    dict(name="蟠桃",     seed=750000,   sell=7200000,   grow=26, unlock=900000000,   color="#FFAB91", dark="#D84315", leaf="#43A047", shape="peach"),
    dict(name="金苹果",   seed=1400000,  sell=15000000,  grow=28, unlock=2500000000,  color="#FFD54F", dark="#F57F17", leaf="#33691E", shape="golden"),
]

# ==================== 工具 ====================
def fmt(n):
    n = int(n)
    if n >= 100000000:
        s = f"{n / 100000000:.2f}".rstrip("0").rstrip(".")
        return s + "亿"
    if n >= 10000:
        s = f"{n / 10000:.2f}".rstrip("0").rstrip(".")
        return s + "万"
    return str(n)


class Plot:
    __slots__ = ("x", "y", "size", "crop", "planted", "grow", "stage", "progress")

    def __init__(self, x, y, size):
        self.x, self.y, self.size = x, y, size
        self.crop = None
        self.planted = 0.0
        self.grow = 0.0
        self.stage = -1
        self.progress = 0.0


# ==================== 游戏 ====================
class FarmGame:
    def __init__(self, root):
        self.root = root
        root.title("🌱 开心农家乐 · 20种作物")
        root.configure(bg="#F1F8E9")
        root.resizable(False, False)

        self.money = 25
        self.selected = 0
        self.unlocked = [False] * len(CROPS)
        self.unlocked[0] = True
        self.btns = []
        self.plots = []
        self.running = True

        self._build_ui()
        self._init_plots()
        self.update_hud()
        self.render()

        self.root.after(400, lambda: self.toast(
            "点地块种萝卜，成熟后点它收获！", CANVAS_W // 2, 40, "#FFF59D"))
        self.tick()

    # ---------------- UI ----------------
    def _build_ui(self):
        top = tk.Frame(self.root, bg="#2E7D32")
        top.pack(fill="x")

        self.money_lbl = tk.Label(top, text="💰 25", font=("Microsoft YaHei", 16, "bold"),
                                  bg="#2E7D32", fg="#FFF176")
        self.money_lbl.pack(side="left", padx=(14, 10), pady=10)

        self.prog_lbl = tk.Label(top, text="已解锁 1 / 20", font=("Microsoft YaHei", 10, "bold"),
                                 bg="#2E7D32", fg="#C8E6C9")
        self.prog_lbl.pack(side="left", pady=10)

        tk.Button(top, text="🧺 一键收获", font=("Microsoft YaHei", 10, "bold"),
                  bg="#FFD54F", activebackground="#FFC107", relief="raised", bd=2,
                  cursor="hand2", command=self.harvest_all).pack(side="right", padx=14, pady=8)

        self.canvas = tk.Canvas(self.root, width=CANVAS_W, height=CANVAS_H,
                                bg="#7CB342", highlightthickness=0)
        self.canvas.pack(padx=8, pady=6)
        self.canvas.bind("<Button-1>", self.on_click)

        # 商店
        shop = tk.Frame(self.root, bg="#DCEDC8")
        shop.pack(fill="x", padx=8, pady=(0, 8))

        head = tk.Frame(shop, bg="#DCEDC8")
        head.pack(fill="x", padx=4, pady=(4, 2))
        tk.Label(head, text="🌰 种子商店", font=("Microsoft YaHei", 10, "bold"),
                 bg="#DCEDC8", fg="#33691E").pack(side="left")
        self.tip_lbl = tk.Label(head, text="点击未解锁种子付费解锁",
                                font=("Microsoft YaHei", 8), bg="#DCEDC8", fg="#689F38")
        self.tip_lbl.pack(side="right")

        grid = tk.Frame(shop, bg="#DCEDC8")
        grid.pack()

        for i, crop in enumerate(CROPS):
            r, c = divmod(i, 5)
            b = tk.Button(grid, text="", font=("Microsoft YaHei", 8),
                          width=10, height=2, relief="raised", bd=2,
                          bg="#FFFDE7", activebackground="#FFE082",
                          cursor="hand2", wraplength=72, justify="center",
                          command=lambda idx=i: self.click_seed(idx))
            b.grid(row=r, column=c, padx=2, pady=2)
            self.btns.append(b)

    def _init_plots(self):
        for r in range(ROWS):
            for c in range(COLS):
                x = PAD + c * CELL + 4
                y = PAD + r * CELL + 4
                self.plots.append(Plot(x, y, CELL - 8))

    # ---------------- 商店点击 ----------------
    def click_seed(self, idx):
        crop = CROPS[idx]
        if self.unlocked[idx]:
            self.selected = idx
            self.tip_lbl.config(text=f"已选：{crop['name']}  种子 {fmt(crop['seed'])}💰 → 卖 {fmt(crop['sell'])}💰")
            self.update_hud()
            return

        if self.money >= crop["unlock"]:
            self.money -= crop["unlock"]
            self.unlocked[idx] = True
            self.selected = idx
            self.toast(f"🎉 解锁「{crop['name']}」！", CANVAS_W // 2, 40, "#FFF176")
            self.update_hud()
        else:
            need = crop["unlock"] - self.money
            self.toast(f"还差 {fmt(need)} 金币解锁「{crop['name']}」",
                       CANVAS_W // 2, 40, "#FFCDD2")

    # ---------------- 菜地点击 ----------------
    def on_click(self, event):
        col = int((event.x - PAD) // CELL)
        row = int((event.y - PAD) // CELL)
        if not (0 <= col < COLS and 0 <= row < ROWS):
            return
        p = self.plots[row * COLS + col]

        if p.crop is None:
            self.try_plant(p)
        elif p.stage >= 3:
            self.harvest_one(p)
        else:
            left = max(0.0, p.grow - (time.time() - p.planted))
            self.toast(f"生长中 {left:.0f}s", p.x + p.size / 2, p.y + 26, "#E3F2FD")

    def try_plant(self, p):
        crop = CROPS[self.selected]
        cx, cy = p.x + p.size / 2, p.y + 26

        if self.money < crop["seed"]:
            self.toast("金币不够啦~", cx, cy, "#FFCDD2")
            return

        self.money -= crop["seed"]
        p.crop = self.selected
        p.planted = time.time()
        p.grow = crop["grow"]
        p.stage = 0
        p.progress = 0.0
        self.update_hud()
        self.render()

    def _roll(self, crop):
        r = random.random()
        qty = 3 if r < 0.10 else (2 if r < 0.32 else 1)
        return crop["sell"] * qty, qty

    def harvest_one(self, p):
        crop = CROPS[p.crop]
        gold, qty = self._roll(crop)
        self.money += gold
        p.crop = None
        p.stage = -1
        p.progress = 0.0
        txt = f"+{fmt(gold)}💰" + (f" ×{qty}!" if qty > 1 else "")
        self.toast(txt, p.x + p.size / 2, p.y + 26, "#FFF59D")
        self.update_hud()
        self.render()

    def harvest_all(self):
        total = count = 0
        for p in self.plots:
            if p.crop is not None and p.stage >= 3:
                gold, _ = self._roll(CROPS[p.crop])
                total += gold
                count += 1
                p.crop = None
                p.stage = -1
                p.progress = 0.0
        if count == 0:
            self.toast("还没有成熟作物哦~", CANVAS_W // 2, 40, "#FFCDD2")
            return
        self.money += total
        self.toast(f"收获 {count} 块地  +{fmt(total)}💰", CANVAS_W // 2, 40, "#FFF59D")
        self.update_hud()
        self.render()

    # ---------------- 主循环 ----------------
    def tick(self):
        if not self.running:
            return
        now = time.time()
        for p in self.plots:
            if p.crop is not None:
                prog = (now - p.planted) / p.grow
                p.progress = min(1.0, prog)
                if prog >= 1.0:
                    p.stage = 3
                elif prog >= 0.6:
                    p.stage = 2
                elif prog >= 0.25:
                    p.stage = 1
                else:
                    p.stage = 0
        self.render()
        self.root.after(150, self.tick)

    # ---------------- 绘制 ----------------
    def render(self):
        c = self.canvas
        c.delete("plot")
        for p in self.plots:
            self.draw_plot(p)

    def draw_plot(self, p):
        c = self.canvas
        x, y, s = p.x, p.y, p.size
        T = "plot"
        cx = x + s / 2
        ground = y + s * 0.76
        R = s / 92

        # 土块
        c.create_rectangle(x + 2, y + 3, x + s, y + s, fill="#4E342E", outline="", tags=T)
        c.create_rectangle(x, y, x + s - 2, y + s - 2, fill="#8D6E63", outline="", tags=T)
        for i in (1, 2):
            yy = y + s * i / 3
            c.create_line(x + 6, yy, x + s - 10, yy, fill="#7A5A50", tags=T)

        if p.crop is None:
            c.create_text(cx, ground - 12, text="+", fill="#A1887F",
                          font=("Arial", 20, "bold"), tags=T)
            return

        crop = CROPS[p.crop]
        leaf = crop["leaf"]

        if p.stage == 0:
            c.create_oval(cx - 11 * R, ground - 9 * R, cx + 11 * R, ground + 4 * R,
                          fill="#6D4C41", outline="", tags=T)
            c.create_oval(cx - 3.5 * R, ground - 13 * R, cx + 3.5 * R, ground - 6 * R,
                          fill="#558B2F", outline="", tags=T)

        elif p.stage == 1:
            c.create_line(cx, ground, cx, ground - 15 * R, fill="#4CAF50", width=3, tags=T)
            c.create_oval(cx - 13 * R, ground - 21 * R, cx - 1 * R, ground - 13 * R, fill=leaf, outline="", tags=T)
            c.create_oval(cx + 1 * R, ground - 27 * R, cx + 13 * R, ground - 19 * R, fill=leaf, outline="", tags=T)

        elif p.stage == 2:
            c.create_line(cx, ground, cx, ground - 28 * R, fill="#388E3C", width=4, tags=T)
            c.create_oval(cx - 15 * R, ground - 20 * R, cx - 1 * R, ground - 11 * R, fill=leaf, outline="", tags=T)
            c.create_oval(cx + 1 * R, ground - 26 * R, cx + 15 * R, ground - 17 * R, fill=leaf, outline="", tags=T)
            c.create_oval(cx - 13 * R, ground - 34 * R, cx - 1 * R, ground - 26 * R, fill=leaf, outline="", tags=T)
            c.create_oval(cx + 1 * R, ground - 40 * R, cx + 13 * R, ground - 32 * R, fill=leaf, outline="", tags=T)
            # 青果
            c.create_oval(cx - 6 * R, ground - 40 * R, cx + 6 * R, ground - 29 * R,
                          fill="#C5E1A5", outline="", tags=T)

        else:
            c.create_line(cx, ground, cx, ground - 28 * R, fill="#388E3C", width=4, tags=T)
            c.create_oval(cx - 15 * R, ground - 20 * R, cx - 1 * R, ground - 11 * R, fill=leaf, outline="", tags=T)
            c.create_oval(cx + 1 * R, ground - 26 * R, cx + 15 * R, ground - 17 * R, fill=leaf, outline="", tags=T)
            c.create_oval(cx - 13 * R, ground - 34 * R, cx - 1 * R, ground - 26 * R, fill=leaf, outline="", tags=T)
            c.create_oval(cx + 1 * R, ground - 40 * R, cx + 13 * R, ground - 32 * R, fill=leaf, outline="", tags=T)

            self._draw_fruit(cx, ground - 38 * R, crop, R, T)

            # 成熟金边
            c.create_rectangle(x + 1, y + 1, x + s - 3, y + s - 3,
                               outline="#FFD54F", width=3, tags=T)

        # 进度条
        if 0 < p.progress < 1:
            bx0, bx1 = x + 10, x + s - 12
            by0, by1 = y + s - 14, y + s - 7
            c.create_rectangle(bx0, by0, bx1, by1, fill="#37474F", outline="", tags=T)
            c.create_rectangle(bx0, by0, bx0 + (bx1 - bx0) * p.progress, by1,
                               fill="#8BC34A", outline="", tags=T)

    def _draw_fruit(self, cx, cy, crop, R, T):
        c = self.canvas
        col, dark, shape = crop["color"], crop["dark"], crop["shape"]

        if shape == "round":
            c.create_oval(cx - 13 * R, cy - 13 * R, cx + 13 * R, cy + 13 * R,
                          fill=col, outline=dark, width=2, tags=T)
            c.create_oval(cx - 8 * R, cy - 8 * R, cx - 3 * R, cy - 3 * R,
                          fill="white", outline="", tags=T)

        elif shape == "big":
            c.create_oval(cx - 16 * R, cy - 15 * R, cx + 16 * R, cy + 15 * R,
                          fill=col, outline=dark, width=2, tags=T)
            c.create_oval(cx - 9 * R, cy - 9 * R, cx - 4 * R, cy - 4 * R,
                          fill="white", outline="", tags=T)
            for dx in (-7, 0, 7):
                c.create_arc(cx + dx * R - 6 * R, cy - 14 * R,
                             cx + dx * R + 6 * R, cy + 14 * R,
                             start=200, extent=140, style="arc",
                             outline=dark, width=1, tags=T)

        elif shape == "long":
            c.create_oval(cx - 9 * R, cy - 20 * R, cx + 9 * R, cy + 18 * R,
                          fill=col, outline=dark, width=2, tags=T)
            c.create_oval(cx - 4 * R, cy - 15 * R, cx + 1 * R, cy - 8 * R,
                          fill="white", outline="", tags=T)

        elif shape == "bunch":
            for dx, dy in ((-9, -5), (9, -5), (0, -15), (-9, 7), (9, 7), (0, 2)):
                c.create_oval(cx + dx * R - 6 * R, cy + dy * R - 6 * R,
                              cx + dx * R + 6 * R, cy + dy * R + 6 * R,
                              fill=col, outline=dark, width=1, tags=T)
            c.create_oval(cx - 3 * R, cy - 21 * R, cx + 1 * R, cy - 17 * R,
                          fill="white", outline="", tags=T)

        elif shape == "pineapple":
            c.create_oval(cx - 11 * R, cy - 15 * R, cx + 11 * R, cy + 14 * R,
                          fill=col, outline=dark, width=2, tags=T)
            for i in range(-2, 3):
                c.create_line(cx - 9 * R, cy + i * 5 * R,
                              cx + 9 * R, cy + i * 5 * R + 4 * R,
                              fill=dark, tags=T)
                c.create_line(cx - 9 * R, cy + i * 5 * R + 4 * R,
                              cx + 9 * R, cy + i * 5 * R,
                              fill=dark, tags=T)
            for dx in (-5, 0, 5):
                c.create_polygon(cx + dx * R, cy - 15 * R,
                                 cx + (dx - 4) * R, cy - 26 * R,
                                 cx + (dx + 4) * R, cy - 26 * R,
                                 fill="#2E7D32", outline="", tags=T)

        elif shape == "ginseng":
            c.create_oval(cx - 6 * R, cy - 16 * R, cx + 6 * R, cy - 1 * R,
                          fill=col, outline=dark, width=2, tags=T)
            c.create_line(cx, cy - 2 * R, cx, cy + 16 * R, fill=col, width=max(3, 6 * R), tags=T)
            c.create_line(cx, cy + 2 * R, cx - 7 * R, cy + 10 * R, fill=col, width=max(2, 4 * R), tags=T)
            c.create_line(cx, cy + 2 * R, cx + 7 * R, cy + 10 * R, fill=col, width=max(2, 4 * R), tags=T)

        elif shape == "dragon":
            c.create_oval(cx - 13 * R, cy - 13 * R, cx + 13 * R, cy + 13 * R,
                          fill=col, outline=dark, width=2, tags=T)
            for dx, dy in ((-8, -7), (0, -11), (8, -7), (-8, 4), (8, 4)):
                c.create_polygon(cx + dx * R, cy + dy * R,
                                 cx + (dx - 3) * R, cy + (dy + 6) * R,
                                 cx + (dx + 3) * R, cy + (dy + 6) * R,
                                 fill="#2E7D32", outline="", tags=T)
            c.create_oval(cx - 4 * R, cy - 5 * R, cx + 4 * R, cy + 1 * R,
                          fill="white", outline="", tags=T)

        elif shape == "lingzhi":
            c.create_arc(cx - 16 * R, cy - 12 * R, cx + 16 * R, cy + 14 * R,
                         start=0, extent=180, style="chord",
                         fill=col, outline=dark, width=2, tags=T)
            c.create_rectangle(cx - 3 * R, cy + 2 * R, cx + 3 * R, cy + 16 * R,
                               fill=dark, outline="", tags=T)
            c.create_oval(cx - 7 * R, cy - 8 * R, cx - 3 * R, cy - 4 * R,
                          fill="#FFF176", outline="", tags=T)

        elif shape == "spiky":
            for ang in range(0, 360, 40):
                rad = math.radians(ang)
                x1, y1 = cx + 13 * R * math.cos(rad), cy + 13 * R * math.sin(rad)
                x2 = cx + 20 * R * math.cos(rad - 0.16)
                y2 = cy + 20 * R * math.sin(rad - 0.16)
                x3 = cx + 20 * R * math.cos(rad + 0.16)
                y3 = cy + 20 * R * math.sin(rad + 0.16)
                c.create_polygon(x1, y1, x2, y2, x3, y3, fill="#827717", outline="", tags=T)
            c.create_oval(cx - 13 * R, cy - 13 * R, cx + 13 * R, cy + 13 * R,
                          fill=col, outline=dark, width=2, tags=T)
            c.create_oval(cx - 7 * R, cy - 7 * R, cx - 2 * R, cy - 2 * R,
                          fill="white", outline="", tags=T)

        elif shape == "worm":
            pts = [(-10, 8), (-6, 2), (-1, -4), (4, -8), (9, -8)]
            for px, py in pts:
                c.create_oval(cx + px * R - 4 * R, cy + py * R - 4 * R,
                              cx + px * R + 4 * R, cy + py * R + 4 * R,
                              fill=col, outline="", tags=T)
            c.create_oval(cx + 7 * R, cy - 14 * R, cx + 14 * R, cy - 7 * R,
                          fill=dark, outline="", tags=T)

        elif shape == "peach":
            c.create_oval(cx - 13 * R, cy - 13 * R, cx + 13 * R, cy + 13 * R,
                          fill=col, outline=dark, width=2, tags=T)
            c.create_arc(cx - 8 * R, cy - 12 * R, cx + 8 * R, cy + 2 * R,
                         start=200, extent=140, style="arc",
                         outline=dark, width=2, tags=T)
            c.create_oval(cx - 8 * R, cy - 7 * R, cx - 3 * R, cy - 2 * R,
                          fill="white", outline="", tags=T)
            c.create_polygon(cx - 1 * R, cy - 13 * R,
                             cx + 7 * R, cy - 21 * R,
                             cx + 4 * R, cy - 11 * R,
                             fill="#2E7D32", outline="", tags=T)

        elif shape == "golden":
            c.create_oval(cx - 13 * R, cy - 13 * R, cx + 13 * R, cy + 13 * R,
                          fill=col, outline="#F57F17", width=3, tags=T)
            c.create_oval(cx - 8 * R, cy - 8 * R, cx - 3 * R, cy - 3 * R,
                          fill="white", outline="", tags=T)
            c.create_polygon(cx - 1 * R, cy - 13 * R,
                             cx + 6 * R, cy - 21 * R,
                             cx + 9 * R, cy - 11 * R,
                             fill="#2E7D32", outline="", tags=T)

    # ---------------- 飘字 ----------------
    def toast(self, text, x, y, color="#FFFFFF"):
        item = self.canvas.create_text(x, y, text=text, fill=color,
                                       font=("Microsoft YaHei", 10, "bold"),
                                       tags="fx")
        self._float(item, 0)

    def _float(self, item, n):
        if n > 22:
            self.canvas.delete(item)
            return
        self.canvas.move(item, 0, -1.5)
        self.root.after(40, lambda: self._float(item, n + 1))

    # ---------------- HUD ----------------
    def update_hud(self):
        self.money_lbl.config(text=f"💰 {fmt(self.money)}")
        self.prog_lbl.config(text=f"已解锁 {sum(self.unlocked)} / {len(CROPS)}")

        for i, b in enumerate(self.btns):
            crop = CROPS[i]
            if self.unlocked[i]:
                txt = f"{crop['name']}\n{fmt(crop['seed'])}💰"
                fg = "#A1887F" if self.money < crop["seed"] else "#33691E"
                if i == self.selected:
                    b.config(text=txt, bg="#FFE082", fg=fg, relief="sunken", state="normal")
                else:
                    b.config(text=txt, bg="#FFFDE7", fg=fg, relief="raised", state="normal")
            else:
                txt = f"🔒{crop['name']}\n{fmt(crop['unlock'])}解锁"
                if self.money >= crop["unlock"]:
                    b.config(text=txt, bg="#C8E6C9", fg="#1B5E20",
                             relief="raised", state="normal")
                else:
                    b.config(text=txt, bg="#ECEFF1", fg="#90A4AE",
                             relief="raised", state="normal")


# ==================== 启动 ====================
def main():
    root = tk.Tk()
    game = FarmGame(root)

    root.update_idletasks()
    w, h = root.winfo_width(), root.winfo_height()
    sw, sh = root.winfo_screenwidth(), root.winfo_screenheight()
    root.geometry(f"+{max(0, (sw - w) // 2)}+{max(0, (sh - h) // 2 - 10)}")

    def on_close():
        game.running = False
        root.destroy()

    root.protocol("WM_DELETE_WINDOW", on_close)
    root.mainloop()


if __name__ == "__main__":
    main()