Currently working on a Rock Paper Scissors game for a basic python class. I've been working on it for about the past week, as I looked up how to make a basic python game and stumbled upon an article here and went off of it. Not sure why though, but it keeps looping. I want to keep the structure similar to this also, as my instructor asked me to keep it like this.
I've tried changing cpu_rand and cpu_choice, and also putting the function results() in different locations but also did not work.
import random #import random module
import sys #import system module
def playgame():
while True:
player_choice = input("Rock, Paper, or Scissors?")
cpu_rand = random.randint(1,3) #Generate random integer 1-3
cpu_choice = None
if cpu_rand == 1: #if cpu_choice = 1, cpu_choice = "Rock"
cpu_choice = "Rock"
elif cpu_rand == 2: #if cpu_choice = 2, cpu_choice = "Scissors"
cpu_choice = "Scissors"
elif cpu_rand == 3: #if cpu_choice = 3, cpu_choice = "Paper"
cpu_choice = "Paper"
def results(): #check results of player choice v computer choice
play_again = None #Sets this to null for future reference, for asking if playing again.
if(player_choice == cpu_choice): #Tie
print("It's a Tie")
play_again = input("Retry?")
#Rock Outcomes
elif(player_choice == "Rock" and cpu_choice == "Scissors"):
print("You Win!")
play_again = input("Play again?")
elif(player_choice == "Rock" and cpu_choice == "Paper"):
print("You Lose!")
play_again = input("Play again?")
#Paper Outcomes
elif(player_choice == "Paper" and cpu_choice == "Scissors"):
print("You Lose!")
play_again = input("Play again?cpu")
elif(player_choice == "Paper" and cpu_choice == "Rock"):
print("You Win!")
play_again = input("Play again?")
#Scissors Outcomes
elif(player_choice == "Scissors" and cpu_choice == "Rock"):
print("You Lose!")
play_again = input("Play again?")
elif(player_choice == "Scissors" and cpu_choice == "Paper"):
print("You Win!")
play_again = input("Play again?")
if play_again == "Yes": #if elif play again statements, from if/elif statements, play_again is changed to an input
playgame()
elif play_again == "No":
print("You Lose!")
sys.exit()
else:
print("Invalid Command")
play_again = input("play again?")
return play_again
results()
def start():
while True:
gamestart = input("You ready to play some Rock, Paper, Scissors? (y/n)")
if gamestart == "y":
playgame()
return gamestart
elif gamestart == "n":
print("Game Over!")
break
else:
print("Invalid Command")
start()
The result I was looking to be returned was everything under the results function, so if player_choice == cpu_choice then it would print out what is under that. Instead it loops back to "Rock, Paper, or Scissors?"
You never called the results function in your code so it never ran.
You didn't call results(). Moreover player_choice and cpu_choice were local variables in playgame().
import random #import random module
import sys #import system module
def playgame():
while True:
player_choice = input("Rock, Paper, or Scissors?")
cpu_rand = random.randint(1,3) #Generate random integer 1-3
cpu_choice = None
if cpu_rand == 1: #if cpu_choice = 1, cpu_choice = "Rock"
cpu_choice = "Rock"
elif cpu_rand == 2: #if cpu_choice = 2, cpu_choice = "Scissors"
cpu_choice = "Scissors"
elif cpu_rand == 3: #if cpu_choice = 3, cpu_choice = "Paper"
cpu_choice = "Paper"
results(player_choice, cpu_choice)
def results(player_choice, cpu_choice): #check results of player choice v computer choice
play_again = None #Sets this to null for future reference, for asking if playing again.
if(player_choice == cpu_choice): #Tie
print("It's a Tie")
play_again = input("Retry?")
#Rock Outcomes
elif(player_choice == "Rock" and cpu_choice == "Scissors"):
print("You Win!")
play_again = input("Play again?")
elif(player_choice == "Rock" and cpu_choice == "Paper"):
print("You Lose!")
play_again = input("Play again?")
#Paper Outcomes
elif(player_choice == "Paper" and cpu_choice == "Scissors"):
print("You Lose!")
play_again = input("Play again?cpu")
elif(player_choice == "Paper" and cpu_choice == "Rock"):
print("You Win!")
play_again = input("Play again?")
#Scissors Outcomes
elif(player_choice == "Scissors" and cpu_choice == "Rock"):
print("You Lose!")
play_again = input("Play again?")
elif(player_choice == "Scissors" and cpu_choice == "Paper"):
print("You Win!")
play_again = input("Play again?")
if play_again == "Yes": #if elif play again statements, from if/elif statements, play_again is changed to an input
playgame()
elif play_again == "No":
print("You Lose!")
sys.exit()
else:
print("Invalid Command")
play_again = input("play again?")
return play_again
results()
def start():
while True:
gamestart = input("You ready to play some Rock, Paper, Scissors? (y/n)")
if gamestart == "y":
playgame()
return gamestart
elif gamestart == "n":
print("Game Over!")
break
else:
print("Invalid Command")
start()
Your code is so dense and repetitive, may I suggest another approach?:
import random
wins = [
('paper', 'rock'), # paper wins over rock
('rock', 'scissors'),
('scissors', 'paper'),
]
items = ['rock', 'paper', 'scissors']
def computer_choice():
return random.choice(items)
def player_choice():
for i, item in enumerate(items):
print i, item
while 1:
choice = input("choose [0..%d]: " % (len(items)-1))
if 0 <= choice < len(items):
break
return items[choice]
while 1:
cpu = computer_choice()
human = player_choice()
print "CPU: %s, HUMAN: %s" % (cpu, human)
if cpu == human:
print 'tie..'
elif (cpu, human) in wins:
print "CPU wins."
else:
print "HUMAN wins."
again = raw_input("play again? [q to quit]: ")
print
if again.lower() == 'q':
break
sample session:
0 rock
1 paper
2 scissors
choose [0..2]: 0
CPU: scissors, HUMAN: rock
HUMAN wins.
play again? [q to quit]:
0 rock
1 paper
2 scissors
choose [0..2]: 1
CPU: paper, HUMAN: paper
tie..
play again? [q to quit]:
0 rock
1 paper
2 scissors
choose [0..2]: 1
CPU: scissors, HUMAN: paper
CPU wins.
play again? [q to quit]:
the only changes to make this play rock, paper, scissors, lizard, spock (https://bigbangtheory.fandom.com/wiki/Rock,_Paper,_Scissors,_Lizard,_Spock) are:
wins = [
('scissors', 'paper'), # Scissors cuts Paper
('paper', 'rock'), # Paper covers Rock
('rock', 'lizard'), # Rock crushes Lizard
('lizard', 'spock'), # Lizard poisons Spock
('spock', 'scissors'), # Spock smashes Scissors
('scissors', 'lizard'), # Scissors decapitates Lizard
('lizard', 'paper'), # Lizard eats Paper
('paper', 'spock'), # Paper disproves Spock
('spock', 'rock'), # Spock vaporizes Rock
('rock', 'scissors'), # (and as it always has) Rock crushes Scissors
]
items = ['rock', 'paper', 'scissors', 'lizard', 'spock']
sample run
0 rock
1 paper
2 scissors
3 lizard
4 spock
choose [0..4]: 4
CPU: scissors, HUMAN: spock
HUMAN wins.
play again? [q to quit]:
0 rock
1 paper
2 scissors
3 lizard
4 spock
choose [0..4]: 2
CPU: spock, HUMAN: scissors
CPU wins.
play again? [q to quit]:
Related
This is my first little program I have created. Can anyone help me with making it so it works with the first letter being capitalized?
# Rock Paper Scissors
import time
import random
user_wins = 0
computer_wins = 0
def RockPaperScissors():
user_choice = input("Enter your choice in a game of Rock, Paper, Scissors: ")
if user_choice == "rock" or user_choice == "paper" or user_choice == "scissors":
print("Good choice, lets see who wins.")
time.sleep(1.5)
else:
print('Please enter either "rock", "paper", or "scissors"')
computer_choice = ["rock", "paper", "scissors"]
rand_choice = random.choice(computer_choice)
print("The computer chose", rand_choice)
if user_choice == "rock" and rand_choice == "scissors":
print("You won!")
elif user_choice == "scissors" and rand_choice == "rock":
print("The computer won, try again.")
elif user_choice == "paper" and rand_choice == "rock":
print("You won!")
elif user_choice == "rock" and rand_choice == "paper":
print("The computer won, try again")
elif user_choice == "scissors" and rand_choice == "paper":
print("You won!")
elif user_choice == "paper" and rand_choice == "scissors":
print("The computer won, try again")
RockPaperScissors()
I also have a slight issue with if you capitalize the first letter, the program does not run as intended. Appreciate the help!
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
I am making a small rock paper scissors program in python. The following code is functional. When I replace the "elif" with "if" the program is not completely functional (returns the else statement often) and I do not understand why. I am aware that elif should be used, but I still do not understand why using "if" is causing a loss in functionality. Thanks!
import random
game = ("rock", "paper", "scissors")
userchoice = str(input("rock, paper, or scissors?"))
while (userchoice == "rock" or "paper" or "scissors"):
computerchoice = random.choice(game)
if (computerchoice == "rock" and userchoice == "scissors"):
print("you lose",computerchoice,"beats",userchoice)
userchoice = str(input("try again, rock, paper, or scissors?"))
elif (computerchoice == "scissors" and userchoice == "paper"):
print("you lose",computerchoice,"beats",userchoice)
userchoice = str(input("try again, rock, paper, or scissors?"))
elif (computerchoice == "paper" and userchoice == "rock"):
print("you lose",computerchoice,"beats",userchoice)
userchoice = str(input("try again, rock, paper, or scissors?"))
elif (computerchoice == "rock" and userchoice == "paper"):
print("you win",userchoice,"beats",computerchoice)
userchoice = str(input("try again, rock, paper, or scissors?"))
elif (computerchoice == "scissors" and userchoice == "rock"):
print("you win",userchoice,"beats",computerchoice)
userchoice = str(input("try again, rock, paper, or scissors?"))
elif (computerchoice == "paper" and userchoice == "scissors"):
print("you win",userchoice,"beats",computerchoice)
userchoice = str(input("try again, rock, paper, or scissors?"))
elif (computerchoice == userchoice):
print("tie")
userchoice = str(input("try again, rock, paper, or scissors?"))
else:
print("what?")
userchoice = str(input("try again, rock, paper, or scissors?"))
If you change the elif to if the program won't work correctly
For example,
take 1st case if computerchoice is rock userchoice is scissors then it asks for input again. But now the execution continues from the next if statement ie
if (computerchoice == "scissors" and userchoice == "paper"):
So if you the same case comes again ie computerchoice is rock userchoice is scissors it wont check the first condition and execute else block.
For further explanation comment
Simple explanation to this is that if there are MULTIPLE if statements in a loop then ONLY the first occurrence of if/else statement is executed and the loop completes and continues the next loop without checking other if statements. Your program works correctly in case of elif statement is because, after the if statement program continues checking all other elif statements
To use if..else statement, you must change the code in this way:
import random
game = ("rock", "paper", "scissors")
userchoice = str(input("rock, paper, or scissors?"))
while (userchoice in game):
computerchoice = random.choice(game)
if (computerchoice == "rock" and userchoice == "scissors"):
print("you lose",computerchoice,"beats",userchoice)
userchoice = str(input("try again, rock, paper, or scissors?"))
else:
if (computerchoice == "scissors" and userchoice == "paper"):
print("you lose",computerchoice,"beats",userchoice)
userchoice = str(input("try again, rock, paper, or scissors?"))
else:
if (computerchoice == "paper" and userchoice == "rock"):
print("you lose",computerchoice,"beats",userchoice)
userchoice = str(input("try again, rock, paper, or scissors?"))
else:
if (computerchoice == "rock" and userchoice == "paper"):
print("you win",userchoice,"beats",computerchoice)
userchoice = str(input("try again, rock, paper, or scissors?"))
else:
if (computerchoice == "scissors" and userchoice == "rock"):
print("you win",userchoice,"beats",computerchoice)
userchoice = str(input("try again, rock, paper, or scissors?"))
else:
if (computerchoice == "paper" and userchoice == "scissors"):
print("you win",userchoice,"beats",computerchoice)
userchoice = str(input("try again, rock, paper, or scissors?"))
else:
if (computerchoice == userchoice):
print("tie")
userchoice = str(input("try again, rock, paper, or scissors?"))
else:
print("what?")
rockuserchoice = str(input("try again, rock, paper, or scissors?"))
I'm teaching myself python and one of my little starting projects is a Rock, Paper, Scissors game.
The code runs fine. I would like to add an extra feature though. Whenever a user enters Rock, Paper or Scissor the input remains in the terminal. That of course leads to some unfair circumstances for the second player.
In order to try to circumvent this, I'm using the getpass function. Unfortunately, after using getpass with P1inp and P2inp in my code, the input still remains on the terminal. Could anyone point out a better solution or nudge me in the right direction?
import sys
import getpass
rules = "Rules:Rock beats Scissors, Scissors beats Paper, and Paper beats Rock"
print(rules)
print("Would you like to play?")
decision = input("Yes or No?")
P1 = str(input("What's the name of Player 1?"))
P2 = str(input("What's the name of Player 2?"))
P1inp = getpass.getpass(input("%s, Rock, Paper or Scissors?"%P1))
P2inp = getpass.getpass(input("%s, Rock, Paper or Scissors?"%P2))
def play(decision):
if decision == "Yes":
compare(P1inp,P2inp)
else:
print("See you next time!")
def compare(P1inp,P2inp):
if P1inp == P2inp:
print("It's a tie!")
elif P1inp == "Rock" and P2inp == "Scissors":
print("%s wins!!"%P1)
elif P1inp == "Rock" and P2inp == "Paper":
print("%s wins!!"%P2)
elif P1inp == "Paper" and P2inp == "Scissors":
print("%s wins!!"%P2)
elif P1inp == "Paper" and P2inp == "Rock":
print("%s wins!!"%P1)
elif P1inp == "Scissors" and P2inp == "Rock":
print("%s wins!!"%P2)
elif P1inp == "Scissors" and P2inp == "Paper":
print("%s wins!!"%P1)
else:
return("Invalid input")
sys.exit()
print(compare(P1inp,P2inp))
print ("Would you like to play again?")
result = input("Yes or No?")
while result == "Yes":
samePlayers = input("Are P1 and P2 still the same?")
if samePlayers == "Yes":
P1inp = input("%s, Rock, Paper or Scissors?"%P1)
P2inp = input("%s, Rock, Paper or Scissors?"%P2)
play(result)
print(compare(P1inp,P2inp))
print ("Would you like to play again?")
result = input("Yes or No?")
else:
P1 = str(input("What's the name of Player 1?"))
P2 = str(input("What's the name of Player 2?"))
P1inp = input("%s, Rock, Paper or Scissors?"%P1)
P2inp = input("%s, Rock, Paper or Scissors?"%P2)
play(result)
print(compare(P1inp,P2inp))
print ("Would you like to play again?")
result = input("Yes or No?")
else:
print("Thanks for playing!")
In getpass.getpass() you should not also have input because Input asks for plain text.
P1inp = getpass.getpass(("%s, Rock, Paper or Scissors?"%P1))
P2inp = getpass.getpass(("%s, Rock, Paper or Scissors?"%P2))
I am creating a Rock, Paper, Scissors game. The game has a main menu which I need to be able to return to from each sub menu. I've tried a few different method I could think of as well as looked here and elsewhere online to determine a method of solving my problem.
I want the user to be able to select an option from the main menu, go to the selected sub menu, then be prompted with an option to return to the main menu. For example, Select the rules sub menu, then return to the main menu. Or, select to play a round of Rock, Paper, Scissors, then select to play again or return back to the main menu.
# random integer
from random import randint
# list for weapon
WEAPON = ["Rock", "Paper", "Scissors"]
# module to run the program
#def main():
# menu()
def main():
menuSelect = ""
print("\tRock, Paper, Scissors!")
# main menu
print("\n\t\tMain Menu")
print("\t1. See the rules")
print("\t2. Play against the computer")
print("\t3. Play a two player game")
print("\t4. Quit")
menuSelect = int(input("\nPlease select one of the four options "))
while menuSelect < 1 or menuSelect > 4:
print("The selection provided is invalid.")
menuSelect = int(input("\nPlease select one of the four options "))
if menuSelect == 1:
rules()
elif menuSelect == 2:
onePlayer()
elif menuSelect == 3:
twoPlayer()
elif menuSelect == 4:
endGame()
# display the rules to the user
def rules():
print("\n\t\tRules")
print("\tThe game is simple:")
print("\tPaper Covers Rock")
print("\tRock Smashes Scissors")
print("\tScissors Cut Paper")
print("")
# one player mode
def onePlayer():
again = ""
player = False
print("\n\tPlayer VS Computer")
while player == False:
player = input("\nSelect your weapon: Rock, Paper, or Scissors\n")
player = player.lower()
computer = WEAPON[randint(0,2)]
computer = computer.lower()
if player == computer:
print(player," vs ",computer)
print("It's a tie!\n")
elif player == "rock":
if computer == "paper":
print(player," vs ",computer)
print("Paper covers rock! You lose!\n")
else:
print("Rock smashes",computer,". You win!\n")
elif player == "paper":
if computer == "scissors":
print(player," vs ",computer)
print("Scissors cut paper! You lose!\n")
else:
print("Paper covers",computer,". You win!\n")
elif player == "scissors":
if computer == "rock":
print(player," vs ",computer)
print("Rock smashes scissors! You lose!\n")
else:
print("Scissors cut",computer,". You win!\n")
else:
print("invalid input")
again = input("Would you like to play again? Yes or no\n")
again = again.lower()
if again == "yes" or "y":
player = False
elif again == "no" or "n":
main()
# two player mode
def twoPlayer():
fight = False
player1 = ""
player2 = ""
print("\n\tPlayer VS Player")
while fight == False:
player1 = input("\nSelect your weapon: Rock, Paper, or Scissors\n")
player1 = player1.lower()
player2 = input("\nSelect your weapon: Rock, Paper, or Scissors\n")
player2 = player2.lower()
if player1 == player2:
print(player1," vs ",player2)
print("It's a tie!\n")
elif player1 == "rock":
if player2 == "paper":
print(player1," vs ",player2)
print("Paper covers rock! Player 2 wins!\n")
else:
print("Rock smashes",player2,". Player 1 wins!\n")
elif player1 == "paper":
if player2 == "scissors":
print(player1," vs ",player2)
print("Scissors cut paper! Player 2 wins!\n")
else:
print("Paper covers",player2,". Player 1 wins!\n")
elif player1 == "scissors":
if player2 == "rock":
print(player1," vs ",player2)
print("Rock smashes scissors! Player 2 wins!\n")
else:
print("Scissors cut",player2,". Player 1 wins!\n")
else:
print("invalid input")
again = input("Would you like to play again? Yes or no\n")
again = again.lower()
if again == "yes" or "y":
player = False
elif again == "no" or "n":
main()
def endGame():
print("Thank you for playing!")
main()
Currently my only test is within the onePlayer() module. The idea behind my code is to ask the user if they want to continue playing. If they don't want to continue playing, then I want the program to bring them back to the main menu.
You are using player variable for two works, instead of that you can use another variable to just check the condition and another to take user input.
Also you can check the condition like : if again in ["yes","y"]
def main():
menuSelect = ""
print("\tRock, Paper, Scissors!")
# main menu
print("\n\t\tMain Menu")
print("\t1. See the rules")
print("\t2. Play against the computer")
print("\t3. Play a two player game")
print("\t4. Quit")
menuSelect = int(input("\nPlease select one of the four options "))
while menuSelect < 1 or menuSelect > 4:
print("The selection provided is invalid.")
menuSelect = int(input("\nPlease select one of the four options "))
if menuSelect == 1:
rules()
elif menuSelect == 2:
onePlayer()
elif menuSelect == 3:
twoPlayer()
elif menuSelect == 4:
endGame()
# display the rules to the user
def rules():
print("\n\t\tRules")
print("\tThe game is simple:")
print("\tPaper Covers Rock")
print("\tRock Smashes Scissors")
print("\tScissors Cut Paper")
print("")
# one player mode
def onePlayer():
again = ""
player = False
print("\n\tPlayer VS Computer")
while player == False:
player = input("\nSelect your weapon: Rock, Paper, or Scissors\n")
player = player.lower()
#computer = WEAPON[randint(0,2)]
#temporary
computer = "paper"
computer = computer.lower()
if player == computer:
print(player," vs ",computer)
print("It's a tie!\n")
elif player == "rock":
if computer == "paper":
print(player," vs ",computer)
print("Paper covers rock! You lose!\n")
else:
print("Rock smashes",computer,". You win!\n")
elif player == "paper":
if computer == "scissors":
print(player," vs ",computer)
print("Scissors cut paper! You lose!\n")
else:
print("Paper covers",computer,". You win!\n")
elif player == "scissors":
if computer == "rock":
print(player," vs ",computer)
print("Rock smashes scissors! You lose!\n")
else:
print("Scissors cut",computer,". You win!\n")
else:
print("invalid input")
again = input("Would you like to play again? Yes or no\n")
again = again.lower()
if again=="yes" or again=="y":
player = False
else:
player = True
main()
main()
Do a try and except command. If they say no your code should be quit(). If they say yes put a continue command and it will restart the whole thing.
put your main method in a while (True): loop, and if option 4 is called, use break like this:
elif menuSelect == 4:
break
add an indent to
again = input("Would you like to play again? Yes or no\n")
again = again.lower()
if again == "yes" or "y":
player = False
else:
main()
and rather than calling main() just set player = True also, your Weapon array has not been defined. easy fix, just add WEAPON = ["rock", "paper", "scissors"] to the beginning of your onePlayer(): method. I can see another problem, change
if again == "yes" or "y":
to
if again == "yes" or again == "y":
one last thing, don't forget your imports! (put it at the top of your code.)
from random import randint
BTW, the break statement just tells python to leave whatever for loop or while loop it's in.