Python剪刀石头布游戏计分异常:需修改代码何处?
问题根源与修改方案
核心问题
- 类型不匹配导致胜负判断失效:
computer_hand通过random.randint(0,2)生成的是整数,但判断胜负时直接和字符串(如"S")比较,导致所有用户获胜的条件永远不成立,player1_score无法递增。 - else分支逻辑错误:当前else分支会在用户没赢的所有情况(包括平局)都给电脑加分,导致即使平局,
computer_score也会错误增长。
修改步骤
1. 修正电脑出拳的变量类型
将生成电脑出拳的代码从:
computer_hand = random.randint(0,2)
改为:
computer_hand = hand[random.randint(0,2)]
这样computer_hand直接存储对应的字符串("R"/"P"/"S"),和用户输入的your_hand类型一致,胜负判断条件才能正常触发。
2. 补充平局判断,修正加分逻辑
在原有的三个用户获胜条件之后,增加平局的判断,只有当电脑明确获胜时才给computer_score加分:
elif your_hand == computer_hand: print("平局!") print("Your score: ",str(player1_score) + "\n My score: ", str(computer_score))
修改后的完整代码
import random hand = ["R","P","S"] def game(): player1_score = 0 computer_score = 0 i=0 while (i<5): print("Enter R for ROCK \nEnter P for PAPER\nEnter S for SCISOR") your_hand = input(player1 + " picks: ").upper() if your_hand not in hand: continue computer_hand = hand[random.randint(0,2)] print("Computer picks: ", computer_hand) if your_hand == "R" and computer_hand == "S": player1_score += 1 print("Your score: ",str(player1_score) + "\n My score: ", str(computer_score)) elif your_hand == "P" and computer_hand == "R": player1_score += 1 print("Your score: ",str(player1_score) + "\n My score: ", str(computer_score)) elif your_hand == "S" and computer_hand == "P": player1_score += 1 print("Your score: ",str(player1_score) + "\n My score: ", str(computer_score)) elif your_hand == computer_hand: print("平局!") print("Your score: ",str(player1_score) + "\n My score: ", str(computer_score)) else: computer_score += 1 print("Your score: ",str(player1_score) + "\n My score: ", str(computer_score)) i += 1 print("Your score: ",str(player1_score) + "\n My score: ", str(computer_score)) print("\t\t\tWELCOME TO ROCK PAPER SCISORS!") print("\t\t\tRemember this: \n\t\t\t\t SCISORS KILLS PAPER \n\t\t\t\t PAPER KILLS STONE \n\t\t\t\t STONE KILLS SCISORS") player1 = input("Player 1 Enter your name: ") print("Player 2: Hello! " + player1 +". I am your COMPUTER!") print("SO SHALL WE : \n\t1. PLAY \n\t2. EXIT") start = int(input("Enter the choice: ")) if start == 1: game() else: exit()
内容的提问来源于stack exchange,提问作者Sinjini
相关产品推荐
相关产品推荐

