import tkinter as tk
import math
import random

# ============ 配置 ============
WIDTH, HEIGHT = 900, 600
FOV = math.radians(72)
NEAR = 0.15
WORLD_SIZE = 12          # 世界 12x12（tkinter 性能有限，别太大）
GRAVITY = -16.0
JUMP = 6.5
MOVE_SPEED = 3.2
MOUSE_SENS = 0.004
EYE_HEIGHT = 1.55

BLOCK_COLORS = {
    1: (90, 160, 70),    # 草
    2: (140, 100, 60),   # 土
    3: (120, 120, 130),  # 石
    4: (150, 100, 50),   # 木
    5: (220, 200, 130),  # 沙
}
BLOCK_NAMES = {1: "草", 2: "土", 3: "石", 4: "木", 5: "沙"}


class Camera:
    def __init__(self):
        self.x, self.y, self.z = WORLD_SIZE / 2, 8.0, WORLD_SIZE / 2
        self.yaw = 0.0
        self.pitch = -0.2
        self.vy = 0.0
        self.on_ground = False

    def forward(self):
        cy, sy = math.cos(self.yaw), math.sin(self.yaw)
        cp, sp = math.cos(self.pitch), math.sin(self.pitch)
        return (sy * cp, sp, cy * cp)

    def right(self):
        return (math.cos(self.yaw), 0.0, -math.sin(self.yaw))


class World:
    def __init__(self):
        self.blocks = {}
        self.generate()

    def generate(self):
        random.seed(7)
        for x in range(WORLD_SIZE):
            for z in range(WORLD_SIZE):
                h = int(2 + 1.2 * math.sin(x * 0.5) + 1.2 * math.cos(z * 0.4)
                        + random.uniform(-0.3, 0.3))
                h = max(1, h)
                for y in range(h):
                    if y == h - 1:
                        t = 1
                    elif y >= h - 3:
                        t = 2
                    else:
                        t = 3
                    self.blocks[(x, y, z)] = t
        # 种树
        for _ in range(6):
            x = random.randint(2, WORLD_SIZE - 3)
            z = random.randint(2, WORLD_SIZE - 3)
            top = 0
            for y in range(20, -1, -1):
                if (x, y, z) in self.blocks:
                    top = y
                    break
            for i in range(1, 4):
                self.blocks[(x, top + i, z)] = 4
            for dx in (-1, 0, 1):
                for dz in (-1, 0, 1):
                    if dx == 0 and dz == 0:
                        continue
                    self.blocks[(x + dx, top + 3, z + dz)] = 1

    def get(self, x, y, z):
        return self.blocks.get((x, y, z), 0)

    def set(self, x, y, z, t):
        if t == 0:
            self.blocks.pop((x, y, z), None)
        else:
            self.blocks[(x, y, z)] = t

    def solid_at(self, x, y, z):
        return (math.floor(x), math.floor(y), math.floor(z)) in self.blocks


def project(point, cam):
    px, py, pz = point
    dx = px - cam.x
    dy = py - cam.y
    dz = pz - cam.z
    cy, sy = math.cos(-cam.yaw), math.sin(-cam.yaw)
    rx = dx * cy + dz * sy
    rz = -dx * sy + dz * cy
    cp, sp = math.cos(-cam.pitch), math.sin(-cam.pitch)
    ry = dy * cp - rz * sp
    rz2 = dy * sp + rz * cp
    if rz2 < NEAR:
        return None
    f = (HEIGHT / 2) / math.tan(FOV / 2)
    sx = WIDTH / 2 + (rx / rz2) * f
    sy_screen = HEIGHT / 2 - (ry / rz2) * f
    return (sx, sy_screen, rz2)


def block_faces(x, y, z):
    x0, y0, z0 = x, y, z
    x1, y1, z1 = x + 1, y + 1, z + 1
    return {
        'top':    [(x0, y1, z0), (x1, y1, z0), (x1, y1, z1), (x0, y1, z1)],
        'bottom': [(x0, y0, z0), (x0, y0, z1), (x1, y0, z1), (x1, y0, z0)],
        'north':  [(x0, y0, z0), (x1, y0, z0), (x1, y1, z0), (x0, y1, z0)],
        'south':  [(x0, y0, z1), (x0, y1, z1), (x1, y1, z1), (x1, y0, z1)],
        'west':   [(x0, y0, z0), (x0, y1, z0), (x0, y1, z1), (x0, y0, z1)],
        'east':   [(x1, y0, z0), (x1, y0, z1), (x1, y1, z1), (x1, y1, z0)],
    }


def face_shade(base, face):
    shade = {'top': 1.15, 'bottom': 0.55, 'north': 0.85,
             'south': 0.95, 'west': 0.75, 'east': 1.0}[face]
    return tuple(min(255, max(0, int(c * shade))) for c in base)


def color_hex(rgb):
    return "#%02x%02x%02x" % rgb


