Comparing user input to a randomly selected list item - Python - python

I am creating a Rock, Paper, Scissors game for a class. as part of the game I need to have a weapon menu display to the screen for the user to select from. Then the computer will randomly select a weapon from a list. The problem I am facing (I believe) is that the list items range from [0,2] where my menu items list [1,3]. I have searched around for hours, but I don't understand the complex things I have been reading online so I'm not certain how to apply them.
# random integer
from random import randint
# list for weapon
WEAPON = ["Rock", "Paper", "Scissors"]
# one player mode
def onePlayer():
scoreP = 0
scoreC = 0
again = ""
player = False
print("---------------------------------------------")
print("\n\tPlayer VS Computer")
while player == False:
print("Weapons:")
print("1. Rock")
print("2. Paper")
print("3. Scissors")
print("4. Quit")
player = input("\nSelect your weapon: ")
if player == "quit" or player == "q" or player == "4":
player = True
main()
else:
try:
player = int(player)
if player == 1:
player = WEAPON[0]
elif player == 2:
player = WEAPON[1]
elif player == 3:
player = WEAPON[2]
except:
print("please enter a number 1 through 4\n")
computer = WEAPON[randint(0,2)]
if player == computer:
print(player," vs ",computer)
print("It's a tie!\n")
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
elif player == 1:
# computer == paper
if computer == 1:
print(player," vs ",computer)
print("Paper covers rock! You lose!\n")
scoreC = scoreC + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
else:
print("Rock smashes scissors. You win!\n")
scoreP = scoreP + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
elif player == 2:
if computer == 2:
print(player," vs ",computer)
print("Scissors cut paper! You lose!\n")
scoreC = scoreC + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
else:
print("Paper covers rock. You win!\n")
scoreP = scoreP + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
elif player == 3:
if computer == 0:
print(player," vs ",computer)
print("Rock smashes scissors! You lose!\n")
scoreC = scoreC + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
else:
print("Scissors cut paper. You win!\n")
scoreP = scoreP + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
#else:
# print("Please select a valid play option\n")
player = False
Please don't mind the print statements inside the if/else statements. I realize these will need to be changed. My main issue is the logic of comparing user input to the computer's random list selection.

You need to be careful with the contents of your variables:
# this is storing a string
computer = WEAPON[randint(0,2)]
# this expects an integer
elif player == 1:
# computer == paper
if computer == 1:
That would be the root of some of the problems that you are seeing.
Also, in general, when coding try to use meaningful variable names and avoid reusing them for more than one purpose: In this case, two new variables like player_weapon and computer_weapon (instead of reusing player and computer) would have probably prevented your bug. Don't be lazy when declaring variables! ;)

In the if statements, it seems like you are comparing the variable computer, which is a string, to an integer. You assign computer = WEAPON[randint(0,2)], so computer is one of the following: ["Rock", "Paper", "Scissors"]. However, in your if statements, you are saying: if computer == 1: to compare it with the person (your person variable is the same way; you assign a string to it before you compare it to integers).
You just have to make sure you are comparing apples to apples

Compare to the strings, not to the numbers, like this
if player == computer:
print(player," vs ",computer)
print("It's a tie!\n")
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
elif player == 'Rock':
# computer == paper
if computer == 'Paper':
print(player," vs ",computer)
print("Paper covers rock! You lose!\n")
scoreC = scoreC + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
else:
print("Rock smashes scissors. You win!\n")
scoreP = scoreP + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
elif player == 'Paper':
if computer == 'Scissors':
print(player," vs ",computer)
print("Scissors cut paper! You lose!\n")
scoreC = scoreC + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
else:
print("Paper covers rock. You win!\n")
scoreP = scoreP + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
elif player == 'Scissors':
if computer == 'Rock':
print(player," vs ",computer)
print("Rock smashes scissors! You lose!\n")
scoreC = scoreC + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
else:
print("Scissors cut paper. You win!\n")
scoreP = scoreP + 1
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
#else:
# print("Please select a valid play option\n")
player = False

