如何实现石头剪刀布游戏三轮对局?解决循环重复结果问题
解决石头剪刀布游戏三轮对局的问题
你的代码核心问题是循环逻辑位置错误:你把获取用户选择和电脑随机选择的代码放在了for循环外面,这意味着这两个值只会被初始化一次,三轮循环都重复使用同一组选择,所以每次输出结果完全相同。
要实现真正的三轮独立对局,需要把get_user_input()和random_choice()的调用放到for循环内部,让每一轮都重新获取用户输入、生成电脑的新随机选择。
修改后的完整代码
import random OPTIONS = ["Rock", "Paper", "Scissors"] def get_user_input(): user_choice = input("Select your play (Rock, Paper or Scissors): ") return user_choice def random_choice(): computer_choice = random.choice(OPTIONS) return computer_choice def game(user_choice, computer_choice): if user_choice == computer_choice: print(f"You selected: {user_choice}.\nComputer selected: {computer_choice}.\nDraw.") else: if computer_choice == "Rock" and user_choice == "Paper": print(f"You selected: {user_choice}.\nComputer selected: {computer_choice}.\nYou won!") if computer_choice == "Rock" and user_choice == "Scissors": print(f"You selected: {user_choice}.\nComputer selected: {computer_choice}.\nYou lost...") if computer_choice == "Paper" and user_choice == "Scissors": print(f"You selected: {user_choice}.\nComputer selected: {computer_choice}.\nYou won!") if computer_choice == "Paper" and user_choice == "Rock": print(f"You selected: {user_choice}.\nComputer selected: {computer_choice}.\nYou lost...") if computer_choice == "Scissors" and user_choice == "Rock": print(f"You selected: {user_choice}.\nComputer selected: {computer_choice}.\nYou won!") if computer_choice == "Scissors" and user_choice == "Paper": print(f"You selected: {user_choice}.\nComputer selected: {computer_choice}.\nYou lost...") def main(): # 将输入和随机选择放入循环,每轮重新生成 for round_num in range(3): print(f"\n--- 第{round_num+1}轮对局 ---") user_choice = get_user_input() computer_choice = random_choice() game(user_choice, computer_choice) print("\n三轮游戏全部结束!") main()
额外优化建议
- 增加输入校验:判断用户输入是否在
OPTIONS列表内,避免无效输入导致逻辑异常 - 简化胜负判断逻辑:用字典替代大量重复的
if语句,让代码更简洁,比如:
# 定义玩家获胜的对应关系:键是玩家选择,值是能击败的电脑选择 WIN_RULES = { "Rock": "Scissors", "Paper": "Rock", "Scissors": "Paper" } def game(user_choice, computer_choice): print(f"You selected: {user_choice}.\nComputer selected: {computer_choice}.") if user_choice == computer_choice: print("Draw.") elif WIN_RULES[user_choice] == computer_choice: print("You won!") else: print("You lost...")
内容的提问来源于stack exchange,提问作者Adrià Martínez
相关产品推荐
相关产品推荐

