import tkinter as tk
import random
import math

# ========================
# 配置
# ========================
CELL = 20
VIEW_W, VIEW_H = 35, 25
WORLD_W, WORLD_H = 80, 80

COLORS = {
    "grass": "#7CFC90",
    "dirt": "#8B5A2B",
    "stone": "#888888",
    "wood": "#DEB887",
    "leaf": "#228B22",
    "sand": "#F4D03F",
    "snow": "#FFFFFF",
    "water": "#5DADE2",
    "flower": "#FF69B4",
    "glow": "#FFFF99",
    "bedrock": "#111111",
    "bg": "#87CEEB",
}

THEMES = {
    "🌸 樱花粉": {"bg": "#FFE4E9", "btn": "#F8BBD0", "fg": "#D81B60"},
    "💙 天空蓝": {"bg": "#E3F2FD", "btn": "#90CAF9", "fg": "#1565C0"},
    "💚 抹茶绿": {"bg": "#E8F5E9", "btn": "#A5D6A7", "fg": "#2E7D32"},
    "🧡 蜜桔橙": {"bg": "#FFF3E0", "btn": "#FFCC80", "fg": "#EF6C00"},
    "💜 梦幻紫": {"bg": "#F3E5F5", "btn": "#CE93D8", "fg": "#7B1FA2"},
    "🍬 糖果色": {"bg": "#FCE4EC", "btn": "#F48FB1", "fg": "#C2185B"},
}

BLOCKS = ["grass", "dirt", "stone", "wood", "leaf", "sand", "snow", "flower", "glow"]

# ========================
# 世界生成
# ========================
world = [[None for _ in range(WORLD_H)] for _ in range(WORLD_W)]
player_x = WORLD_W // 2
player_y = 0

def simple_noise(x):
    return (
        math.sin(x * 0.1) * 3 +
        math.sin(x * 0.3) * 2 +
        math.sin(x * 0.5) * 1
    )

def generate_world():
    global player_y
    for x in range(WORLD_W):
        height = int(18 + simple_noise(x))
        for y in range(WORLD_H):
            if y < height - 4:
                world[x][y] = "stone"
            elif y < height - 1:
                world[x][y] = "dirt"
            elif y == height - 1:
                if y < 12:
                    world[x][y] = "snow"
                elif y > 22:
                    world[x][y] = "sand"
                else:
                    world[x][y] = "grass"
            elif y == height and random.random() < 0.05:
                world[x][y] = "flower"
            elif 0 < y - height < 4:
                world[x][y] = "water"
            else:
                world[x][y] = None
            if y == WORLD_H - 2:
                world[x][y] = "bedrock"

    for _ in range(30):
        tx = random.randint(5, WORLD_W - 5)
        th = int(18 + simple_noise(tx)) - 1
        for dy in range(3):
            world[tx][th - dy] = "wood"
        for dx in [-1, 0, 1]:
            for dy in [-1, 0, 1]:
                world[tx + dx][th - 3 + dy] = "leaf"

    for _ in range(50):
        gx = random.randint(0, WORLD_W - 1)
        gy = random.randint(WORLD_H // 2, WORLD_H - 5)
        world[gx][gy] = "glow"

    player_y = max(0, int(18 + simple_noise(player_x)) - 4)

generate_world()

# ========================
# 玩家
# ========================
vx = vy = 0
on_ground = False
inventory = {b: 10 for b in BLOCKS}
current_block = "grass"

# ========================
# UI
# ========================
root = tk.Tk()
root.title("🌍 超大世界沙盒")
root.resizable(False, False)

top = tk.Frame(root)
top.pack(fill="x")

canvas = tk.Canvas(
    root,
    width=VIEW_W * CELL,
    height=VIEW_H * CELL,
    highlightthickness=0
)
canvas.pack()

bottom = tk.Frame(root)
bottom.pack(fill="x")

label_info = tk.Label(root, font=("Consolas", 10))
label_info.pack()

theme_buttons = []

# ========================
# 换肤（✅ Canvas 用 background）
# ========================
def apply_theme(name):
    t = THEMES[name]
    root.configure(bg=t["bg"])
    top.configure(bg=t["bg"])
    bottom.configure(bg=t["bg"])
    canvas.configure(background=COLORS["bg"])  # ✅ 永不会炸
    label_info.configure(bg=t["bg"], fg=t["fg"])
    for btn in theme_buttons:
        btn.configure(bg=t["btn"], fg=t["fg"])

# ========================
# 绘制
# ========================
def draw():
    canvas.delete("all")
    ox = player_x - VIEW_W // 2
    oy = player_y - VIEW_H // 2

    for dx in range(VIEW_W):
        for dy in range(VIEW_H):
            wx, wy = ox + dx, oy + dy
            if 0 <= wx < WORLD_W and 0 <= wy < WORLD_H and world[wx][wy]:
                canvas.create_rectangle(
                    dx * CELL, dy * CELL,
                    (dx + 1) * CELL, (dy + 1) * CELL,
                    fill=COLORS[world[wx][wy]], outline="#555"
                )

    px = (VIEW_W // 2) * CELL
    py = (VIEW_H // 2) * CELL
    canvas.create_oval(px - 6, py - 6, px + 6, py + 6, fill="red")

    label_info.config(
        text=f"坐标:({player_x},{player_y}) 方块:{current_block} 库存:{inventory[current_block]}"
    )

# ========================
# 逻辑
# ========================
def update():
    global player_x, player_y, vy, on_ground
    player_x += vx
    player_y += vy
    player_x = max(0, min(WORLD_W - 1, player_x))

    below = world[player_x][min(WORLD_H - 1, player_y + 1)]
    on_ground = below is not None and below != "water"

    if not on_ground:
        vy += 0.5
    else:
        vy = 0

    draw()
    root.after(30, update)

# ========================
# 控制
# ========================
def key_down(e):
    global vx, vy
    if e.keysym in ("a", "Left"):
        vx = -1
    if e.keysym in ("d", "Right"):
        vx = 1
    if e.keysym in ("w", "Up", "space") and on_ground:
        vy = -4
    if e.keysym == "p":
        vx = vy = 0

def key_up(e):
    global vx
    if e.keysym in ("a", "d", "Left", "Right"):
        vx = 0

def click(e):
    global current_block
    ox = player_x - VIEW_W // 2
    oy = player_y - VIEW_H // 2
    wx = ox + e.x // CELL
    wy = oy + e.y // CELL
    if 0 <= wx < WORLD_W and 0 <= wy < WORLD_H:
        if e.num == 1:
            b = world[wx][wy]
            if b and b != "bedrock":
                inventory[b] += 1
                world[wx][wy] = None
        elif e.num == 3 and inventory[current_block] > 0 and world[wx][wy] is None:
            world[wx][wy] = current_block
            inventory[current_block] -= 1

def select(b):
    global current_block
    current_block = b

for b in BLOCKS:
    btn = tk.Button(bottom, text=b[:1].upper(), width=3, command=lambda b=b: select(b))
    btn.pack(side="left", padx=2)
    theme_buttons.append(btn)

for name in THEMES:
    btn = tk.Button(top, text=name, font=("Comic Sans MS", 9))
    btn.pack(side="left", padx=2)
    theme_buttons.append(btn)
    btn.configure(command=lambda n=name: apply_theme(n))

root.bind("<KeyPress>", key_down)
root.bind("<KeyRelease>", key_up)
canvas.bind("<Button-1>", click)
canvas.bind("<Button-3>", click)

apply_theme("🌸 樱花粉")
draw()
update()
root.mainloop()