示例输出:
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:
✅使用词典以清洁和正确的获胜条件。
✅使用Random.Choice(),以提高可读性和效率。
现在您的游戏将始终如一地产生正确的结果! 🚀