实践:使用 Python 开发一款迷你游戏
点击上方蓝字 ● 关注Linux公社
什么是颜色游戏 Color Game?
Tkinter 和 random 模块
linuxmi@linuxmi /home/linuxmi/www.linuxmi.com ⚡ sudo apt install python3-tk
如何使用 Python 构建颜色游戏
colours名称存储为字符串列表,并将 score 变量初始化为 0,将 time_remaining 初始化为 60。from tkinter import *import random
colours = ['Red', 'Green', 'Blue', 'Black', 'Pink', 'White', 'Purple', 'Yellow', 'Brown']score = 0time_remaining = 60beginGame() 的函数,它将事件作为输入参数。该函数执行两个任务。首先,它检查 time_remaining 是否等于60。如果是,它调用并执行 countdown() 函数。其次,它调用 nextColour() 函数,在游戏进行时随机洗牌并显示颜色和分数。def beginGame(event): if time_remaining == 60: countdown() nextColour()nextColour() 的函数并全局引用变量。如果剩余时间大于 0,则在代码后半部分定义的条目标签(存储在变量 e 中)上使用focus_set() 方法将焦点设置在输入字段上。def nextColour(): global score global time_remaining
if time_remaining > 0: e.focus_set() if e.get().lower() == colours[1].lower(): score += 1 e.delete(0, END) random.shuffle(colours) label.config(fg=str(colours[1]), text=str(colours[0])) scoreLabel.config(text="分数: " + str(score))countdown() 的函数,它引用剩余时间变量并将其减一。使用 timeLabel 的 config() 函数显示屏幕剩余时间,使用 after() 函数在延迟 1000 毫秒或一秒后回调倒计时函数。def countdown(): global time_remaining if time_remaining > 0: time_remaining -= 1 timeLabel.config(text="剩余时间: " + str(time_remaining)) timeLabel.after(1000, countdown)root = Tk()root.title("颜色游戏 - Linux迷 www.linuxmi.com")root.geometry("800x600")root.configure(background='Orange')instructions = Label(root, text="www.linuxmi.com 提醒你:键入单词的颜色而不是文本。;)", font=('Arial', 24), bg="orange")instructions.pack()scoreLabel = Label(root, text="按 Enter 键开始", font=('Arial', 24), bg="orange")scoreLabel.pack()root.mainloop()使用 Python 输出颜色游戏
使用 Python 开发游戏
如果需要完整代码,请扫描上方二维码关注 Linux迷 公众号。后台回复 pyg
链接:https://www.linuxmi.com/python-color-game.html
关注我们 长按或扫描下面二维码关注 Linux公社
关注 Linux公社,添加“ 星标 ”
每天 获取 技术干货,让我们一起成长
合作联系:root@linuxidc.net