I have condensed a majority of your code by implementing a small dict_map. It could be condensed further but why bother.
# random integer
from random import randint
# list for weapon
WEAPON = ["Rock", "Paper", "Scissors"]
MAPP = {"Rock":{"Win":'Scissors', "Loss":"Paper", "Adj":"Smashes"},
"Paper":{"Win":"Rock", "Loss":"Scissors", "Adj":"Covers"},
"Scissors":{"Win":"Paper", "Loss":"Rock", "Adj":'Cuts'}}
def have_won(player, computer):
#determines if the players choice has beaten the computers
if MAPP[player]["Win"] == computer:
adj = MAPP[player]['Adj']
return True, ' '.join([player, adj, computer])
else:
adj = MAPP[computer]['Adj']
return False, ' '.join([computer, adj, player])
# one player mode
def onePlayer():
scoreP = 0
scoreC = 0
again = ""
player = False
print("---------------------------------------------")
print("\n\tPlayer VS Computer")
while player == False:
print("Weapons:")
print("1. Rock")
print("2. Paper")
print("3. Scissors")
print("4. Quit")
player = input("\nSelect your weapon: ")
if player == "quit" or player == "q" or player == "4":
player = True
else:
try:
player = int(player)
if player == 1:
player = WEAPON[0]
elif player == 2:
player = WEAPON[1]
elif player == 3:
player = WEAPON[2]
except:
print("please enter a number 1 through 4\n")
computer = WEAPON[randint(0,2)]
print player, computer
outcome = have_won(player, computer)
if player == computer:
print(player," vs ",computer)
print("It's a tie!\n")
print("Player:",scoreP,"\nComputer:",scoreC)
print("")
elif outcome[0] == True:
print(outcome[1]+"! You Win!!")
scoreP += 1
elif outcome[0] == False:
print(outcome[1]+"! You Lose!!")
scoreC += 1
#else:
# print("Please select a valid play option\n")
print("Player:",scoreP,"\nComputer:",scoreC)
player = False
onePlayer()

Related

Rock, paper, scissors game in Python - some clarification needed

I am writing a simple game of rock, paper and scissors, where the user competes with a computer. There are 5 tries.
The problems I ran into are :
If I enter something apart from three options, it should return "Invalid Entry". Instead, the program stops
The program never prints "You won the game" or "You lost the game", it finishes after 5 attempts
Other feedback would also be appreciated
import random
def game():
win_count = 0
loose_count = 0
tries = 0
while tries < 5:
chosen = input("Make your choice: ")
if chosen == "scissors" or chosen == "Scissors":
element = "scissors"
elif chosen == "paper" or chosen == "Paper":
element = "paper"
elif chosen == "rock" or chosen == "Rock":
element = "rock"
else:
return "Invalid Entry"
computer_choices = ["scissors", "paper", "rock"]
computer_choice = random.choice(computer_choices)
if element == "scissors" and computer_choice == "paper":
print("Computer chose paper, you chose scissors, you win !")
win_count += 1
tries += 1
elif element == "paper" and computer_choice == "scissors":
print("Computer chose scissors, you chose paper, you loose !")
loose_count += 1
tries += 1
elif element == "paper" and computer_choice == "rock":
print("Computer chose rock, you chose paper, you win !")
win_count += 1
tries += 1
elif element == "rock" and computer_choice == "paper":
print("Computer chose paper, you chose rock, you loose !")
loose_count += 1
tries += 1
else:
print("Whoops, that's a draw, try again")
tries+=1
print("Your Wins: "+ str(win_count))
print("Computer Wins: "+str(loose_count))
if win_count > loose_count:
return "Congrats, you won the game!"
else:
return "Sorry, you lost"
game()
return statement does not print anything but they return the value from a function and as soon as a return statement executes the function ends up executing that's why whenever the user inputs something invalid the program stop.
Also not use the if statement from if chosen = paper or chosen = Paper instead use .lower() to lower the string.
I have made some changes to your code.
Try this code
import random
def game():
win_count = 0
loose_count = 0
tries = 0
while tries < 5:
element = input("Make your choice: ").lower()
computer_choices = ["scissors", "paper", "rock"]
if element not in computer_choices:
print("Invalid choice")
continue
computer_choice = random.choice(computer_choices)
if element == "scissors" and computer_choice == "paper":
print("Computer chose paper, you chose scissors, you win !")
win_count += 1
tries += 1
elif element == "paper" and computer_choice == "scissors":
print("Computer chose scissors, you chose paper, you loose !")
loose_count += 1
tries += 1
elif element == "paper" and computer_choice == "rock":
print("Computer chose rock, you chose paper, you win !")
win_count += 1
tries += 1
elif element == "rock" and computer_choice == "paper":
print("Computer chose paper, you chose rock, you loose !")
loose_count += 1
tries += 1
else:
print("Whoops, that's a draw, try again")
tries+=1
print("Your Wins: "+ str(win_count))
print("Computer Wins: "+str(loose_count))
if win_count > loose_count:
print("Congrats, you won the game!")
else:
print("Sorry, you lost")
game()

