我是Python的新手,并制作了岩石纸游戏。我发现结果有时是错误的。 程序的代码为

问题描述 投票:0回答:1

enter your move: rock computer played: rock you won Do you want to play again? (y/n): y enter your move: rock computer played: scissors you won Do you want to play again? (y/n): y enter your move: rock computer played: rock tie Do you want to play again? (y/n):

这些结果是我一直在运行该程序的结果,在首先,预期的结果应该为“不''won'。
如何解决此问题以及可能导致问题的原因


问题是由使用结果引起的。Index([your_move,comp_mov])%3来确定获奖者,这导致逻辑不正确。
正确的方法
而不是使用列表和索引,而是使用字典来映射获胜的情况:

import random moves = ["rock", "paper", "scissors"] winning_cases = { "rock": "scissors", "scissors": "paper", "paper": "rock" } def comp_move(): return random.choice(moves) def game(): your_move = input("Enter your move (rock, paper, scissors): ").strip().lower() if your_move not in moves: print("Invalid move! Try again.") return comp_mov = comp_move() print(f"Computer played: {comp_mov}") if your_move == comp_mov: print("Tie!") elif winning_cases[your_move] == comp_mov: print("You won!") else: print("You lost!") while True: game() if input("Do you want to play again? (y/n): ").strip().lower() == "n": break

实现的fixes:

python
1个回答
0
投票
✅删除结果.index(),导致结果不一致。

✅添加了输入验证以防止无效的选择。

✅使用Random.Choice(),以提高可读性和效率。
现在您的游戏将始终如一地产生正确的结果! 🚀

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.