How to use a function for a computer's choice [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am at the final steps of creating a rock, paper, scissors game for class. In our brief we must include a function for the computer's choice.
I created the function but some errors have come up where it says that 'choices' has been undefined. I am new to using functions so I am not entirely sure why these errors have come up as I thought I already defined choices.
This is the piece of code which has the error:
def aiChoice():
choices = ['r', 'p', 's']
com_choice = random.choice(choices)
# the possible choices
return choices
return com_choice
for i in range(games):
print(f"Match {i+1}, trust your instinct")
while True:
user_play = input("Select r, p, or s: ")
# asks user to play rock, paper or scissors
if user_play in choices: **error here that says undefined name 'choices'**
# checks user input
break
# if valid, breaks the loop
print("Please enter only r, p, or s")
# otherwise asks again
com_choice = random.choice(choices) **same error here for 'choices'**
# assigns the computer choice
print(com_choice)
# prints a random item from the list as the computer's choice
if user_play == com_choice:
print('Draw!')
draw = draw + 1
# if the user plays the same move as the computer, one point goes to draw

You need choices outside of the aiChoice() function.
See:
import random
win = 0
loss = 0
draw = 0
# the possible choices
choices = ['r', 'p', 's']
def aiChoice():
com_choice = random.choice(choices)
return com_choice
while True:
name = input("Enter your name: ")
# asks user for name
if name.isalpha():
break
else:
print("Please enter characters A-Z only")
# makes sure user only enters letters
# taken from Stack Overflow
# asks user how many games they want to play
while True:
games = int(input(name + ', enter in number of plays between 1 and 7: '))
if games <= 7:
break
else:
print('1 to 7 only.')
# makes sure user input doesn't exceed seven plays
for i in range(games):
print(f"Match {i+1}, trust your instinct")
while True:
user_play = input("Select r, p, or s: ")
# asks user to play rock, paper or scissors
if user_play in choices:
# checks user input
break
# if valid, breaks the loop
print("Please enter only r, p, or s")
# otherwise asks again
com_choice = random.choice(choices)
# assigns the computer choice
print(com_choice)
# prints a random item from the list as the computer's choice
if user_play == com_choice:
print('Draw!')
draw = draw + 1
# if the user plays the same move as the computer, one point goes to draw
elif user_play == 'r' and com_choice == 'p':
print('Paper beats rock.')
print('AI wins!')
loss = loss + 1
# if the user plays rock and computer plays paper, says that the computer won and puts a point in the loss category
elif user_play == 'r' and com_choice == 's':
print('Rock beats scissors.')
print(name + ' wins!')
win = win + 1
# if the user plays rock and computer plays scissors, says that the person won and puts a point in the win category
elif user_play == 'p' and com_choice == 'r':
print('Paper beats rock.')
print(name + ' wins!')
win = win + 1
# if the user plays paper and computer plays rock, says that the person won and puts a point in the win category
elif user_play == 'p' and com_choice == 's':
print('Scissors beats paper.')
print('AI wins!')
loss = loss + 1
# if the user playspaper and scissors plays paper, says that the computer won and puts a point in the loss category
elif user_play == 's' and com_choice == 'r':
print('Rock beats scissors.')
print('AI wins!')
loss = loss + 1
# if the user plays scissors and computer plays rock, says that the computer won and puts a point in the loss category
elif user_play == 's' and com_choice == 'p':
print('Scissors beats paper.')
print(name + ' wins!')
win = win + 1
# if the user plays scissors and computer plays paper, says that the person won and puts a point in the win category
print(name + "'s final score:")
print('Wins: ' + str(win))
print('Loss: ' + str(loss))
print('Draws: ' + str(draw))
# prints the final score after all games are finished.
At the moment you're also not calling the aiChoice() function.
Do this instead:
import random
win = 0
loss = 0
draw = 0
# the possible choices
choices = ['r', 'p', 's']
def aiChoice():
com_choice = random.choice(choices)
return com_choice
while True:
name = input("Enter your name: ")
# asks user for name
if name.isalpha():
break
else:
print("Please enter characters A-Z only")
# makes sure user only enters letters
# taken from Stack Overflow
# asks user how many games they want to play
while True:
games = int(input(name + ', enter in number of plays between 1 and 7: '))
if games <= 7:
break
else:
print('1 to 7 only.')
# makes sure user input doesn't exceed seven plays
for i in range(games):
print(f"Match {i+1}, trust your instinct")
while True:
user_play = input("Select r, p, or s: ")
# asks user to play rock, paper or scissors
if user_play in choices:
# checks user input
break
# if valid, breaks the loop
print("Please enter only r, p, or s")
# otherwise asks again
com_choice = aiChoice()
# assigns the computer choice
print(com_choice)
# prints a random item from the list as the computer's choice
if user_play == com_choice:
print('Draw!')
draw = draw + 1
# if the user plays the same move as the computer, one point goes to draw
elif user_play == 'r' and com_choice == 'p':
print('Paper beats rock.')
print('AI wins!')
loss = loss + 1
# if the user plays rock and computer plays paper, says that the computer won and puts a point in the loss category
elif user_play == 'r' and com_choice == 's':
print('Rock beats scissors.')
print(name + ' wins!')
win = win + 1
# if the user plays rock and computer plays scissors, says that the person won and puts a point in the win category
elif user_play == 'p' and com_choice == 'r':
print('Paper beats rock.')
print(name + ' wins!')
win = win + 1
# if the user plays paper and computer plays rock, says that the person won and puts a point in the win category
elif user_play == 'p' and com_choice == 's':
print('Scissors beats paper.')
print('AI wins!')
loss = loss + 1
# if the user playspaper and scissors plays paper, says that the computer won and puts a point in the loss category
elif user_play == 's' and com_choice == 'r':
print('Rock beats scissors.')
print('AI wins!')
loss = loss + 1
# if the user plays scissors and computer plays rock, says that the computer won and puts a point in the loss category
elif user_play == 's' and com_choice == 'p':
print('Scissors beats paper.')
print(name + ' wins!')
win = win + 1
# if the user plays scissors and computer plays paper, says that the person won and puts a point in the win category
print(name + "'s final score:")
print('Wins: ' + str(win))
print('Loss: ' + str(loss))
print('Draws: ' + str(draw))
# prints the final score after all games are finished.