How can I store a number while using multiple if statements?

I am creating a python code for rock, paper, scissors but I can't seem to keep track of the score of wins, losses, and ties. I think there is something wrong with my "count" which i called "win += 0", "lose += 0" and "tie += 0." Could someone please tell me what I should do to increase the score by 1 every time there is a win, lose or tie?
Here is my code below:
from random import randint
t = ["rock", "paper", "scissors"]
computer = t[randint(0,2)]
player = False
lose = 0
win = 0
for i in range(0,10):
print("1... 2... 3... go!")
while player == False:
player = input("rock, paper, scissors: ")
print("Computer: ", computer)
print("User: ", player)
if player == computer:
tie = 0
tie +=1
print("Tie!")
elif player == "rock":
if computer == "paper":
lose +=0
print("You lose!")
else:
win +=0
print("You win!")
elif player == "paper":
if computer == "scissors":
lose = 0
lose +=0
print("You lose!")
else:
win +=0
print("You win!")
elif player == "scissors":
if computer == "rock":
lose +=0
print("You lose!")
else:
win +=0
print("You win!")
else:
print("That's not a valid play. Check your spelling!")
player = False
computer = t[randint(0,2)]
break
print("Final Tally")
print("************")
print("User Wins: ", win)
print("Computer Wins: ", lose)
print("Ties: ", tie)
if tie > win and tie > lose:
print("It's a tie!")
elif win > tie and win > lose:
print("You won!")
else:
print("The computer won!")
Here's the fixed version. I suggest you work on it some more :)
from random import choice
t = ["rock", "paper", "scissors"]
tie = 0
lose = 0
win = 0
for i in range(0, 10):
print("1... 2... 3... go!")
# you need to refresh these variables on every for iteration
computer = choice(t)
player = None
# if you're using while to make sure player inputs, that's the only thing that needs
# to be within the while loop
while not player:
player = input("rock, paper, scissors: ")
print("Computer: ", computer)
print("User: ", player)
# I would look for a way to simplify determining the winner
if player == computer:
# tie += 1 is the same as tie = tie + 1
tie +=1
print("Tie!")
elif player == "rock":
if computer == "paper":
lose += 1
print("You lose!")
else:
win += 1
print("You win!")
elif player == "paper":
if computer == "scissors":
lose += 1
print("You lose!")
else:
win += 1
print("You win!")
elif player == "scissors":
if computer == "rock":
lose += 1
print("You lose!")
else:
win += 1
print("You win!")
else:
print("That's not a valid play. Check your spelling!")
print("Final Tally")
print("************")
print("User Wins: ", win)
print("Computer Wins: ", lose)
print("Ties: ", tie)
if tie > win and tie > lose:
print("It's a tie!")
elif win > tie and win > lose:
print("You won!")
else:
print("The computer won!")
UPDATE: Apparently I have nothing to do. So ok, here's a straightforward way to simplify win conditioning.
win_condition_rock = player == 'rock' and computer == 'scissors'
win_condition_paper = player == 'paper' and computer == 'rock'
win_condition_scissors = player == 'scissors' and computer == 'paper'
if player == computer:
# tie += 1 is the same as tie = tie + 1
tie +=1
print("Tie!")
elif any([win_condition_paper, win_condition_scissors, win_condition_rock]):
win += 1
print('You win')
else:
lose += 1
print('You lose')
UPDATE 2: And here's a check for valid input
while player not in t:
player = input("rock, paper, scissors: ").lower()
if player not in t:
print('Invalid input')

