Python剪刀石头布程序while循环问题及代码优化咨询
问题解答
一、循环失效的原因
你在game/game2/game3函数里的while循环条件逻辑错误:
比如game函数的循环条件:
while your_score != 1 or computer_score != 1:
这个条件的意思是只要玩家分数不等于1,或者电脑分数不等于1,就继续循环。当一方分数达到1后,另一方分数还没到(比如玩家得1分,电脑0分),此时your_score !=1是False,但computer_score !=1是True,整个or条件为True,循环会继续执行,不会自动终止。
正确的终止条件应该是当任意一方达到目标分数时停止循环,所以应该把or改成and,或者用更直观的逻辑:
# 以game函数为例,目标分数是1 while your_score < 1 and computer_score < 1:
或者:
while not (your_score == 1 or computer_score == 1):
这样当任意一方达到目标分数时,循环就会终止,不需要额外的if语句来break。
另外注意:函数内的your_score和computer_score是局部变量,修改后不会影响全局变量,但这不是循环失效的原因,只是需要注意的细节。
二、代码优化方案
你的代码存在大量重复逻辑(比如三个game函数、三个start函数几乎完全一致),可以通过参数化、简化逻辑来大幅缩短代码:
优化后的完整代码
import random import time OPTIONS = ["rock", "paper", "scissors"] # 定义获胜规则:键是玩家选择,值是能击败的电脑选择 WIN_RULES = {1: 3, 2: 1, 3: 2} def show_choice(choice): """简化选择展示逻辑""" return OPTIONS[choice - 1] def is_win(user_choice, computer_choice): """简化胜负判断""" return WIN_RULES[user_choice] == computer_choice def countdown(): """提取重复的倒计时逻辑""" print("ok, lets start") for num in range(3, 0, -1): time.sleep(1) print(num) time.sleep(1) def play_game(target_score): """合并三个game函数,用target_score参数控制获胜条件""" user_score = 0 computer_score = 0 countdown() while user_score < target_score and computer_score < target_score: try: user = int(input("What do you shoot?\n1.rock\n2.paper\n3.scissors\n")) if user not in [1,2,3]: print("Invalid choice, please enter 1/2/3") continue except ValueError: print("Invalid input, please enter a number") continue computer = random.choice([1,2,3]) print(f"You: {show_choice(user)}") print(f"Computer: {show_choice(computer)}") if user == computer: print("It's a tie!\n") elif is_win(user, computer): print("You won!\n") user_score +=1 else: print("You lost!\n") computer_score +=1 if user_score == target_score: print("You won, gg!") else: print("You lost, nt!") def confirm_ready(target_score): """合并三个start函数,复用确认逻辑""" while True: s = input("Are you ready? 'yes' or 'no'\n").strip().lower() if s == "yes": play_game(target_score) break elif s == "no": print("ok, I'll wait") for num in range(3,0,-1): time.sleep(1) print(num) print("You should be ready now") time.sleep(1) play_game(target_score) break else: print("Wrong input, try again") def select_gamemode(): """简化游戏模式选择""" while True: print("1. The best of 1 (first to 1 point)") print("2. The best of 3 (first to 2 points)") print("3. The best of 5 (first to 3 points)") try: mode = int(input("Which mode do you want to play?\n")) if mode ==1: confirm_ready(1) break elif mode ==2: confirm_ready(2) break elif mode ==3: confirm_ready(3) break else: print("Invalid mode, please enter 1/2/3\n") except ValueError: print("Invalid input, please enter a number\n") # 启动程序 select_gamemode()
优化点说明
- 消除重复代码:
- 将三个
game函数合并为play_game,通过target_score参数控制获胜条件(1/2/3分) - 将三个
start函数合并为confirm_ready,复用准备确认逻辑 - 提取重复的倒计时逻辑为
countdown函数
- 将三个
- 简化逻辑:
- 用字典
WIN_RULES替代冗长的or判断,让胜负规则更清晰 - 简化
show函数为show_choice,直接通过索引获取选项文本 - 增加输入合法性校验,避免用户输入非数字或无效选项导致崩溃
- 用字典
- 修复逻辑错误:
- 修正了
start函数中while s == "yes" or "no"的错误(该条件永远为True,因为"no"是布尔真值),改为while True循环直到输入合法 - 修正了循环终止条件,去掉了多余的
break语句
- 修正了
内容的提问来源于stack exchange,提问作者Laki
相关产品推荐
相关产品推荐

