mardi 1 septembre 2020

Python - properly returning value for rock, paper, scissors

I am trying to write a Python script where the user can select a choice for 'r', 'p', or 's' and the script will generate the outcome of the Rock, Paper, Scissors game based on the returned value. This is what I have so far:

from random import choice
import sys

# Input name
meetname = input("Nice to meet you! What's your name? \n")
print(' \n')

# Game instructions
rpsthink = 'Well, ' + meetname + ", how about we play a game of Rock, Paper, Scissors?"
print(rpsthink)
print('\n')

#Ask user for choice of rock, paper, scissors
try:
    user_move = str(input("Enter 'r' for rock, 'p' for paper, or 's' for scissors. The system will randomly select a choice, and the result of the game will be displayed to you. You can enter 'Q' to quit the game at any time. \n"))
except ValueError:
    print("Please make sure your input is 'r', 'p', 's', or 'Q'!")
    sys.exit()

print('\n')

if user_move =='Q':
    print('Sorry to see you go - hope you had fun playing!')
    sys.exit()

# Generate a random computer choice
def computer_rps() -> str:
    #Computer will randomly select from rock, paper, scissors:
    computermove: str = choice(['r','p','s'])
    return computermove

def gameresult(user_move, computermove):
    # Return value based on comparison of user and computer moves
    # User wins
    if (user_move == 'r' and computermove == 's') or (user_move == 'p' and computermove == 'r') or (user_move == 's' and computermove =='p'):
        return 1
    # User loses
    if (user_move == 'r' and computermove == 'p') or (user_move == 's' and computermove == 'r') or (user_move == 'p' and computermove == 's'):
        return -1
    # Tie game
    if user_move == computermove:
        return 0

#Notification of game result based on returned function value
if int(gameresult(user_move, computermove)) == -1:
    print("The computer made a choice of ", computermove)
    print("Looks like the computer won this time...don't let that deter you - let's have another round for a shot at victory!")
if int(gameresult(user_move, computermove)) == 1:
    print("The computer made a choice of ", computermove)
    print('Looks like you won! Excellent choice! But how many times can you make the winning decision...?')
if int(gameresult(user_move, computermove)) == 0:
    print("The computer made a choice of ", computermove)
    print("Looks like it's a tie game - how about another round to settle the score?")

sys.exit()

However, I get an error of the name 'computermove' not being defined for the line if int(gameresult(user_move, computermove)) == -1. Do I need to set computermove as a global variable so that the comparison of user and computer moves can be properly done?




Aucun commentaire:

Enregistrer un commentaire