import tkinter as tk
import random

# 窗口基础配置
WIDTH = 620
HEIGHT = 740
cell_w, cell_h = 110, 110
cols, rows = 3, 3
margin = 15

root = tk.Tk()
root.title="刮刮乐完整模拟器"
root.geometry(f"{WIDTH}x{HEIGHT}")
root.configure(bg="#f5f0dc")

# 全局常量&全局变量
init_money = 200  # 初始余额
card_cost = 15    # 单张刮刮卡售价

# 全局资金
balance = init_money
is_bankrupt = False

# 刮刮卡数据
prize_list = [0, 0, 0, 10, 20, 50, 100, 200, 500]
lucky_num = 0
cell_data = []
scratched = [False] * 9
win_total = 0

# 画布
canvas = tk.Canvas(root, bg="#f5f0dc", width=WIDTH, height=HEIGHT)
canvas.pack()

# 顶部文字UI
tk.Label(root, text="趣味刮刮乐", font=("SimHei", 24, "bold"), fg="#dd1e1e", bg="#f5f0dc").place(x=200, y=12)
tip_label = tk.Label(root, text="幸运数字：无，请先购买刮刮卡", font=("SimHei", 15), bg="#f5f0dc")
tip_label.place(x=150, y=65)

# 资金面板
balance_label = tk.Label(root, text=f"账户余额：{balance} 元", font=("SimHei", 16, "bold"), fg="#0066cc", bg="#f5f0dc")
balance_label.place(x=25, y=HEIGHT-90)
earn_label = tk.Label(root, text=f"本次中奖：{win_total} 元", font=("SimHei", 15), fg="#199c2b", bg="#f5f0dc")
earn_label.place(x=25, y=HEIGHT-55)

# 卡片绘制起始坐标
start_x = (WIDTH - cols * cell_w - (cols - 1) * margin) // 2
start_y = 130


def refresh_all():
    global balance, is_bankrupt, lucky_num, cell_data, scratched, win_total
    canvas.delete("all")

    # 破产判定
    if balance <= 0:
        balance = 0
        is_bankrupt = True
        tip_label.config(text="破产！余额归零，点重置本金恢复")
    else:
        tip_label.config(text=f"幸运数字：{lucky_num}，刮相同数字拿奖金")

    # 更新文字
    balance_label.config(text=f"账户余额：{balance} 元")
    earn_label.config(text=f"本次中奖：{win_total} 元")

    # 没有买卡，空白卡片区域
    if len(cell_data) == 0:
        canvas.create_text(WIDTH/2, HEIGHT/2, text="暂无刮刮卡\n点击右下角购买", font=("SimHei", 20), fill="#666666")
        return

    # 绘制9格刮奖区
    for row in range(rows):
        for col in range(cols):
            index = row * cols + col
            px = start_x + col*(cell_w+margin)
            py = start_y + row*(cell_h+margin)

            if scratched[index]:
                # 已刮开
                canvas.create_rectangle(px, py, px+cell_w, py+cell_h, fill="white", outline="#444", width=2)
                num = cell_data[index]
                font_color = "#d62828" if num == lucky_num else "#222222"
                canvas.create_text(px+55, py+40, text=str(num), font=("SimHei", 32, "bold"), fill=font_color)
                canvas.create_text(px+55, py+76, text=f"{prize_list[index]}元", font=("SimHei", 12), fill="#209c35")
            else:
                # 灰色涂层
                canvas.create_rectangle(px, py, px+cell_w, py+cell_h, fill="#999999", outline="#444", width=2)
                canvas.create_text(px+55, py+52, text="按住刮开", font=("SimHei", 11))


def calc_win():
    """统计当前刮开的总奖金，仅展示，不入余额"""
    total = 0
    for i in range(9):
        if scratched[i] and cell_data[i] == lucky_num:
            total += prize_list[i]
    return total


def drag_scratch(event):
    global win_total, is_bankrupt
    # 这里移除了balance，中奖不再修改余额
    if is_bankrupt or len(cell_data) == 0:
        return
    idx = xy_to_index(event.x, event.y)
    if idx == -1:
        return
    scratched[idx] = True
    win_total = calc_win()
    refresh_all()


def xy_to_index(x, y):
    """鼠标坐标转为格子编号"""
    for r in range(rows):
        for c in range(cols):
            idx = r * cols + c
            x1 = start_x + c*(cell_w+margin)
            y1 = start_y + r*(cell_h+margin)
            x2 = x1 + cell_w
            y2 = y1 + cell_h
            if x1 <= x <= x2 and y1 <= y <= y2:
                return idx
    return -1


def buy_card():
    """花钱购买一张新刮刮卡，只有买卡扣钱，中奖不加钱"""
    global balance, lucky_num, cell_data, scratched, win_total, is_bankrupt
    if is_bankrupt:
        tip_label.config(text="已破产，无法购卡！")
        return
    if balance < card_cost:
        tip_label.config(text=f"余额不足！需要{card_cost}元，当前只有{balance}元")
        return

    # 仅买卡扣款，中奖不会增收余额
    balance -= card_cost
    win_total = 0
    scratched = [False] * 9

    # 生成新卡片号码
    lucky_num = random.choice([7, 8, 9])
    cell_data.clear()
    for _ in range(9):
        if random.random() < 0.32:
            cell_data.append(lucky_num)
        else:
            cell_data.append(random.choice([1, 2, 3, 4, 5, 6]))

    refresh_all()


def reset_balance():
    """重置本金，解除破产"""
    global balance, is_bankrupt, lucky_num, cell_data, scratched, win_total
    balance = init_money
    is_bankrupt = False
    lucky_num = 0
    cell_data = []
    scratched = [False]*9
    win_total = 0
    tip_label.config(text="幸运数字：无，请先购买刮刮卡")
    refresh_all()


# 功能按钮
buy_btn = tk.Button(root, text=f"购买刮刮卡（{card_cost}元）", font=("SimHei",12), bg="#ffc107", command=buy_card)
buy_btn.place(x=420, y=HEIGHT-92, width=160, height=36)
reset_btn = tk.Button(root, text="重置本金", font=("SimHei",11), bg="#72d869", command=reset_balance)
reset_btn.place(x=420, y=HEIGHT-54, width=160, height=36)

# 绑定鼠标拖拽刮开
canvas.bind("<B1-Motion>", drag_scratch)

# 初始化界面
refresh_all()
root.mainloop()