import tkinter as tk
from tkinter import ttk, messagebox
import random


class App50:
    """スネークゲーム"""

    CELL = 20
    COLS = 20
    ROWS = 20
    SPEED = 150  # ms

    def __init__(self, root):
        self.root = root
        self.root.title("スネークゲーム")
        self.root.configure(bg="#111")
        self.root.resizable(False, False)
        self._build_ui()
        self.new_game()

    def _build_ui(self):
        # ヘッダー
        header = tk.Frame(self.root, bg="#222", pady=6)
        header.pack(fill=tk.X)
        tk.Label(header, text="🐍 スネークゲーム", font=("Noto Sans JP", 14, "bold"),
                 bg="#222", fg="#00ff88").pack(side=tk.LEFT, padx=12)
        self.score_label = tk.Label(header, text="スコア: 0", font=("Noto Sans JP", 12),
                                    bg="#222", fg="#fff")
        self.score_label.pack(side=tk.LEFT, padx=16)
        self.best_label = tk.Label(header, text="ベスト: 0", font=("Noto Sans JP", 10),
                                   bg="#222", fg="#aaa")
        self.best_label.pack(side=tk.LEFT)

        # キャンバス
        w = self.CELL * self.COLS
        h = self.CELL * self.ROWS
        self.canvas = tk.Canvas(self.root, width=w, height=h,
                                bg="#111", highlightthickness=0)
        self.canvas.pack(padx=8, pady=4)

        # フッター
        footer = tk.Frame(self.root, bg="#111", pady=4)
        footer.pack(fill=tk.X)
        tk.Label(footer, text="矢印キー / WASD で操作  |  Space でポーズ",
                 bg="#111", fg="#555", font=("Noto Sans JP", 9)).pack(side=tk.LEFT, padx=12)
        ttk.Button(footer, text="リスタート", command=self.new_game).pack(side=tk.RIGHT, padx=8)

        # キーバインド
        self.root.bind("<Left>",  lambda e: self.change_dir((-1, 0)))
        self.root.bind("<Right>", lambda e: self.change_dir((1, 0)))
        self.root.bind("<Up>",    lambda e: self.change_dir((0, -1)))
        self.root.bind("<Down>",  lambda e: self.change_dir((0, 1)))
        self.root.bind("<a>", lambda e: self.change_dir((-1, 0)))
        self.root.bind("<d>", lambda e: self.change_dir((1, 0)))
        self.root.bind("<w>", lambda e: self.change_dir((0, -1)))
        self.root.bind("<s>", lambda e: self.change_dir((0, 1)))
        self.root.bind("<space>", lambda e: self.toggle_pause())

        self.best_score = 0
        self._after_id = None

    def new_game(self):
        if self._after_id:
            self.root.after_cancel(self._after_id)
        cx, cy = self.COLS // 2, self.ROWS // 2
        self.snake = [(cx, cy), (cx - 1, cy), (cx - 2, cy)]
        self.direction = (1, 0)
        self.next_dir = (1, 0)
        self.score = 0
        self.paused = False
        self.game_over = False
        self._place_food()
        self._draw()
        self._tick()

    def change_dir(self, d):
        dx, dy = d
        if (dx, dy) != (-self.direction[0], -self.direction[1]):
            self.next_dir = d

    def toggle_pause(self):
        if self.game_over:
            return
        self.paused = not self.paused
        if not self.paused:
            self._tick()

    def _place_food(self):
        free = [(x, y) for x in range(self.COLS) for y in range(self.ROWS)
                if (x, y) not in self.snake]
        self.food = random.choice(free)

    def _tick(self):
        if self.paused or self.game_over:
            return
        self.direction = self.next_dir
        head = (self.snake[0][0] + self.direction[0],
                self.snake[0][1] + self.direction[1])

        # 壁・自分に衝突
        if (head[0] < 0 or head[0] >= self.COLS or
                head[1] < 0 or head[1] >= self.ROWS or
                head in self.snake):
            self.game_over = True
            self._draw()
            return

        self.snake.insert(0, head)
        if head == self.food:
            self.score += 10
            if self.score > self.best_score:
                self.best_score = self.score
            self.score_label.config(text=f"スコア: {self.score}")
            self.best_label.config(text=f"ベスト: {self.best_score}")
            self._place_food()
        else:
            self.snake.pop()

        self._draw()
        speed = max(60, self.SPEED - self.score // 50 * 10)
        self._after_id = self.root.after(speed, self._tick)

    def _draw(self):
        self.canvas.delete("all")
        c = self.CELL

        # グリッド（薄く）
        for x in range(0, self.COLS * c, c):
            self.canvas.create_line(x, 0, x, self.ROWS * c, fill="#1a1a1a")
        for y in range(0, self.ROWS * c, c):
            self.canvas.create_line(0, y, self.COLS * c, y, fill="#1a1a1a")

        # フード
        fx, fy = self.food
        self.canvas.create_oval(fx*c+3, fy*c+3, (fx+1)*c-3, (fy+1)*c-3,
                                fill="#ff4444", outline="")

        # スネーク
        for i, (x, y) in enumerate(self.snake):
            color = "#00ff88" if i == 0 else "#00cc66" if i < 4 else "#009944"
            self.canvas.create_rectangle(x*c+1, y*c+1, (x+1)*c-1, (y+1)*c-1,
                                         fill=color, outline="")

        if self.game_over:
            self.canvas.create_rectangle(0, 0, self.COLS*c, self.ROWS*c,
                                         fill="", stipple="gray50", outline="")
            self.canvas.create_text(self.COLS*c//2, self.ROWS*c//2 - 20,
                                    text="GAME OVER", fill="white",
                                    font=("Arial", 24, "bold"))
            self.canvas.create_text(self.COLS*c//2, self.ROWS*c//2 + 20,
                                    text=f"スコア: {self.score}", fill="#aaa",
                                    font=("Arial", 14))

        if self.paused and not self.game_over:
            self.canvas.create_text(self.COLS*c//2, self.ROWS*c//2,
                                    text="PAUSE", fill="white",
                                    font=("Arial", 24, "bold"))


if __name__ == "__main__":
    root = tk.Tk()
    app = App50(root)
    root.mainloop()
