简体   繁体   中英

How do I make my basic Rock/Paper/Scissors game with fewer lines of code?

I built this simple rock/paper/scissor game by watching some tutorials. Everything is working fine. The issue is that I want to implement something where if the user and the computer choose the same word, then it should say something like "draw."

I could go ahead and add a bunch of "if" and "else" statements, but I don't want that. Can you guys think of any other way to implement that with fewer lines of code?

#Simple rock, paper and scissor game
import random

user_wins = 0
computer_wins = 0
options = ["rock", "paper", "scissors"]

while True:
    user_pick = input("Please choose Rock/Paper/Scissors Or Press Q to quit: ")
    if user_pick.lower() == "q":
        print("You quit.")
        break
    elif user_pick not in options:
        print("Please enter a valid input.")
        continue
    random_number = random.randint(0, 2)
    computer_pick = options[random_number]
    print("The computer picked", computer_pick)
    if computer_pick == "rock" and user_pick == "scissors":
        print("You lost!")
        computer_wins += 1
    
    elif computer_pick == "paper" and user_pick == "rock":
        print("You lost!")
        computer_wins += 1

    elif computer_pick == "scissors" and user_pick == "paper":
        print("You lost!") 
        computer_wins += 1

    else:
        print('You win!')
        user_wins += 1

You could use a dictionary to map which choices beat each other. This will enable to you make the conditional part of the code, which determines who wins, more concise. It is also more easily expanded to rock-paper-scissors variants with more options, without the need for many more conditional statements.

#Simple rock, paper and scissor game
import random

user_wins = 0
computer_wins = 0
options = ["rock", "paper", "scissors"]
beaten_by = {
    "rock": "scissors",
    "scissors": "paper",
    "paper": "rock"
}

while True:
    user_pick = input("Please choose Rock/Paper/Scissors Or Press Q to quit: ")
    if user_pick.lower() == "q":
        print("You quit.")
        break
    elif user_pick not in options:
        print("Please enter a valid input.")
        continue
    random_number = random.randint(0, 2)
    computer_pick = options[random_number]
    print("The computer picked", computer_pick)
    
    if user_pick == computer_pick:
        print("Draw!")
    elif user_pick == beaten_by[computer_pick]:
        print("You lost!")
        computer_wins += 1
    else:
        print("You win!")
        user_wins += 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM