Python Rock Paper Scissors List Choices - python

Instructions: Write a program to allow the user to play Rock, Paper, Scissors against the computer. The program will be menu driven (see details below). The user can continue to play the game over and over by choosing to play the game in the menu. A game consists of a single battle: win, lose, or tie. For a single battle the user makes their move and then the computer move is displayed followed by a description of who won that battle. Do not break a tie.
Once the user chooses to quit, the program then displays the win/loss/tie record for all the games just played
The user will enter the details in the following order during gameplay:
Menu choice (1 integer, 1 to play a game, 2 to quit)
Player's move (1 string, 'Rock', 'Paper', or 'Scissors')
My problem is that I'm not sure how to make the computer choose from my list and accept it. I keep getting this...1
import random
def main():
"""
Runs a game of Rock, Paper, Scissors. Asks the user for input and plays against the computer.
"""
#print display message
print('Lets play Rock, Paper, Scissors!')
moves_list = ['Rock', 'Paper', 'Scissors']
#a place to keep track of scores
tied = 0
computer = 0
player = 0
#create a variable to control loop
play_again = 1
comp_choice = process_comp()
player_choice = process_player()
winner = determine_winner(player_choice, comp_choice)
#while loop for multiple games
while play_again == 1:
comp_choice = process_comp()
player_choice = process_player()
if comp_choice == 'Rock' or comp_choice == 'rock':
print('Computer chooses rock.')
elif comp_choice == 'Paper' or comp_choice == 'paper':
print('Computer chooses paper.')
else:
print('Computer chooses scissors.')
#call the determine winner function
winner = determine_winner(player_choice, comp_choice)
#check who won the game and add 1 to the correct winner
if winner == 'computer':
computer += 1
elif winner == 'player':
player += 1
else:
tied += 1
#ask user if they want to play again
play_again = input('Would you like to play again? (Enter 1 for yes, 2 for no): ')
#display number of games that were won
print()
print('There were', tied, 'tied games.')
print('The player won', player, 'games.')
print('The computer won', computer,'games.')
#define the computer process function
def process_comp():
#make computer choose a move from list
choosen = random.choice(moves_list)
return choosen
#make sure user enters correct option.
def process_player():
player_choice = int(input('Rock, Paper, Scissors? (Enter 2 if you want to quit):'))
#if the player enters 2, quit the game
if player_choice == 2:
print('Thank you for playing!')
play_again = 2
#check if user is inputting correct selections
while player_choice != 'Rock' or player_choice != 'rock' and player_choice != 'Paper' or player_choice != 'paper' and player_choice != 'Scissors' or player_choice != 'scissors' and player_choice != 2:
print('Error! Please enter an option that was given.')
player_choice = int(input('Rock, Paper, Scissors? (Enter 2 if you want to quit):'))
return player_choice
#define the determine winner function.
def determine_winner(player_choice, comp_choice):
#setup computer selections
if comp_choice == 'Rock' or comp_choice == 'rock':
if player_choice == 'Paper' or player_choice == 'paper':
print('You win!')
winner = 'player'
elif player_choice == 'Scissors' or player_choice == 'scissors':
print('The computer wins!')
winner = 'computer'
else:
print('The game is tied. Try again.')
winner = 'tied'
if comp_choice == 'Paper' or comp_choice == 'paper':
if player_choice == 'Rock' or player_choice == 'rock':
print('The computer wins!')
winner = 'computer'
elif player_choice == 'Scissors' or player_choice == 'scissors':
print('You win!')
winner = 'player'
else:
print('The game is tied. Try again.')
winner = 'tied'
if comp_choice == 'Scissors' or comp_choice == 'scissors':
if player_choice == 'Rock' or player_choice == 'rock':
print('You win!')
winner = 'player'
elif player_choice == 'Paper' or player_choice == 'player':
print('The computer wins!')
winner = 'computer'
else:
print('The game is tied. Try again.')
winner = 'tied'
return winner
main()

You are trying to translate a string, e.g. rock into an integer (number). This is not possible as Python has no way of knowing the integer you wish to translate it into. Instead you could change your process_player() to the following. I simplified your while statement, and removed the translation to int - Then you check for whether player_choice is equal to the string '2' instead of the integer version, and it should work
def process_player():
player_choice = input('Rock, Paper, Scissors? (Enter 2 if you want to quit):')
# if the player enters 2, quit the game
if player_choice == '2':
print('Thank you for playing!')
# check if user is inputting correct selections
while player_choice.lower() not in ['rock', 'paper', 'scissors', '2']:
print('Error! Please enter an option that was given.')
player_choice = input('Rock, Paper, Scissors? (Enter 2 if you want to quit):')
return player_choice

Related

Always receive 'You Lose' message in RPS against computer