Related

If user inputs letter output should be word

Basically, my game runs off 3 words - Steal, Deal or Quit however I want the option that if the user inputs say the letter 's' it should = Steal as the output (The player is versing a PC and the results of the game are based on the 2 values.
human = input('Steal, Deal or Quit [s|d|q]?:')
print(" ")
print('You chose: ' + human)
#Computer input
sd = ["Steal", "Deal"]
computer_choice = random.choice(sd)
print('Comp chose: ' + computer_choice)
print(" ")
if human == computer_choice:
print('Draw! Split pot -50 each')
elif human == 'Steal' and computer_choice == 'Deal':
print('You win! You gain 100.')
elif human == 'Deal' and computer_choice == 'Steal':
print('You loose! Comp gain 100.')
elif human == 'Steal' and computer_choice == 'Steal':
print('Too Greedy! You get nothing')
You should use a dictionary to map the human letter input to the words Steal or Deal
First add the dictionary at the top:
human_input_map = {
's': 'Steal'
'd': 'Deal'
}
Then after taking the user input you can convert their input into the full word for comparing with computer_choice.
human = input('Steal, Deal or Quit [s|d|q]?:')
human = human_input_map[human]

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?
computermove is undefined because it's not available in the scope you're accessing it and you haven't created it anywhere else. You need to create a variable that receives the value returned by the function that generates the computer move.
computermove = computer_rps() # Add this line here and it should do it
#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()
The error is pretty explicative. It's telling you that the variable computermove is not defined on the line where you are trying to use it.
You need to define said variable to the return value of the function computer_rps before calling the gameresult function.
Such as:
computermove = computer_rps()
if int(gameresult(user_move, computermove...

I am working on a rock, paper, scissors program using functions and it is always returning else cases

I am looking for some input on a rock, paper, scissors program that I am making where the statements in the main() and determineWinner that use playerChoice always terminate in the else: case. Each trial will output the player chooses scissors and that the game is tied. I am not sure where I went wrong here as I've printed the input to confirm it is correct before sending to it to the other functions. I cannot figure what pare of the above to function is causing the problem, if anyone could point me in the right direction here I would be grateful.
Here is the code I have so far:
import random
# define main function
def main():
# initialize playAgain to start game, set stats to 0
playAgain = 'y'
numberTied = 0
numberPlayerWon = 0
numberComputerWon = 0
print("Let's play a game of rock, paper, scissors.")
# loop back to play again if user confirms
while playAgain == 'y' or playAgain == 'Y':
computerChoice = processComputerChoice()
playerChoice = processPlayerChoice()
# display computer choice
if computerChoice == 1:
print('The computer chooses rock.')
elif computerChoice == 2:
print('The computer chooses paper.')
else:
print('The computer chooses scissors.')
# display player choice
if playerChoice == 1:
print('You choose rock.')
elif playerChoice == 2:
print('You choose paper.')
else:
print ('You choose scissors.')
# assign who won to result and add total wins/ties to accumulator
result = determineWinner(playerChoice, computerChoice)
if result == 'computer':
numberComputerWon += 1
elif result == 'player':
numberPlayerWon += 1
else:
numberTied += 1
# ask player if they would like to play again
print('')
print
playAgain = input('Do you want to play again? (Enter y or Y to start another game)')
print('')
else:
# print accumulated wins and ties for computer and player
print('There were', numberTied, 'tie games played.')
print('The computer won', numberComputerWon, 'game(s).')
print('The player won', numberPlayerWon, 'game(s).')
print('')
# define computer choice function
def processComputerChoice():
# randomly select an option for the computer to play
randomNumber = random.randint(1,3)
print(randomNumber)
return randomNumber
# define player choice function
def processPlayerChoice():
choice = int(input(('What is your choice? Enter 1 for rock, 2 for paper, or 3 for scissors. ')))
print (choice)
# throw error if player makes invalid choice
while choice != 1 and choice != 2 and choice != 3:
print('ERROR: please input a valid choice of 1, 2, or 3')
choice = int(input('Please enter a correct choice: '))
return choice
# definition for the function to determine the winner
def determineWinner(playerChoice, computerChoice):
# determine player choice and compare to computer choice to determine the winner
if computerChoice == 1:
if playerChoice == 2:
print('Paper covers rock. You are victorious!')
winner = 'player'
elif playerChoice == 3:
print('Rock bashes scissors. The computer is victorious!')
winner = 'computer'
else:
print('The game is tied. Try again 1')
winner = 'tied'
if computerChoice == 2:
if playerChoice == 1:
print('Paper covers rock. The computer is victorious!')
winner = 'computer'
elif playerChoice == 3:
print('Scissors slice paper. You are victorious!')
winner = 'player'
else:
print('The game is tied. Try again 2')
winner = 'tied'
if computerChoice == 3:
if playerChoice == 1:
print('Rock bashes scissors. You are victorious!')
winner = 'player'
elif playerChoice == 2:
print('Scissors slice paper. The computer is victorious!')
winner = 'computer'
else:
print('The game is tied. Try again 3')
winner = 'tied'
return winner
main()
input("Press Enter to continue")
The return statement of your function processPlayerChoice has incorrect indentation. It should be out of while loop (unindent it one level)
At the moment, if player enters correct choice your function will return None.
If user enters incorrect choice, it will enter the while loop and will return whatever the second input from user is.
def processPlayerChoice():
choice = int(input(('What is your choice? Enter 1 for rock, 2 for paper, or 3 for scissors. ')))
print (choice)
# throw error if player makes invalid choice
while choice != 1 and choice != 2 and choice != 3:
print('ERROR: please input a valid choice of 1, 2, or 3')
choice = int(input('Please enter a correct choice: '))
return choice
Make sure to align your return statements with the function body. Currently in both processPlayerChoice and determineWinner they are aligned with the conditional loops, and thus will not be reached every time.

Rock paper scissors AI issue

I'm building a simple rock paper scissors game. It works fine, except for the fact that the game won't stop when comp_count reaches 3. I can't seem to understand why, since it works fine for player_count. Help me out please!
from random import randint
player_count = 0
comp_count = 0
def game():
player_choice = raw_input('Do you choose rock [r], paper [p], or scissors [s]? ')
computer_choice = randint(0,2)
#Rock = 0 Paper = 1 Scissors = 2
#Player chooses paper, computer chooses rock
if player_choice == "p" and computer_choice == 0:
print 'Computer chose rock'
player_won()
#Player chooses rock, computer chooses scissors
elif player_choice == 'r' and computer_choice == 2:
print 'Computer chose scissors'
player_won()
#Player chooses scissors, computer chooses paper
elif player_choice == 's' and computer_choice == 1:
print 'Computer chose paper'
player_won()
#Computer chooses paper, player chooses rock
elif player_choice == 'r' and computer_choice == 1:
print 'Computer chose paper'
computer_won()
#Computer chooses rock, player chooses scissors
elif player_choice == 's' and computer_choice == 0:
print 'Computer chose rock'
computer_won()
#Computer chooses scissors, player chooses paper
elif player_choice == 'p' and computer_choice == 2:
print 'Computer chose scissors'
computer_won()
#Ties
elif player_choice == 'r' and computer_choice == 0:
print "It's a tie!"
game()
elif player_choice == 's' and computer_choice == 2:
print "It's a tie!"
game()
elif player_choice == 'p' and computer_choice == 1:
print "It's a tie!"
game()
#Wrong input
else:
print 'Please try again.'
game()
def player_won():
global player_count
print 'You win!'
player_count += 1
print 'You have ' + str(player_count) + ' point(s).'
while player_count < 3:
game()
def computer_won():
global comp_count
print 'Computer wins!'
comp_count += 1
print 'Computer has ' + str(comp_count) + ' point(s).'
while comp_count < 3:
game()
print 'Welcome to Rock, Paper, Scissors! First to 3 points wins it all.'
game()
Your while loops are whats causing your problem. Simply change while to a if in your player_won and computer_won functions and it fixes the issue.
def player_won():
global player_count
print 'You win!'
player_count += 1
print 'You have ' + str(player_count) + ' point(s).'
if player_count < 3:
game()
def computer_won():
global comp_count
print 'Computer wins!'
comp_count += 1
print 'Computer has ' + str(comp_count) + ' point(s).'
if comp_count < 3:
game()
Now go rock paper scissors your heart out!
I admit this isn't really a direct answer to your question, but I feel it might be useful to have a potentially simpler way to write this brought up.
You could make the user choose from three different numbers in the input instead of letters, or just convert the letters to numbers. One advantage of this is that to test for a tie, you could simply write:
if player_choice == computer_choice:
Even checking for who won in a game if it wasn't a tie wouldn't be very difficult, since if it is all numeric, an option that beats another one will be one away from it in a certain direction. So, for example, you could test if the player won like so:
winning = computer_choice - 1
if winning == -1: winning = 2
if player_choice == wining:
player_won()
else: #assuming we have already checked if it is a tie, we can say that otherwise the computer won.
computer_won()
If each number represented a different option (for example if you had a dictionary linking 0 to rock, 1 to scissors, and 2 to paper), then this would check if the user chose the option before the computer's, which would be the winning option.
That would actually let you check for who won and with which options with relatively few if statements. Your check could look something like this:
options = {0: "rock", 1:"scissors", 2:"paper"}
#collect player and computer choice here
print "computer chose "+options[computer_choice] #We will probably tell them what the computer chose no matter what the outcome, so might as well just put it once up here now that a variable can determine what the computer chose.
if player_choice == computer_choice:
print "It's a tie!"
game()
winning = computer_choice - 1
if winning == -1: winning = 2
if player_choice == wining:
player_won()
else: #assuming we have already checked if it is a tie, we can say that otherwise the computer won.
computer_won()
This isn't really necessary for making your code work, but I think it will be useful if you are interested.

Undefined Function?

I am not sure why I am getting an error that game is not defined:
#!/usr/bin/python
# global variables
wins = 0
losses = 0
draws = 0
games = 0
# Welcome and get name of human player
print 'Welcome to Rock Paper Scissors!!'
human = raw_input('What is your name?')
print 'Hello ',human
# start game
game()
def game():
humanSelect = raw_input('Enter selection: R - Rock, P - Paper, S - Scissors, Q - Quit: ')
while humanSelect not in ['R', 'P', 'S', 'Q']:
print humanSelect, 'is not a valid selection'
humanSelect = raw_input('Enter a valid option please')
return humanSelect
main()
Because, at the time the statement game() is executed you have not yet reached the statement def game(): and game is, therefore, undefined.
If you move game() to after def game() you will then get a similar error on main() which is harder to fix as you don't appear to be defining a function called main anywhere in the code.
You have to define the function game before you can call it.
def game():
...
game()
Okay, I spent some time tinkering with this today and now have the following:
import random
import string
# global variables
global wins
wins = 0
global losses
losses = 0
global draws
draws = 0
global games
games = 0
# Welcome and get name of human player
print 'Welcome to Rock Paper Scissors!!'
human = raw_input('What is your name? ')
print 'Hello ',human
def readyToPlay():
ready = raw_input('Ready to Play? <Y> or <N> ')
ready = string.upper(ready)
if ready == 'Y':
game()
else:
if games == 0:
print 'Thanks for playing'
exit
else:
gameResults(games, wins, losses, draws)
return
def game():
global games
games += 1
human = humanChoice()
computer = computerChoice()
playResults(human, computer)
readyToPlay()
def humanChoice():
humanSelect = raw_input('Enter selection: R - Rock, P - Paper, S - Scissors: ')
while humanSelect not in ['R', 'P', 'S']:
print humanSelect, 'is not a valid selection'
humanSelect = raw_input('Enter a valid option please')
return humanSelect
def computerChoice():
computerInt = random.randint(1, 3)
if computerInt == '1':
computerSelect = 'R'
elif computerInt == '2':
computerSelect = 'P'
else:
computerSelect = 'S'
return computerSelect
def playResults(human, computer):
global draws
global wins
global losses
if human == computer:
print 'Draw'
draws += 1
elif human == 'R' and computer == 'P':
print 'My Paper wrapped your Rock, you lose.'
losses += 1
elif human == 'R' and computer == 'S':
print 'Your Rock smashed my Scissors, you win!'
wins += 1
elif human == 'P' and computer == 'S':
print 'My Scissors cut your paper, you lose.'
losses += 1
elif human == 'P' and computer == 'R':
print 'Your Paper covers my Rock, you win!'
wins += 1
elif human == 'S' and computer == 'R':
print 'My Rock smashes your Scissors, you lose.'
losses += 1
elif human == 'S' and computer == 'P':
print 'Your Scissors cut my Paper, you win!'
wins += 1
def gameResults(games, wins, losses, draws):
print 'Total games played', games
print 'Wins: ', wins, ' Losses: ',losses, ' Draws: ', draws
exit
readyToPlay()
I am going to work on the forcing the humanSelect variable to upper case in the same manner that I did with ready, ready = string.upper(ready). I ran into indentation errors earlier today, but will iron that out later tonight.
I do have a question. Is it possible to use a variable between the () of a raw_input function similar to this:
if game == 0:
greeting = 'Would you like to play Rock, Paper, Scissors?'
else:
greeting = 'Play again?'
ready = raw_input(greeting)

Categories