如何让函数每次调用后更新分数变量?Python骰子游戏问题
解决骰子游戏分数累计问题(五局三胜)
问题根源
- 初始代码中,
p1_value和p2_value定义在score()函数内部,每次调用函数都会重新初始化为0,完全无法累计分数。 - 拆分后的尝试代码存在两处关键错误:
- 未使用
global声明就试图修改全局作用域的p1_value和p2_value,导致未解析引用错误; - 判断逻辑完全无效:
if f"Player 1 wins this round!"永远为真(非空字符串在布尔判断中默认是True),根本没有用到score2()的实际返回结果。
- 未使用
解决方案一:使用全局变量
将分数变量定义在全局作用域,在函数内用global声明要修改的全局变量,确保每次调用函数都能更新累计分数。
完整代码示例:
import random import time def die_roll(): return random.randrange(2, 12) # 全局分数变量,初始化为0 p1_value = 0 p2_value = 0 def play_round(): global p1_value, p2_value # 声明要修改全局变量 p1_roll = die_roll() p2_roll = die_roll() print(f"P1 you rolled a {p1_roll}") print(f"P2 you rolled a {p2_roll}") if p1_roll > p2_roll: p1_value += 1 print(f"Player 1 wins this round! P1 score: {p1_value}, P2 score: {p2_value}") elif p1_roll < p2_roll: p2_value += 1 print(f"Player 2 wins this round! P1 score: {p1_value}, P2 score: {p2_value}") else: print("Round is a tie, no points!") # 检查是否有人达到3分,决出胜负 if p1_value == 3: print("\nPlayer 1 wins the game!") return True # 返回True表示游戏结束 elif p2_value == 3: print("\nPlayer 2 wins the game!") return True return False # 返回False表示继续游戏 # 主循环,直到有人获胜 while True: if play_round(): break time.sleep(1) # 延迟1秒,让输出更清晰
解决方案二:使用类封装(更优雅的方式)
对于需要维护状态(如分数)的场景,用类封装数据和逻辑更符合Python面向对象思想,也能避免全局变量的潜在问题。
完整代码示例:
import random import time class DiceGame: def __init__(self): self.p1_score = 0 self.p2_score = 0 def die_roll(self): return random.randrange(2, 12) def play_round(self): p1_roll = self.die_roll() p2_roll = self.die_roll() print(f"P1 you rolled a {p1_roll}") print(f"P2 you rolled a {p2_roll}") if p1_roll > p2_roll: self.p1_score += 1 print(f"Player 1 wins this round! P1 score: {self.p1_score}, P2 score: {self.p2_score}") elif p1_roll < p2_roll: self.p2_score += 1 print(f"Player 2 wins this round! P1 score: {self.p1_score}, P2 score: {self.p2_score}") else: print("Round is a tie, no points!") # 判断游戏是否结束 if self.p1_score == 3: print("\nPlayer 1 wins the game!") return True elif self.p2_score == 3: print("\nPlayer 2 wins the game!") return True return False # 启动游戏 game = DiceGame() while True: if game.play_round(): break time.sleep(1)
关键补充说明
- 全局变量方案适合新手快速理解,但在复杂程序中容易引发状态混乱,仅推荐小项目使用;
- 类封装方案更易于扩展,比如后续添加更多玩家、修改获胜规则时,代码维护成本更低;
- 你尝试的拆分逻辑中,正确的判断方式应该是接收
score2()的返回值,而非直接判断字符串字面量,示例如下:
但这种拆分方式不如整合到单一函数或类中清晰。result = score2() if result == "Player 1 wins this round!": p1_value += 1
内容的提问来源于stack exchange,提问作者Mgworbz
相关产品推荐
相关产品推荐