For my exercise, I have to get the computer to play against the user in RPS. However, after both the computer and I input our action, the user will always receive a 'You Lose'.
import random
def get_computer_move():
"""Deterministic 'random' move chooser"""
options = ['rock', 'paper', 'scissors']
return options[random.randint(0, 2)]
def game_result(move1, move2):
"""game_result *exactly* as defined in question one"""
options = ["rock", "paper", "scissors"]
if move1 == move2:
return 0
elif move1 == "paper" and move2 == "rock":
return 1
elif move1 == "rock" and move2 == "scissors":
return 1
elif move1 == "scissors" and move2 == "paper":
return 1
else:
return 2
def main():
"""Runs a single game of PSR"""
print("Let's Play Paper, Scissors, Rock!")
user1 = input("Player one move: ").lower()
computer1 = print("The computer plays " + get_computer_move())
game_result(computer1, user1)
if user1 == computer1:
return print("It's a draw")
elif user1 == "paper" and computer1 == "rock":
return print("You win")
elif user1 == "rock" and computer1 == "scissors":
return print("You win")
elif user1 == "scissors" and computer1 == "paper":
return print("You win")
else:
return print("You lose")
main()
Here is my code although it is quite messy.
What I want to happen is:
Let's Play Paper, Scissors, Rock!
Player one move: ROCK
The computer plays rock
It's a draw
But it will always come out as:
Let's Play Paper, Scissors, Rock!
Player one move: ROCK
The computer plays rock
You lose
Help would be appreciated.
print returns none, you want to save the computers move and then print that separately
computer1 = get_computer_move()
print("The computer plays", computer1)

I wrote a simple python game but functions in that are not executing

I am fairly new in python coding. I made a simple rock, paper, scissor game using random module. I wrote it in three functions. when I am executing it, I get no error but it is not executing the functions.
what I wrote:
import random
def main():
global comp
global user
global play
play = ''
#preparing list for computer to select from
game = ['rock', 'paper', 'scissor']
#computer chooses randomly from the list above
comp = random.choice(game)
print(comp)
#user inputs their choice
user = input("Rock, Paper or Scissor? ")
def user_choice():
global play
play = input("Do you want to continue? press y or n for yes and no respectively. ")
if play == y:
main()
elif play == n:
print("Thank you for playing!")
exit()
#conditions to the game
def play_game():
global user
global comp
while True:
if user == comp:
print("Tie!")
print("Computer: ", comp, "and User:", user)
elif user == 'rock':
if comp == 'paper':
print("Rock covers paper, computer wins")
else:
print("rock smashes through scissor, you win")
elif user == 'paper':
if comp == 'rock':
print("paper covers rock, you win!")
else:
print("scissor cuts through paper, computer wins")
elif user == 'scissor':
if comp == 'rock':
print("Rock smashes through scissor, Computer wins!")
else:
print("Scissor cuts through paper")
user_choice()
if __name__ == '__main__':
main()
play_game()
it is not executing play_game() and user_choice().
It only ask for the input.
The first thing which is wrong is that y and n are not under "" thus python is treating them as a variable. the second thing which was wrong is the position of the play game which should come below the main() to get executed. All user_choice() was not indented properly
Try this code
import random
def main():
global comp
global user
global play
play = ''
# preparing list for computer to select from
game = ['rock', 'paper', 'scissor']
# computer chooses randomly from the list above
comp = random.choice(game)
print(comp)
# user inputs their choice
user = input("Rock, Paper or Scissor? ")
def user_choice():
global play
play = input(
"Do you want to continue? press y or n for yes and no respectively. ")
if play == "y":
main()
elif play == "n":
print("Thank you for playing!")
exit()
# conditions to the game
def play_game():
global user
global comp
while True:
if user == comp:
print("Tie!")
print("Computer: ", comp, "and User:", user)
elif user == 'rock':
if comp == 'paper':
print("Rock covers paper, computer wins")
else:
print("rock smashes through scissor, you win")
elif user == 'paper':
if comp == 'rock':
print("paper covers rock, you win!")
else:
print("scissor cuts through paper, computer wins")
elif user == 'scissor':
if comp == 'rock':
print("Rock smashes through scissor, Computer wins!")
else:
print("Scissor cuts through paper")
user_choice()
if __name__ == '__main__':
main()
play_game()
Create another function main() and call play_game() and user_choice() within main.
The code calls the main() function and this takes an input, but it does not call any of the other functions.
This is why.
Expect that you mean to call play_game() and user_choice() from within main().
Working code.
import random
def main():
global comp
global user
global play
play = ''
#preparing list for computer to select from
game = ['rock', 'paper', 'scissor']
#computer chooses randomly from the list above
comp = random.choice(game)
print(comp)
#user inputs their choice
user = input("Rock, Paper or Scissor? ")
user_choice()
play_game()
def user_choice():
global play
play = input("Do you want to continue? press y or n for yes and no respectively. ")
if play == 'y':
main()
elif play == 'n':
print("Thank you for playing!")
exit()
#conditions to the game
def play_game():
global user
global comp
while True:
if user == comp:
print("Tie!")
print("Computer: ", comp, "and User:", user)
elif user == 'rock':
if comp == 'paper':
print("Rock covers paper, computer wins")
else:
print("rock smashes through scissor, you win")
elif user == 'paper':
if comp == 'rock':
print("paper covers rock, you win!")
else:
print("scissor cuts through paper, computer wins")
elif user == 'scissor':
if comp == 'rock':
print("Rock smashes through scissor, Computer wins!")
else:
print("Scissor cuts through paper")
if __name__ == '__main__':
main()

