import tkinter as tk
from tkinter import messagebox
import random

# ---------- 成语库 ----------
IDIOMS = [
    "一帆风顺", "顺水推舟", "舟车劳顿", "顿开茅塞", "塞翁失马",
    "马到成功", "功成名就", "就事论事", "事半功倍", "背水一战",
    "战无不胜", "胜友如云", "云开见日", "日新月异", "异想天开",
    "开门见山", "山清水秀", "秀外慧中", "中庸之道", "道听途说"
]

def is_valid_idiom(word):
    return word in IDIOMS

# ---------- 核心逻辑 ----------
current_idiom = ""

def new_game():
    global current_idiom
    current_idiom = random.choice(IDIOMS)
    label_current.config(text=f"当前成语：{current_idiom}")
    entry_input.delete(0, tk.END)
    text_history.delete("1.0", tk.END)

def check_idiom():
    global current_idiom
    user_input = entry_input.get().strip()

    if len(user_input) != 4:
        messagebox.showwarning("提示", "请输入四字成语")
        return

    if not is_valid_idiom(user_input):
        messagebox.showerror("错误", "这不是合法成语")
        return

    if user_input[0] != current_idiom[-1]:
        messagebox.showerror(
            "接龙失败",
            f"应以「{current_idiom[-1]}」开头"
        )
        return

    # 成功
    text_history.insert(tk.END, f"{current_idiom} → {user_input}\n")
    current_idiom = user_input
    label_current.config(text=f"当前成语：{current_idiom}")
    entry_input.delete(0, tk.END)

# ---------- GUI 界面 ----------
root = tk.Tk()
root.title("成语接龙打字软件")
root.geometry("420x360")
root.resizable(False, False)

label_title = tk.Label(
    root,
    text="🀄 成语接龙打字练习",
    font=("微软雅黑", 16)
)
label_title.pack(pady=10)

label_current = tk.Label(
    root,
    text="点击开始游戏",
    font=("微软雅黑", 14),
    fg="blue"
)
label_current.pack(pady=5)

entry_input = tk.Entry(
    root,
    font=("微软雅黑", 14),
    justify="center"
)
entry_input.pack(pady=10)
entry_input.bind("<Return>", lambda e: check_idiom())

btn_check = tk.Button(
    root,
    text="提交成语",
    font=("微软雅黑", 12),
    command=check_idiom
)
btn_check.pack(pady=5)

btn_new = tk.Button(
    root,
    text="重新开始",
    font=("微软雅黑", 10),
    command=new_game
)
btn_new.pack(pady=5)

text_history = tk.Text(
    root,
    height=8,
    font=("微软雅黑", 10)
)
text_history.pack(padx=10, pady=10, fill=tk.BOTH)

new_game()
root.mainloop()