Python骰子游戏:条件满足后如何立即终止while循环?
问题分析与解决方案
核心问题
原循环逻辑无法实现“任一玩家得分≥100时立即终止游戏”的需求:
- 初始用
or作为循环条件:while int(player1Score) <100 or int(player2Score)<100,逻辑是只要有一个玩家分数不足100,游戏就继续。这会导致即使A玩家已经达标,只要B玩家没到,游戏仍会继续,不符合预期。 - 改成
and后:while int(player1Score) <100 and int(player2Score)<100,逻辑变为两个玩家都不足100才继续,但当前代码会强制执行完player1()和player2()才检查条件,导致A玩家达标后,B玩家仍会被强制玩一轮,无法立即终止。
修正代码
修改循环结构,在每个玩家回合结束后立即检查分数,一旦达标就终止循环:
# 初始化玩家分数(假设初始值为0) player1Score = 0 player2Score = 0 while True: player1() # 玩家1回合结束后立即检查 if int(player1Score) >= 100: print("\nPlayer 1 wins! Game over.") break player2() # 玩家2回合结束后立即检查 if int(player2Score) >= 100: print("\nPlayer 2 wins! Game over.") break
额外优化建议
- 避免全局变量:当前代码依赖
player1Score、dice1、dice2等全局变量,可改为让函数返回值传递数据,比如player1()返回更新后的分数,diceThrow()返回两个骰子的数值:
调用时只需更新分数:def diceThrow(): import random d1 = random.randint(1,6) d2 = random.randint(1,6) return d1, d2 def player1(current_score): rTotal = 0 print("\nPlayer 1 turn!") while True: dice1, dice2 = diceThrow() print(f"Dice 1: {dice1} \nDice 2: {dice2}") if dice1 == 1 and dice2 == 1: current_score = 0 rTotal = 0 print("DOUBLE ONE! Banked total reset, Player 2's turn.") break elif dice1 ==1 or dice2 ==1: rTotal =0 print("Rolled a single one. Player 2's turn!") break else: choice = input("Gamble (G) or Bank (B): ").upper() if choice == 'G': rTotal += dice1 + dice2 elif choice == 'B': rTotal += dice1 + dice2 current_score += rTotal print(f"\nPlayer 1 banked! Total: {current_score}") break print("Turn over") return current_scoreplayer1Score = player1(player1Score) - 替换
while 1==1为while True,更符合Python语法规范。
内容的提问来源于stack exchange,提问作者Manpreet Singh
相关产品推荐
相关产品推荐