Rock Paper Scissors Not Printing Out Results

I am trying to create a Rock Paper Scissors program against a computer but running into some issues.
I have made two methods, one for the computer's choice and the user's choice. For the computer, it randomly generates 0,1,2 and selects rock, paper or scissors from an array which I declared as a local variable, rps. When I try to run the game with the game_play() method, I am able to enter in input but don't get an output of the result between the player and the computer.
class RockPaperScissors():
global rps
rps = ['rock', 'paper','scissors']
def computer_choice(self): #computer randomly picks rock paper or scissors
x = random.randint(0,2)
w = rps[x]
return w
#print(rps[x])
def player_choice(self): #does the player choose rock paper or scissors
x = True
while x:
choice = (input("Player- would you like rock, paper, or scissors? enter rock,paper, or scissors?: "))
if choice.lower() == 'rock':
return 'rock'
elif choice.lower() == 'paper':
return 'paper'
elif choice.lower() == 'scissors':
return 'scissors'
else:
("please enter in rock, paper or scissors")
def game_play(self):
rock = RockPaperScissors()
user = rock.player_choice()
comp= rock.computer_choice()
if comp == 'rock' and user == 'paper':
return "the player wins!"
elif comp == 'rock' and user == 'scissors':
return "the computer wins!"
elif comp == 'paper' and user == 'rock':
return "the computer wins!"
elif comp == 'paper' and user == 'scissors':
return "the player wins!"
elif comp == 'scissors' and user == 'paper':
return"the computer wins!"
elif comp == 'scissors' and user == 'rock':
return "the player wins"
I am trying to test it this way:
rock = RockPaperScissors()
rock.game_play()
If you are running it as a script instead of everything in the Python interpreter. You must explicitly print the value.
One possible solution is:
rock = RockPaperScissors()
print(rock.game_play())
Directly answering your question: you are not "printing" the game, which would be...
print(rock.game_play())
However, there's some other improvements I would do.
Avoid global variables so that you can provide greater clarity to
the code. Maybe it's a better idea to define rps inside the function
computer_choice() instead of having it as a global variable.
You can simplify player_choice() as:
x = input("Player- would you like rock, paper, or scissors? enter rock,paper, or scissors?: ").lower()
while x != 'rock' and x != 'paper' and x != 'scissors':
choice = (input("Player- would you like rock, paper, or scissors? enter rock, paper, or scissors?: "))
x = input("please enter in rock, paper or scissors").lower()
return x
Possibly, your code wasn't copied correctly, but everything below the first line (class RockPaperScissors:) is missing one indent.
Finally, another possible solution is to print the game's result inside function game_play() instead of returning a string.
Good luck and keep learning.

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.

Python Newbie - Rock, Paper, Scissors

