如何让Turtle点击事件关联random.choice的随机选择?
颜色猜谜游戏实现修正方案
核心需求
制作一款20色交互游戏:
- 程序随机选中一种颜色,输出对应提示文字
- 保留本次随机选择的结果
- 用户点击对应色块时,反馈“正确/错误”
现有代码的关键问题
- 随机结果未持久化:每次调用
random.choice(list1)()都会重新生成随机值,无法保留初始选中的目标颜色 - 回调函数参数错误:turtle的
onclick回调默认传入点击坐标,而非print;且比较时调用函数(返回None),永远无法匹配 - 无目标存储变量:缺少全局/类变量保存选中的提示函数,点击时无法校验正确性
修正后的完整代码示例
import turtle import random # 全局变量:存储选中的目标颜色对应的提示函数 target_color_func = None # 绘制方块的基础实现(若已有该函数可替换) def draw_square(t, color, size, x, y): t.penup() t.goto(x, y) t.pendown() t.fillcolor(color) t.begin_fill() for _ in range(4): t.forward(size) t.right(90) t.end_fill() # 各颜色对应的提示函数 def barbie(): print("your hint is 'Barbie'.") def rose(): print("your hint is 'Rose'.") def fuscia(): print("your hint is 'Fuscia'.") # 其余17个颜色函数(punch、blush等)请自行补充定义... # 颜色函数列表 color_funcs = [barbie, rose, fuscia, punch, blush, watermelon, flamingo, rouge, salmon, coral, peach, strawberry, rosewood, lemonade, taffy, bubblegum, balletslipper, crepe, magenta, hotpink] # 初始化随机选中的目标颜色 def init_target(): global target_color_func target_color_func = random.choice(color_funcs) target_color_func() # 输出提示 # 点击回调函数:校验点击色块是否匹配目标 def barbiec(x, y): global target_color_func if target_color_func == barbie: print("That's Right!") else: print("Try Again.") # 主程序逻辑 if __name__ == "__main__": pinky = turtle.Turtle() pinky.hideturtle() # 绘制Barbie对应的色块 draw_square(pinky,"#F699CD",30,-170,80) # 绑定Barbie色块的点击事件 barbiet = turtle.Turtle() barbiet.penup() barbiet.hideturtle() barbiet.color("white") barbiet.goto(-135,110) barbiet.showturtle() barbiet.onclick(barbiec) # 初始化目标颜色并给出提示 init_target() # 启动turtle交互循环 turtle.done()
关键改进说明
- 持久化随机结果:用全局变量
target_color_func存储选中的提示函数,仅在init_target中初始化一次,避免重复随机 - 修正回调参数:回调函数
barbiec接收turtle自动传入的x,y坐标参数,符合API规范 - 直接对比函数对象:校验时直接对比点击对应的函数(如
barbie)和target_color_func,而非函数调用结果(函数返回None无法匹配) - 模块化拆分:将初始化逻辑独立为
init_target,代码结构更清晰,便于后续扩展其他色块的交互逻辑
内容的提问来源于stack exchange,提问作者emmtm
相关产品推荐
相关产品推荐