Variable not registering change in value

I wanted to make a simple Rock, Paper, Scissor game in Python. It goes well with the game, but the final scores are always being showed as a 0.
I wanted to show a smaller section of the code but, I don't know where the problem lies, so I am sorry for the length of the code.
I am still a novice learner, so please pardon me if the question is too silly or the code is not well formatted.
#Rock-Paper-Scissor Game
import random
print("Please enter your name:")
userName = input()
print("Welcome " + userName)
print("The following are the rules of the game:")
print("Press 'R' for Rock")
print("Press 'P' for Paper")
print("Press 'S' for Scissor")
print("This will be a 10 point match")
userTally = 0
compTally = 0
def gameProcess(userTally, compTally): #The process of the game. It increments or decrements the value depending on the result
print("Your turn:")
userInput = input()
computerChoice = random.choice(["R","P","S"])
if userInput == "R": #User Inputs R for Rock
if computerChoice == "R":
print("The computer chose Rock")
print("It's a Tie")
elif computerChoice == "P":
print("The computer chose Paper")
print("Computer Won")
compTally = compTally + 1
elif computerChoice == "S":
print("The computer chose Scissor")
print("You Won")
userTally = userTally + 1
elif userInput == "P": #User Inputs P for Paper
if computerChoice == "R":
print("The computer chose Rock")
print("You Won")
userTally = userTally + 1
elif computerChoice == "P":
print("The computer chose Paper")
print("It's a Tie")
elif computerChoice == "S":
print("The computer chose Scissor")
print("Computer Won")
compTally = compTally + 1
elif userInput == "S": #User Inputs S for Scissor
if computerChoice == "R":
print("The computer chose Rock")
print("Computer Won")
compTally = compTally + 1
elif computerChoice == "P":
print("The computer chose Paper")
print("You Won")
userTally = userTally + 1
elif computerChoice == "S":
print("The computer chose Scissor")
print("It's a Tie")
return(userTally,compTally)
def tryCount(): #The number of tries....
tryNum = 1
while tryNum < 11:
gameProcess(0, 0)
tryNum = tryNum + 1
tryCount()
print("You scored " + str(userTally))
print("The computer scored " + str(compTally))
if userTally > compTally:
print("CONGRATULATIONS, YOU WON.")
elif userTally < compTally:
print("Sorry, better luck next time.")
close = input()
if close == "Random Input.":
exit()
else:
exit()
You pass 0, 0 to gameProcess, which you treat as the scores within the function, and then return them modified, but you do not actually use the return value in the only place you call gameProcess (in tryCount), so the global userTally, compTally variables remain unchanged.
This is how you should change tryCount:
def tryCount(): #The number of tries....
global userTally, compTally
tryNum = 1
while tryNum < 11:
userTally,compTally=gameProcess(userTally,compTally)
tryNum = tryNum + 1

NameError: free variable 'player_one_rps' referenced before assignment in enclosing scope

