如何测试Python骰子游戏的平局决胜逻辑并避免无限循环?
嘿,别担心!作为Python新手遇到这种逻辑问题太正常了,咱们来一步步解决你的平局决胜难题~
首先得说说你原代码里的问题:你在每一轮结束后就检查平局,然后递归调用DiceGame()——这相当于直接重启了整个游戏,之前的得分全清零了,而且递归加Count -=1很容易触发无限循环,完全不是咱们想要的“决胜”效果。
咱们的目标是:先完成完整的5轮游戏,要是平局就只加一次决胜轮,然后必须分出胜负。下面是修改后的完整代码,我还加了一些优化:
import random def Rolls(): Roll1 = random.randint(1,6) Roll2 = random.randint(1,6) print ("You got a", Roll1) print ("You got a", Roll2) Score1 = Roll1 + Roll2 # 用取余判断奇偶,比列举所有数字简洁多啦 if Score1 % 2 == 0: print ("Your total is even so you get an extra 10 pts.") Score2 = Score1 + 10 print ("Your score for this round is", Score2) else: print ("Your total is odd so you lose 5 pts.") Score2 = Score1 - 5 if Score2 <= 0: print ("Your score has gone below 0pts. It will therefore be reset to 0pts") Score2 = 0 print ("Your score for this round is", Score2) return Score2 def DiceGame(): player1_score = 0 player2_score = 0 # 用for循环控制5轮游戏,比while更直观 for round_num in range(1, 6): print(f"\n It is Round {round_num} \n") # 玩家1回合 print ("It is Player 1's turn.") input("Press [Enter] to roll.") score = Rolls() player1_score += score print ("Player 1, your score so far is", player1_score) # 玩家2回合 print ("It is Player 2's turn.") input("Press [Enter] to roll.") score = Rolls() player2_score += score print ("Player 2, your score so far is", player2_score) # 5轮结束后检查是否平局 if player1_score == player2_score: print ("\nIt is a tie after 5 rounds!") print ("Starting a single tiebreaker round...") print ("\n --- Tiebreaker Round --- \n") # 决胜轮:玩家1掷骰子 print ("Player 1's turn for tiebreaker.") input("Press [Enter] to roll.") tie_score1 = Rolls() player1_score += tie_score1 print ("Player 1's total score after tiebreaker:", player1_score) # 玩家2掷骰子 print ("Player 2's turn for tiebreaker.") input("Press [Enter] to roll.") tie_score2 = Rolls() player2_score += tie_score2 print ("Player 2's total score after tiebreaker:", player2_score) # 最终判定胜负 if player1_score > player2_score: print ("\nPlayer 1 wins!") elif player2_score > player1_score: print ("\nPlayer 2 wins!") else: # 万一决胜轮还是平局,咱们随机选个胜者,保证能分出结果 print ("\nStill a tie after tiebreaker! Randomly selecting winner...") print ("Player 1 wins!" if random.randint(0,1) == 0 else "Player 2 wins!") DiceGame()
核心修改点说明:
- 移除递归,改用顺序流程:先跑完5轮完整游戏,再处理平局,不会重置之前的得分。
- 单独的决胜轮逻辑:只执行一次决胜回合,把得分加到总得分里,彻底避免无限循环。
- 平局兜底方案:如果决胜轮还是平,用随机数选胜者,确保一定能分出胜负,符合你的需求。
- 代码优化:把奇偶判断改成
Score1 % 2 == 0,比列举所有偶数更简洁;变量名改成Python规范的小写加下划线,可读性更好。
要是你还有其他疑问,随时问哦~
内容的提问来源于stack exchange,提问作者Shirotama
相关产品推荐
相关产品推荐

