Simplify Python code (Rock, Paper, Scissors)

爷,独闯天下 提交于 2021-01-29 06:15:42

问题


I am a complete python newbie and this is my first question on stackoverflow, so please be patient with me :)

So to get some excersise, I tried programming my own rock, paper, scissors game in Python. However, my code is relatively long compared to other rock, paper, scissor programs. This is because I programmed every single possible option in the game. Is there a possibility to simplify this code? As in not having to programm every single possibiliy in the game? Because doing so might be possible in Rock, Paper, Scissors, but probably not in more advanced problems.

Let me know what you think, thank you!!!

All the best, Luca Weissbeck

The code:

#Rock, Paper, Scissors
while True:
    Game_list = ["Rock", "Paper", "Scissors"]
        User_1 = str(input("Rock, Paper, Scissors?"))
    #Let the computer make its choice
        import random
        Computer_1 = random.choice(Game_list)
    #Possibility of a draw
        if str(Computer_1) == User_1:
            Draw_choice = str(input("It's a draw. Do you want to replay?(Y/N)"))
            if Draw_choice == "Y":
                continue
            else:
                break
    #Possibility of player winning
        if str(Computer_1) == "Rock" and User_1 == "Paper" or str(Computer_1) == 
    "Paper" and User_1 == "Scissors" or str(Computer_1) == "Scissors" and User_1 
    == "Rock":
            UW1 = str(input("You won. The computer chose:" + Computer_1 + " Do 
    you want to play again? (Y/N)"))
            if UW1 == "Y":
                continue
            else:
            break
    #Possibility of computer winning
        if str(Computer_1) == "Rock" and User_1 == "Scissors" or str(Computer_1) 
    == "Paper" and User_1 == "Rock" or str(Computer_1) == "Scissors" and User_1 
    == "Paper":
            UL1 = str(input("You lost. The Compuer chose:" + Computer_1 + " Do 
    you want to play again? (Y/N)"))
            if UL1 == "Y":
                continue
            else:
                break
    #End sentence                  
    print("Bye, thank you for playing!")

回答1:


There are a lot of repeated strings in this program. They can be collapsed.

import random
States = ['Rock','Paper','Scissors']
playAgain = True
while playAgain:
    User = str(input("Choose your play: "))
    try:
        User = States.index(User)
    except: 
        print('Your choice is not one of the choices in Rock, Paper, Scissors')
        break
    Comp = random.randint(0,2)
    winner = (Comp-User)%3
    if winner==0:
        print("There is a tie. Both User and Computer chose " + States[User])
    elif winner==1:
        print("Computer wins. Computer chose "+States[Comp]+" and User chose "+States[User])
    else:
        print("User wins. Computer chose "+States[Comp]+" and User chose "+States[User])
    if str(input("Do you want to play again? (Y/N)")) == "N":
        playAgain = False
print("Thanks for playing!")



回答2:


You can try to store the win possibilities.

win_case = [['rock','scissor'], ['scissor','paper'], ['paper','rock']]

Then the main program will be like

if (user == comp):
     // draw
elif ([user,comp] in win_case):
     // user win
else:
     // comp win



回答3:


Length of code is one thing. Organization and readability is another (more important) one. What often helps is a separation of code and config. Set constants, settings, messages first, then use them in the code:

import random

# game config
R, P, S = "Rock", "Paper", "Scissors"
BEATS = {R: S, P: R, S: P}
MESSAGES = {
    "draw": "It's a draw. Play again? (Y/N)\n",
    "win": "You won. Comp chose: {}. Play again? (Y/N)\n",
    "loss": "You lost. Comp chose: {}. Play again? (Y/N)\n",
    "invalid": "Invalid input: {}. Play again? (Y/N)\n",
}

# game code
play = "Y"
while play.upper() == "Y":
    u1 = str(input("{}, {}, {}?\n".format(R, P, S)))
    c1 = random.choice([R, P, S])

    if u1 not in BEATS:
        play = input(MESSAGES["invalid"].format(u1))
    elif c1 == u1:
        play = input(MESSAGES["draw"])
    elif BEATS[u1] == c1:
        play = input(MESSAGES["win"].format(c1))               
    else:
        play = input(MESSAGES["loss"].format(c1))


来源:https://stackoverflow.com/questions/51467707/simplify-python-code-rock-paper-scissors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!