Python版Rock Paper Scissors Lizard Spock游戏:多次运行结果重复问题求助
问题分析与解决
核心问题1:随机动作重复
你把user_action和computer_action的生成放在了循环外面,这两个变量只会被赋值一次,循环里反复用同一个动作,自然每次结果都一样。
核心问题2:结果列表存的都是None
determine_winner函数只有print输出,没有返回任何值,所以你append到res里的都是函数默认返回的None。
修正后的代码
from enum import IntEnum import random class Action(IntEnum): Rock = 0 Paper = 1 Scissors = 2 Lizard = 3 Spock = 4 victories = { Action.Scissors: [Action.Lizard, Action.Paper], Action.Paper: [Action.Spock, Action.Rock], Action.Rock: [Action.Lizard, Action.Scissors], Action.Lizard: [Action.Spock, Action.Paper], Action.Spock: [Action.Scissors, Action.Rock] } def get_user_selection(): selection = random.randint(0, len(Action) - 1) return Action(selection) def get_computer_selection(): selection = random.randint(0, len(Action) - 1) return Action(selection) def determine_winner(user_action, computer_action): defeats = victories[user_action] if user_action == computer_action: result = f"Both players selected {user_action.name}. It's a tie!" elif computer_action in defeats: result = f"{user_action.name} beats {computer_action.name}! You win!" else: result = f"{computer_action.name} beats {user_action.name}! You lose." print(result) return result # 返回结果,方便存入列表 res = [] for n in range(5): # 每次循环都重新生成随机动作 user_action = get_user_selection() computer_action = get_computer_selection() new_result = determine_winner(user_action, computer_action) res.append(new_result) print(res)
关键修改点
- 把
user_action和computer_action的生成移到for循环内部,每次循环都会重新生成随机动作。 - 给
determine_winner函数添加return语句,返回生成的结果字符串,这样res列表里就能存实际的结果内容。 - 补充了缺失的
from enum import IntEnum和import random导入语句(原代码里没写,运行会报错)。
内容的提问来源于stack exchange,提问作者Asma Ahmed
相关产品推荐
相关产品推荐

