如何在Python def语句外部调用其内部的骰子总点数更新currentspace?
问题原因
- 原有
roll函数仅将计算出的骰子总点数做了打印输出,未通过return语句返回,函数外部默认拿到的返回值是None,无法用于累加。 - 连续三次掷出双骰的分支未定义返回逻辑,该场景下函数同样无有效返回值。
解决方案
统一在函数计算完成后返回总点数,同时可通过返回值标记是否触发三次双骰的进监狱规则,修改后的完整可运行代码如下:
import random # 可自行定义监狱对应的地图位置 JAIL_POS = 10 def roll(): doubles = 0 total = 0 go_to_jail = False # 第一次掷骰 x = random.randint(1, 6) y = random.randint(1, 6) print(x, y) total += x + y if x == y: print('Doubles') doubles = 1 print(f'You have rolled {doubles} doubles!') # 第二次掷骰 x1 = random.randint(1, 6) y1 = random.randint(1, 6) print(x1, y1) total += x1 + y1 if x1 == y1: print('Doubles') doubles = 2 print(f'You have rolled {doubles} doubles!') # 第三次掷骰 x2 = random.randint(1, 6) y2 = random.randint(1, 6) print(x2, y2) if x2 == y2: doubles = 3 print(f'You rolled {doubles} doubles!') print('Go to Jail!') go_to_jail = True total = 0 # 三次双骰不累计本次移动点数 else: total += x2 + y2 print(f'You rolled {total} in total.') else: print(f'You rolled {total} in total.') else: print(f'You rolled {total} in total.') # 返回元组:(本次需累加的点数, 是否触发进监狱) return (total, go_to_jail) currentspace = 0 # 调用掷骰函数 move_step, need_jail = roll() if need_jail: currentspace = JAIL_POS else: currentspace += move_step print(f'当前所处位置:{currentspace}')
逻辑说明
- 原有零散的total计算统一合并为递增赋值,避免重复定义临时变量。
- 将
import random移到函数外部,避免每次调用掷骰函数时重复导入模块。 - 如果不需要处理三次双骰的特殊规则,仅需在原有代码的所有打印总点数的分支末尾加
return 对应总点数变量,即可在外部拿到数值做累加。
内容的提问来源于stack exchange,提问作者NoahAllan
相关产品推荐
相关产品推荐

