有没有办法使这款剪刀石头布更具代码效率? (以更好的方式减少行数)

时间:2019-04-25 11:38:58

标签: python python-3.x

如何使游戏更好,更代码有效?我是python的新手,因此该游戏可以运行,但是我敢肯定,有一种更简单的方法可以完成我的工作

import random
Answers = [
    "rock",
    "paper",
    "scissors",
]
Answer = input("rock / paper / scissors ?\n")
RandomNum = random.choice(Answers)
print(RandomNum)
while Answer == RandomNum:
    print("Tie, try again")
    Answer = input("rock / paper / scissors ?\n")
    RandomNum = random.choice(Answers)
    print(RandomNum)
if (int(len(Answer)) - int(len(RandomNum))) == -4: #if User input is Rock - Scissors = -4
    print("You have won")
else:
    if (int(len(Answer)) - int(len(RandomNum))) == 4:  # if User input is Scissors - Rock = 4
        print("You have lost")
    else:
        if (int(len(Answer)) - int(len(RandomNum))) == -3:  # if User input is Paper - Scissors = -3
            print("You have lost")
        else:
            if (int(len(Answer)) - int(len(RandomNum))) == 3:  # if user input is Scissors - Paper = 3
                print("You have won")
            else:
                if int(len(Answer)) > int(len(RandomNum)):  # answers except scissors and paper
                    print("You have won")
                else:
                    print("You have lost")

它工作正常,但是如果用户输入无效答案,它将认为它是实际答案,所以我真的不知道如何解决该问题,并使代码更好

1 个答案:

答案 0 :(得分:1)

一种非常简单的方法是维护一个词典,其中包括谁打败谁的样子。 {'rock':'scissors','scissors':'paper','paper':'rock'}就像岩石击败剪刀一样,剪刀击败纸张,而纸张击败了岩石。

然后我们可以按以下方式编写方法。

import random

#dictionary of who beats whom
beats = {'rock':'scissors','scissors':'paper','paper':'rock'}

#All possible answers
answers = list(beats.keys())

#Take answer from user and chose comp answer at random
user_answer = input("rock / paper / scissors ?\n")
comp_answer = random.choice(answers)

print('I chose', comp_answer)

#Check if user input is valid
if user_answer not in beats.keys():
    print('Invalid input')

#If both comp and user choose same, they tie
elif user_answer == comp_answer:
    print('Tied, Try again')

#If user answer was in key, and comp_answer was in value, user wins
elif beats[user_answer] == comp_answer:
    print('You have won')

#Otherwise comp wins
else:
    print('You have lost')