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.
Related
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
I Was Practicing Programs Of Python And Then I Made This Rock, Paper, Scissors Program. And The Program Is Running Perfectly But The Problem Is Like This:
I Chose "Rock, Paper, Scissors" Like This Than It Runs.
But If I Enter Rock, Paper, Scissors In Any Other Way It Prints The Else Statment i.e., Invalid Choice.
I Want To Use Upper/Lower Case But How And Where.
import random
user = input("""Tell Me What Do You Choose:
~Rock
~Paper
~Scissors.
-> I Choose : """)
choose = ["Rock", "Paper", "Scissors"]
computer = random.choice(choose)
print(f"Computer Chose {computer}.")
#Function To Compare Choices
def compare(user, computer):
if user == computer:
return("It's A Tie :(....")
elif user == "Rock":
if computer == "Scissors":
return("User Wins!")
else:
return("Computer Wins!")
elif user == "Scissors":
if computer == "Paper":
return("User Wins!")
else:
return("Computer Wins!")
elif user == "Paper":
if computer == "Rock":
return("User Wins!")
else:
return("Computer Wins!")
else:
return("User Choose Out Of The Options!")
exit()
print(compare(user, computer))
just transform your input into lowercase with the lower() method
user = user.lower()
that makes sCiSsOrS into scissors
you also need to adjust your if statements to be all lowercase
elif user == "Rock": --> elif user == "rock":
I just started to learn how to program three days ago. I decided to learn Python, version 3.7.2. Today I wrote this code trying to create a game in which you enter a username and play rock, paper, scissors against a bot. However right after I enter my username (line 2-4), the Python shell closes. I am running the program by clicking on the file in My Explorer, Windows 10. I suppose this is a simple beginner mistake, can someone please help out?
I tried adding input() at line 4. When I do this, the Python shell does not close after entering the username. It does nothing, just newline. And when I type something in that newline and press Enter, the shell closes.
Here's my code:
import random
print('Hello, welcome to Rock, Paper, Scissors. Enter your name to get started.')
usn = input()
def game(choice):
options = ['rock', 'paper', 'scissors']
bot = random.choice(options)
if choice == 'rock' and bot == 'scissors':
print(usn + ' played rock, I played scissors. You won. Nice!')
elif choice == 'rock' and bot == 'paper':
print(usn + ' played rock, I played paper. You lost. Haha, loser!')
elif choice == 'paper' and bot == 'scissors':
print(usn + ' played paper, I played scissors. You lost. Haha, loser!')
elif choice == 'paper' and bot == 'rock':
print(usn + ' played paper, I played rock. You won. Nice!')
elif choice == 'scissors' and bot == 'paper':
print(usn + ' played scissors, I played paper. You won. Nice!')
elif choice == 'scissors' and bot == 'rocks':
print(usn + ' played scissors, I played rocks. You lost. Haha, loser!')
elif choice == bot:
print("It's a draw, dang it!")
def again(x):
while True:
if x == 'Yes':
game(input('Rock, Paper or Scissors?'))
again(input('Want to play again? Yes or No'))
else:
print('Goodbye. Press Enter to exit.')
input()
Expected: I expected that after I enter a username, I can enter either rock, paper or scissors and then the game would play.
Actual result: Python shell closes after entering the username.
You need to call game too -- though game needs to be declared at that point.
I refactored things a little here and made them a little more convenient for the user.
The argument names used in game are username and user_choice, so as not to shadow the global names (or use them by accident).
The again() recursive function is replaced by a while loop that's breaked out of when the user says they don't want to play again.
The RPS and again question inputs are lower-cased and stripped, so the user entering, say, " NO ", "nO", "pAPeR", etc. works.
The next thing I'd recommend thinking about is how to simplify the repetition in the game function. :)
import random
def game(username, user_choice):
options = ['rock', 'paper', 'scissors']
bot = random.choice(options)
if user_choice == 'rock' and bot == 'scissors':
print(username + ' played rock, I played scissors. You won. Nice!')
elif user_choice == 'rock' and bot == 'paper':
print(username + ' played rock, I played paper. You lost. Haha, loser!')
elif user_choice == 'paper' and bot == 'scissors':
print(username + ' played paper, I played scissors. You lost. Haha, loser!')
elif user_choice == 'paper' and bot == 'rock':
print(username + ' played paper, I played rock. You won. Nice!')
elif user_choice == 'scissors' and bot == 'paper':
print(username + ' played scissors, I played paper. You won. Nice!')
elif user_choice == 'scissors' and bot == 'rocks':
print(username + ' played scissors, I played rocks. You lost. Haha, loser!')
elif user_choice == bot:
print("It's a draw, dang it!")
print('Hello, welcome to Rock, Paper, Scissors. Enter your name to get started.')
name = input()
while True: # do forever, unless `break`ed out of (or an exception occurs)
choice = input('Rock, Paper or Scissors?').lower().strip()
game(name, choice)
if input('Want to play again? Yes or No').lower().strip() == 'no':
print('Goodbye. Press Enter to exit.')
input()
break # break out of the "while true" loop
First problem is that you are not calling any function after receiving the user name I would try something like this (notice that i added some comments to the code):
import random
print('Hello, welcome to Rock, Paper, Scissors. Enter your name to get started.')
usn = input()
def game(choice):
options = ['rock', 'paper', 'scissors']
bot = random.choice(options)
if choice == 'rock' and bot == 'scissors':
print(usn + ' played rock, I played scissors. You won. Nice!')
elif choice == 'rock' and bot == 'paper':
print(usn + ' played rock, I played paper. You lost. Haha, loser!')
elif choice == 'paper' and bot == 'scissors':
print(usn + ' played paper, I played scissors. You lost. Haha, loser!')
elif choice == 'paper' and bot == 'rock':
print(usn + ' played paper, I played rock. You won. Nice!')
elif choice == 'scissors' and bot == 'paper':
print(usn + ' played scissors, I played paper. You won. Nice!')
elif choice == 'scissors' and bot == 'rocks':
print(usn + ' played scissors, I played rocks. You lost. Haha, loser!')
elif choice == bot:
print("It's a draw, dang it!")
# Taking this out of the function, it is going to be called right on the execution
x = 'Yes'
while True: #here you are doing an loop, that will only end when break is called
if x == 'Yes':
game(input('Rock, Paper or Scissors?'))
x = input('Want to play again? Yes or No')
else:
print('Goodbye. Press Enter to exit.')
input()
break
def game(choice): creates a function named game. you need to tell python to execute this function with one parameter: choice
like so: game(usn)
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 7 years ago.
Im new to programming and trying to build a simple rock paper scissors program in python 2.7. in my function i have 2 main if statements
rules = raw_input("Before we being playing would you like to hear the rules first? ")
if rules.lower() == "yes":
print """
Scissors cuts Paper
Paper covers Rock
Rock crushes Scissors"""
and the second
choice = raw_input("please enter your choice? (Must be either rock, paper or scissors) ")
computer = random.choice(["rock", "paper", "scissors"])
if choice == "rock" or "paper" or "scissors":
if choice == computer :
print "Its a tie !"
elif choice == "rock" and computer == "scissors":
print "Rock beats scissors you win!."
elif choice == "rock" and computer == "paper":
print "Paper beats rock you loose !."
elif choice == "paper" and computer == "scissors":
print "Scissors beats paper you loose !."
elif choice == "paper" and computer == "rock":
print "Paper beats rock you win !."
elif choice == "scissors" and computer == "paper":
print "Scissors beats paper you win !."
elif choice == "scissors" and computer == "rock":
print "Rock beats scissors you loose !."
else :
print "Invalid Entry Please try again."
individually both bits of code work as they should but when i try and put them together in one function the first if statement asking about rules works but then quits before the second if statement which has the main functionality of the program. Ive tried indenting the second bit of code within the first if statement but it doesn't seem to work
I was wondering if there is anyway of making these 2 snips of code work in a simple function ? or should i create a class with these 2 functions ?
also if anyone has any tips on how to make my progam better please let me know. Thanks for any help in advance.
heres the full code
import random
def rock_paper_scissors_spock():
rules = raw_input("Before we being playing would you like to hear the rules first? ")
if rules.lower() == "yes":
print """
Scissors cuts Paper
Paper covers Rock
Rock crushes Scissors"""
choice = raw_input("please enter your choice? (Must be either rock, paper or scissors) ")
computer = random.choice(["rock", "paper", "scissors"])
if choice == "rock" or "paper" or "scissors":
if choice == computer :
print "Its a tie !":
elif choice == "rock" and computer == "scissors":
print "Rock beats scissors you win!."
elif choice == "rock" and computer == "paper":
print "Paper beats rock you loose !."
elif choice == "paper" and computer == "scissors":
print "Scissors beats paper you loose !."
elif choice == "paper" and computer == "rock":
print "Paper beats rock you win !."
elif choice == "scissors" and computer == "paper":
print "Scissors beats paper you win !."
elif choice == "scissors" and computer == "rock":
print "Rock beats scissors you loose !."
else :
print "Invalid Entry PLease try again."
rock_paper_scissors_spock()
You said if choice == "rock" or "paper" or "scissors":, but Python does not connect the choice == to all of the choices. You could put parentheses around choice == "rock", and it would do the same thing. Change it to if choice in ("rock", "paper", "scissors")
I am trying to create a rock, paper, scissors game in Python. I am a newbie so please forgive what may seem like a simple question. I am creating a function that can run through the user's choice and compare it to a random selection by the computer. I would like the results to be displayed as a print statement, however I keep getting None as the feedback. Please also note I know there are more potential outcomes, so far I am only testing the outcomes if the user selects "rock".
Here is the section of code:
import random
rkprsr = ['rock', 'paper', 'scissors']
random.shuffle(rkprsr)
def gameplay (user_choice):
dealer_choice = rkprsr.pop()
if user_choice == 'rock' and dealer_choice == 'paper':
print ('You selected rock and I selected paper. My paper covers your rock. You lose.')
elif user_choice == 'rock' and dealer_choice == 'scissors':
print ('You selected rock and I selected scissors. Your rock crushes my scissors. You win!')
elif user_choice == 'rock' and dealer_choice == 'rock':
print ('You selected rock and I selected rock. Stalemate. We tied.')
return
user_choice = input ('Please type rock, paper, or scissors:')
print('')
print('')
user_choice = user_choice.lower
print (gameplay(user_choice))
user_choice = user_choice.lower
print (gameplay(user_choice))
I see two problems. First, lower needs parentheses or else user_choice will be a function object rather than a string. This is why none of your if conditions are passing even though the user inputs "rock". Second, printing the result of gameplay will always print None, because that's what gets returned when you have a return statement with nothing after it. (or if you don't have a return statement at all).
user_choice = user_choice.lower()
gameplay(user_choice)
You have an empty return statement, which will return None. All printing is done within the function itself, so you don't need to print gameplay(user_choice), nor do you need to have a return statement in the function. Simply call it and it should do what you expect. None is the return value from that function call so it is printed out.
Edit: As other poster noticed, user_choice.lower needs the parentheses to function properly
You're probably trying to do the following:
def gameplay (user_choice):
dealer_choice = rkprsr.pop()
if user_choice == 'rock' and dealer_choice == 'paper':
return 'You selected rock and I selected paper. My paper covers your rock. You lose.'
elif user_choice == 'rock' and dealer_choice == 'scissors':
return 'You selected rock and I selected scissors. Your rock crushes my scissors. You win!'
elif user_choice == 'rock' and dealer_choice == 'rock':
return 'You selected rock and I selected rock. Stalemate. We tied.'
The function gameplay will return a string, which you can print in the outer scope if you wish.