Tkinter开发掷硬币游戏如何实现不同函数间的跳转调用
实现方案
你编写的随机数判断跳转函数逻辑本身是正确的,只需要补充2处缺失逻辑、修正1个显示bug即可实现需求:
- 在
coinFlip()函数末尾添加upordown()调用,确保执行完对应spinner模块后自动计算总得分并更新界面显示 - 若需要支持多次点击「Flip」按钮正常游玩,可在
coinFlip()开头重置初始资金为100,避免多次操作的资金数据累计 - 修正
upordown()函数的文本错误:原代码资金低于初始值时仍显示“赢了”,需调整为对应输钱提示
完整修正代码
from tkinter import * # 引入tkinter库 import random # 引入随机数生成库 money = 100 # 抛硬币模块 def coinFlip(): global money money = 100 # 每次点击重置初始资金,不需要累计游玩可删除该行 flip = random.randint(1, 2) if flip == 1: headspinner() else: tailspinner() upordown() # 执行完成后计算并显示得分 # 正面转盘模块 def headspinner(): global money head = random.randint(1, 2) if head == 1: money = money + 30 else: money = money - 25 # 反面转盘模块 def tailspinner(): global money tail = random.randint(1, 4) if tail == 1: money = money + 2 elif tail == 2: money = money + 5 elif tail == 3: money = money + 10 else: money = money + 15 # 盈亏计算模块 def upordown(): global money diff = money - 100 if diff > 0: screen.itemconfig(message, text = f"恭喜,你赢了${diff:.2f}", font = ("Calibri", "18")) elif diff < 0: screen.itemconfig(message, text = f"很遗憾,你输了${abs(diff):.2f}", font = ("Calibri", "18")) else: screen.itemconfig(message, text = "平局,你没有输也没有赢", font = ("Calibri", "18")) # 初始化窗口 root = Tk() # 创建画布 screen = Canvas(root, height = 600, width = 800, bg = "lightgreen") screen.pack() # 抛硬币按钮 go = Button(root, text = "Flip", cursor = "hand2", command = coinFlip) goButton = screen.create_window(400, 530, window = go) # 标题 title = screen.create_text(400, 100, text = "Welcome to Flip and Spin", font = ("Calibri", "35")) # 说明文本 text1 = Label(root, text = "欢迎来到Flip and Spin游戏!\n游戏将先抛硬币再转转盘决定你的盈亏\n初始资金为100美元,快来试试你的手气吧!", font = ("Calibri", "20"), justify = CENTER, bg = "light green") text1label = screen.create_window(400, 300, window = text1,) # 结果显示文本 message = screen.create_text(400, 400, text = "Results", font = ("Calibri", "18")) mainloop()
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