I'm very new to Python and decided to set myself a challenge of programming a Rock, Paper, Scissors game without copying someone else's code. However, I need help from a Pythonista grown-up!
I've seen many other variations on Rock, Paper, Scissors, on here but nothing to explain why my version isn't working. My program basically follows this format: set empty variables at start, define 4 functions that prints intro text, receives player input, randomly picks the computer's choice, then assesses whether its a win or a loss for the player.
This is all then stuck in a while loop that breaks once the player selects that they don't want to play anymore. (This bit is working fine)
However, whenever I run the code, it just always gives a draw and doesn't seem to store any data for the computer's choice function call. Does anybody know what I'm doing wrong?
Many thanks!
import random
playerAnswer = ''
computerAnswer = ''
winsTotal = 0
timesPlayed = 0
def showIntroText():
print('Time to play Rock, Paper, Scissors.')
print('Type in your choice below:')
def playerChoose():
playerInput = input()
return
def computerChoose():
randomNumber = random.randint(1, 3)
if randomNumber == 1:
computerPick = 'Paper'
elif randomNumber == 2:
computerPick = 'Scissors'
else:
computerPick = 'Rock'
return
def assessResult():
if playerAnswer == computerAnswer:
print('Draw!')
elif playerAnswer == 'Rock' and computerAnswer == 'Paper':
print('Paper beats Rock. You lose!')
elif playerAnswer == 'Paper' and computerAnswer == 'Scissors':
print('Scissors cuts Paper. You lose!')
elif playerAnswer == 'Scissors' and computerAnswer == 'Rock':
print('Rock blunts Scissors. You lose!')
else:
print('You win!')
winsTotal += 1
return
while True:
timesPlayed += 1
showIntroText()
playerAnswer = playerChoose()
computerAnswer = computerChoose()
assessResult()
print('Do you want to play again? (y/n)')
playAgain = input()
if playAgain == 'n':
break
print('Thank you for playing! You played ' + str(timesPlayed) + ' games.')
You have missed returning values in most of the case.
** Add 'return playerInput ' in playerChoose() instead of only return.
** Add ' return computerPick ' in computerChoose() instead of return.
** Initialize winsTotal variable before using it as 'winsTotal = 0' in assessResult().
** Variables you have intialized at the start of program are out of scope for functions.
Please check this StackOverFlow link for understanding scope of variables in python.
** Add 'return winsTotal' in assessResult() instead of return.
import random
def showIntroText():
print('Time to play Rock, Paper, Scissors.')
print('Type in your choice below:')
def playerChoose():
playerInput = input()
return playerInput
def computerChoose():
randomNumber = random.randint(1, 3)
if randomNumber == 1:
computerPick = 'Paper'
elif randomNumber == 2:
computerPick = 'Scissors'
else:
computerPick = 'Rock'
return computerPick
def assessResult(winsTotal):
if playerAnswer == computerAnswer:
print('Draw!')
elif playerAnswer == 'Rock' and computerAnswer == 'Paper':
print('Paper beats Rock. You lose!')
elif playerAnswer == 'Paper' and computerAnswer == 'Scissors':
print('Scissors cuts Paper. You lose!')
elif playerAnswer == 'Scissors' and computerAnswer == 'Rock':
print('Rock blunts Scissors. You lose!')
else:
print('You win!')
winsTotal += 1
return winsTotal
total_win = 0
while True:
timesPlayed += 1
showIntroText()
playerAnswer = playerChoose()
computerAnswer = computerChoose()
total_win = assessResult(total_win)
print('Do you want to play again? (y/n)')
playAgain = input()
if playAgain == 'n':
break
print('Thank you for playing! You played ' + str(timesPlayed) + ' games.' + 'Out of which you won '+ str(total_win))
Output:
C:\Users\dinesh_pundkar\Desktop>python c.py
Time to play Rock, Paper, Scissors.
Type in your choice below:
"Rock"
You win!
Do you want to play again? (y/n)
"y"
Time to play Rock, Paper, Scissors.
Type in your choice below:
"Rock"
Draw!
Do you want to play again? (y/n)
"y"
Time to play Rock, Paper, Scissors.
Type in your choice below:
"Rock"
Paper beats Rock. You lose!
Do you want to play again? (y/n)
"y"
Time to play Rock, Paper, Scissors.
Type in your choice below:
"Rock"
Paper beats Rock. You lose!
Do you want to play again? (y/n)
"n"
Thank you for playing! You played 4 games.Out of which you won 1
add input and return in your functions
def computerChoose And def assessResultreturn None
for Example by this code you can play this game :
import random
playerAnswer = ''
computerAnswer = ''
winsTotal = 0
timesPlayed = 0
def playerChoose():
playerInput = input("insert:")
return playerInput
def computerChoose():
randomNumber = random.randint(1, 3)
if randomNumber == 1:
computerPick = 'Paper'
elif randomNumber == 2:
computerPick = 'Scissors'
else:
computerPick = 'Rock'
return computerPick
def assessResult(playerAnswer, computerAnswer):
if playerAnswer == computerAnswer:
print('Draw!')
elif playerAnswer == 'Rock' and computerAnswer == 'Paper':
print('Paper beats Rock. You lose!')
elif playerAnswer == 'Paper' and computerAnswer == 'Scissors':
print('Scissors cuts Paper. You lose!')
elif playerAnswer == 'Scissors' and computerAnswer == 'Rock':
print('Rock blunts Scissors. You lose!')
else:
print('You win!')
return
while True:
timesPlayed += 1
playerAnswer = playerChoose()
computerAnswer = computerChoose()
assessResult(playerAnswer,computerAnswer)
print('Do you want to play again? (y/n)')
playAgain = input()
if playAgain == 'n':
break
print('Thank you for playing! You played ' + str(timesPlayed) + ' games.')
It is always a draw because you aren't returning the answers from your function, both playerAnswer and computerAnswer return None
As some of people said playerChoose() and computerChoose() return with None
Modifidy these statement playerChoose() -> return playerInput
and computerChoose() -> return computerPick
AS well as you have to use global variable. Insert this row
global winsTotal
in the assessResult().

Categories