Rock Paper Scissors 游戏代码优化

52 阅读2分钟
  • 用户在运行 Rock Paper Scissors 游戏时遇到了一些问题,包括:
    • 程序似乎不接受输入的整数。
    • 不将结果添加到胜负平局计数中。
    • 在调试模式下不显示计算机的选择。
  1. 解决方案

    • 将用户输入的字符串转换为整数。
    • 在适当的地方更新胜负平局计数。
    • 在调试模式下显示计算机的选择。
import random

def main():

    continuing = "y"

    win = 0
    lose = 0
    draw = 0

    while continuing == "y":
        print("Score:", win,"wins,", draw, "draws,", lose,"losses")
        print("(D)ebug to show computer's choice")
        print("(N)ew game")
        print("(Q)uit")

        choice = input(" ")

        if choice == "n" or choice == "N":
            win, draw, lose = playgame(win, draw, lose)

        elif choice == "d" or choice == "D":
            win, draw, lose = playgame2(win, draw, lose)

        elif choice == "q" or choice == "Q":
            break


def playgame(win, draw, lose):

    computer = random.randint(1,3)
    player = int(input("Enter 1 for Rock, 2 for Paper, or 3 for Scissors: "))

    if computer == 1 and player == 2:
        Score = "You won"
        win += 1

    elif computer == 1 and player == 3:
        Score = "You lost"
        lose += 1

    elif computer == 2 and player == 1:
        Score = "You lost"
        lose += 1

    elif computer == 2 and player == 3:
        Score = "You won"
        win += 1

    elif computer == 3 and player == 1:
        Score = "You won"
        win += 1

    elif computer == 3 and player == 2:
        Score = "You lost"
        lose += 1

    elif computer == player:
        Score = "Draw"
        draw += 1

    print(Score)
    return (win, draw, lose)

def playgame2(win, draw, lose):

    computer = random.randint(1, 3)
    player = int(input("Enter 1 for Rock, 2 for Paper, or 3 for Scissors: "))

    if computer == 1 and player == 2:
        Score = "You won"
        print("Computer chose rock")
        win += 1

    elif computer == 1 and player == 3:
        Score = "You lost"
        print("Computer chose rock")
        lose += 1

    elif computer == 2 and player == 1:
        Score = "You lost"
        print("Computer chose paper")
        lose += 1

    elif computer == 2 and player == 3:
        Score = "You won"
        print("Computer chose paper")
        win += 1

    elif computer == 3 and player == 1:
        Score = "You won"
        print("Computer chose scissors")
        win += 1

    elif computer == 3 and player == 2:
        Score = "You lost"
        print("Computer chose scissors")
        lose += 1

    elif computer == player:
        Score = "Draw"
        print("Computer chose the same as you")
        draw += 1

    print(Score)
    return (win, draw, lose)


main()    

在优化的代码中:

  • 使用了 int() 函数将用户输入的字符串转换为整数,解决了整数输入问题。

  • 在每个结果分支中使用 print() 函数显示结果,这样即使不处于调试模式,用户也可以看到结果。

  • 在 playgame() 和 playgame2() 函数中添加了参数 win、draw 和 lose,以便在函数中更新这些计数器。