I'm quite new to coding, and I've been trying to make a text-based game with a menu. The game itself works fine, but once I try to incorporate a menu, i get the error "NameError: free variable 'player_one_rps' referenced before assignment in enclosing scope".
I have been googling it like a mad for some time now, but the few answers I find uses too advanced code for me to understand it yet.
(I tried changing the scopes and indents, I tried calling different functions at different indents, I tried assigning an argument to the functions, also, to have the main menu as the last function in the code – the list goes on..)
Here is the code for the menu and game option 1:
def main():
print("\t\t*** Welcome to this totally adequate game! ***")
def game_menu():
"""Displays game menu and prompts user for input"""
menu_choice = input("""What do you want to do?
1 - One player: rock, paper, scissor, lizard, spock
2 - Two player: rock, paper, scissor, lizard, spock
3 - Surprise! Bonus feature
4 - User guide
5 - Quit
Enter the menu number to access: """)
while True:
if menu_choice == "1":
print("One player: rock, paper, scissor, lizard, spock")
player_one_rps()
break
elif menu_choice == "2":
print("Two player: rock, paper, scissor, lizard, spock")
player_two_rps()
break
elif menu_choice == "3":
print("Surprise! Bonus feature")
dad_jokes()
break
elif menu_choice == "4":
print("User guide")
user_info()
elif menu_choice == "5":
print("Quit game")
exit()
elif menu_choice != 1 - 5:
print("Error, choose a valid number")
# print(menu_choice)
game_menu()
main()
# First game
def player_one_rps():
"""One player rock, paper, scissor, lizard, spock - game"""
import random
def instructions():
"""Displays menu and simple instructions on how to play"""
print("Welcome to rock, paper, scissor, lizard, spock!")
play = input("\nNavigate by \"yes\", \"no\", and numbers.\nNew game?:").lower()
if play == "yes":
print("1. Rock")
print("2. Paper")
print("3. Scissors")
print("4. Lizard")
print("5. Spock")
elif play != "no":
print("an error has occured. Please type \"yes\" or \"no\":")
instructions()
def get_user_choice():
"""Prompts the player to pick a 'weapon'"""
choice = int(input("What do you choose?: "))
if choice > 5:
print("Invalid number, please try again....")
get_user_choice()
elif choice < 1:
print("Invalid number, please try again....")
get_user_choice()
elif choice == 1:
print("You chose rock")
elif choice == 2:
print("You chose paper")
elif choice == 3:
print("You chose scissor")
elif choice == 4:
print("You chose lizard")
elif choice == 5:
print("You chose spock")
return choice
def get_pc_choice():
"""The computer chooses a random weapon"""
choice = random.randint(1, 5)
if choice == 1:
print("PC chose rock")
elif choice == 2:
print("PC chose paper")
elif choice == 3:
print("PC chose scissor")
elif choice == 4:
print("PC chose lizard")
elif choice == 5:
print("PC chose spock")
return choice
def winner(user_choice, pc_choice, user_wins, pc_wins, ties):
"""Calculates if the player or computer won the match"""
if user_choice == 1 and pc_choice == 3 or pc_choice == 4:
print("\nYou win.")
user_wins = user_wins.append(1)
elif user_choice == 2 and pc_choice == 1 or pc_choice == 5:
print("\nYou win.")
user_wins = user_wins.append(1)
elif user_choice == 3 and pc_choice == 2 or pc_choice == 4:
print("\nYou win.")
user_wins = user_wins.append(1)
elif user_choice == 4 and pc_choice == 2 or pc_choice == 5:
print("\nYou win.")
user_wins = user_wins.append(1)
elif user_choice == 5 and pc_choice == 1 or pc_choice == 3:
print("\nYou win.")
user_wins = user_wins.append(1)
elif user_choice == pc_choice:
print("\nTie")
ties = ties.append(1)
else:
print("\nPC won")
pc_wins = pc_wins.append(1)
return
def game_total(user_wins, pc_wins, ties):
"""Displays the total score"""
user_wins = sum(user_wins)
pc_wins = sum(pc_wins)
ties = sum(ties)
print("Your final score: ", user_wins)
print("PC\'s final Score: ", pc_wins)
print("Total ties: ", ties)
def main_one_p():
"""Main instructions for how the game runs"""
user_choice = 0
user_wins = []
pc_choice = 0
pc_wins = []
ties = []
final_user_wins = 0
final_pc_wins = 0
final_ties = 0
Continue = "yes"
instructions()
while Continue == "yes":
user_choice = get_user_choice()
pc_choice = get_pc_choice()
winner(user_choice, pc_choice, user_wins, pc_wins, ties)
Continue = input("Would you like to play again: ").lower()
if Continue == "no":
print("This is the final scores.")
break
game_total(user_wins, pc_wins, ties)
main_one_p()
player_one_rps()
game_menu() # Returns player to the main menu
(sorry if it is quite long)
Could anyone help point me in the direction of my mistake? Explanations and tips on how to fix it would also be greatly appreciated :)
In general, I'm thankful for all feedback, as i really want to become better at coding.
The global function must have a higher declarative code than where it is called. Simply reposition the function. The function game_menu must be below the function play_one_rps. The other functions are the same.

Returning to the main menu in my game - Python

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.

Categories

Resources