class Game:
    def __init__(self, root):
        self.root = root
        self.root.title("迷你 3D 沙盒 - 纯 tkinter 版")
        self.root.resizable(False, False)

        self.canvas = tk.Canvas(root, width=WIDTH, height=HEIGHT,
                                bg="black", highlightthickness=0)
        self.canvas.pack()

        self.world = World()
        self.cam = Camera()
        self.selected_type = 1

        self.keys = set()
        self.mouse_locked = False

        # 事件
        root.bind("<KeyPress>", self.on_key_down)
        root.bind("<KeyRelease>", self.on_key_up)
        self.canvas.bind("<ButtonPress-1>", lambda e: self.break_block())
        self.canvas.bind("<ButtonPress-3>", lambda e: self.place_block())
        self.canvas.bind("<Motion>", self.on_motion)
        self.canvas.bind("<Button-1>", self.on_canvas_click, add="+")

        self.last_mouse = None
        self.running = True

        self.loop()

    # ---------- 输入 ----------
    def on_key_down(self, e):
        k = e.keysym.lower()
        self.keys.add(k)
        if k == "escape":
            self.running = False
            self.root.destroy()
        if k == "space" and self.cam.on_ground:
            self.cam.vy = JUMP
        if k in ("1", "2", "3", "4", "5"):
            self.selected_type = int(k)

    def on_key_up(self, e):
        self.keys.discard(e.keysym.lower())

    def on_motion(self, e):
        # 鼠标按住左键拖动转视角（tkinter 无法真正锁定鼠标）
        if self.mouse_locked and self.last_mouse:
            dx = e.x - self.last_mouse[0]
            dy = e.y - self.last_mouse[1]
            self.cam.yaw += dx * MOUSE_SENS
            self.cam.pitch -= dy * MOUSE_SENS
            self.cam.pitch = max(-math.pi / 2 + 0.05,
                                 min(math.pi / 2 - 0.05, self.cam.pitch))
        self.last_mouse = (e.x, e.y)

    def on_canvas_click(self, e):
        # 点击画布获取焦点并进入“拖动视角”模式
        self.canvas.focus_set()
        self.mouse_locked = True

    # ---------- 交互 ----------
    def raycast(self, max_dist=7.0):
        step = 0.08
        d = 0.0
        fx, fy, fz = self.cam.forward()
        while d < max_dist:
            px = self.cam.x + fx * d
            py = self.cam.y + fy * d
            pz = self.cam.z + fz * d
            bx, by, bz = math.floor(px), math.floor(py), math.floor(pz)
            if (bx, by, bz) in self.world.blocks:
                return (bx, by, bz)
            d += step
        return None

    def break_block(self):
        hit = self.raycast()
        if hit:
            self.world.set(*hit, 0)

    def place_block(self):
        hit = self.raycast()
        if not hit:
            return
        bx, by, bz = hit
        for off in [(0, 0, 0), (-1, 0, 0), (1, 0, 0), (0, -1, 0),
                    (0, 1, 0), (0, 0, -1), (0, 0, 1)]:
            nx, ny, nz = bx + off[0], by + off[1], bz + off[2]
            if (nx, ny, nz) not in self.world.blocks:
                # 别放进自己身体
                if not (math.floor(self.cam.x) == nx and
                        math.floor(self.cam.y - EYE_HEIGHT) <= ny <= math.floor(self.cam.y) and
                        math.floor(self.cam.z) == nz):
                    self.world.set(nx, ny, nz, self.selected_type)
                    return

    # ---------- 物理 ----------
    def try_move(self, dx, dy, dz):
        cam = self.cam
        if not self.world.solid_at(cam.x + dx, cam.y, cam.z):
            cam.x += dx
        if not self.world.solid_at(cam.x, cam.y, cam.z + dz):
            cam.z += dz
        cam.y += dy
        foot = cam.y - EYE_HEIGHT
        if self.world.solid_at(cam.x, foot, cam.z):
            cam.y = math.floor(foot) + 1 + EYE_HEIGHT
            cam.vy = 0
            cam.on_ground = True
        else:
            cam.on_ground = False
        if self.world.solid_at(cam.x, cam.y + 0.2, cam.z):
            cam.y -= 0.2
            if cam.vy > 0:
                cam.vy = 0

    # ---------- 主循环 ----------
    def loop(self):
        if not self.running:
            return
        dt = 1 / 30.0  # 固定步长，tkinter 下更稳定

        # 移动
        fwd = self.cam.forward()
        rgt = self.cam.right()
        mvx = mvz = 0.0
        if "w" in self.keys:
            mvx += fwd[0]; mvz += fwd[2]
        if "s" in self.keys:
            mvx -= fwd[0]; mvz -= fwd[2]
        if "a" in self.keys:
            mvx -= rgt[0]; mvz -= rgt[2]
        if "d" in self.keys:
            mvx += rgt[0]; mvz += rgt[2]
        mlen = math.hypot(mvx, mvz)
        if mlen > 0:
            mvx = mvx / mlen * MOVE_SPEED * dt
            mvz = mvz / mlen * MOVE_SPEED * dt

        # 键盘转视角（Q/E 左右，R/F 上下）
        if "q" in self.keys:
            self.cam.yaw -= 1.5 * dt
        if "e" in self.keys:
            self.cam.yaw += 1.5 * dt
        if "r" in self.keys:
            self.cam.pitch = min(math.pi / 2 - 0.05, self.cam.pitch + 1.2 * dt)
        if "f" in self.keys:
            self.cam.pitch = max(-math.pi / 2 + 0.05, self.cam.pitch - 1.2 * dt)

        # 重力
        self.cam.vy += GRAVITY * dt
        dy = self.cam.vy * dt
        self.try_move(mvx, dy, mvz)

        if self.cam.y < -10:
            self.cam.x, self.cam.y, self.cam.z = WORLD_SIZE / 2, 10, WORLD_SIZE / 2
            self.cam.vy = 0

        self.render()
        self.root.after(33, self.loop)

    # ---------- 渲染 ----------
    def render(self):
        c = self.canvas
        c.delete("all")

        # 天空渐变
        bands = 24
        for i in range(bands):
            t = i / bands
            r = int(120 + 60 * t)
            g = int(175 + 40 * t)
            b = int(235)
            y0 = int(HEIGHT * i / bands)
            y1 = int(HEIGHT * (i + 1) / bands)
            c.create_rectangle(0, y0, WIDTH, y1, fill=color_hex((r, g, b)), outline="")

        # 收集可见面
        faces = []
        cam = self.cam
        for (bx, by, bz), t in self.world.blocks.items():
            dx, dy, dz = bx - cam.x, by - cam.y, bz - cam.z
            if dx * dx + dz * dz > 45 * 45:
                continue
            base = BLOCK_COLORS[t]
            for fname, verts in block_faces(bx, by, bz).items():
                proj = [project(v, cam) for v in verts]
                if any(p is None for p in proj):
                    continue
                depth = sum(p[2] for p in proj) / 4
                faces.append((depth, proj, face_shade(base, fname)))

        faces.sort(key=lambda x: -x[0])
        for depth, proj, col in faces:
            pts = []
            for p in proj:
                pts.extend([p[0], p[1]])
            c.create_polygon(pts, fill=color_hex(col), outline="#000000")

        # 准星
        cx, cy = WIDTH // 2, HEIGHT // 2
        c.create_line(cx - 10, cy, cx + 10, cy, fill="white", width=2)
        c.create_line(cx, cy - 10, cx, cy + 10, fill="white", width=2)

        # 命中高亮
        hit = self.raycast()
        if hit:
            for fname, verts in block_faces(*hit).items():
                proj = [project(v, cam) for v in verts]
                if any(p is None for p in proj):
                    continue
                pts = []
                for p in proj:
                    pts.extend([p[0], p[1]])
                c.create_polygon(pts, fill="", outline="yellow", width=2)

        # HUD
        info = f"坐标 ({self.cam.x:.1f}, {self.cam.y:.1f}, {self.cam.z:.1f})  朝向 {math.degrees(self.cam.yaw):.0f}°"
        c.create_text(10, 10, text=info, fill="white", anchor="nw",
                      font=("Microsoft YaHei", 12, "bold"))
        help_text = "WASD移动 空格跳 QE转左右 RF转上下 左键破坏 右键放置 1-5选方块 点击画面后拖动转视角 ESC退出"
        c.create_text(10, HEIGHT - 12, text=help_text, fill="#dddddd", anchor="sw",
                      font=("Microsoft YaHei", 10))

        # 物品栏
        slot_w = 56
        start_x = WIDTH // 2 - slot_w * 3
        y = HEIGHT - 80
        for i, t in enumerate([1, 2, 3, 4, 5]):
            x = start_x + i * slot_w
            selected = (t == self.selected_type)
            outline = "yellow" if selected else "#cccccc"
            c.create_rectangle(x, y, x + slot_w - 6, y + slot_w - 6,
                               fill="#28283a", outline=outline, width=2)
            c.create_rectangle(x + 8, y + 8, x + slot_w - 14, y + slot_w - 14,
                               fill=color_hex(BLOCK_COLORS[t]), outline="")
            c.create_text(x + 5, y + 4, text=str(i + 1), fill="white", anchor="nw",
                          font=("Microsoft YaHei", 9, "bold"))
            c.create_text(x + (slot_w - 6) // 2, y + slot_w - 8,
                          text=BLOCK_NAMES[t], fill="white",
                          font=("Microsoft YaHei", 9))


if __name__ == "__main__":
    root = tk.Tk()
    game = Game(root)
    root.mainloop()