Just need this for a game program. At the end of the Rock-Paper-Scissors program it asks if the user wants to play again or not, and uses sys.exit() to terminate the program. However, instead of terminating the program if the user enters something that isn't 'Y' or 'y' in the replayFunc() function, it goes into the code under the except: block in main(). Any help is appreciated.
import random
import os
import sys
userOS = str(sys.platform)
def clearFunc():
if "win32" not in userOS:
os.system('clear')
else:
os.system('cls')
def replayFunc():
exitPrompt = input("Do you want to play again? (Y/N): ")
if exitPrompt == 'Y' or exitPrompt == 'y':
main()
else:
sys.exit(0)
def main():
oppChoice = random.randint(1,3)
playerChoice = int
print("Welcome to Rock-Paper-Scissors!")
input("\nPress Enter to continue: ")
clearFunc()
try:
playerChoice = int(input("Please use 1-3 to select from the list below:\n\n1. Rock\n2. Paper\n3. Scissors\n"))
if playerChoice == 1 and oppChoice == 1:
print("You tied!")
replayFunc()
elif playerChoice == 1 and oppChoice == 2:
print("Computer Wins!")
replayFunc()
elif playerChoice == 1 and oppChoice == 3:
print("You win!")
replayFunc()
elif playerChoice == 2 and oppChoice == 1:
print("You win!")
replayFunc()
elif playerChoice == 2 and oppChoice == 2:
print("You tied!")
replayFunc()
elif playerChoice == 2 and oppChoice == 3:
print("Computer Wins!")
replayFunc()
elif playerChoice == 3 and oppChoice == 1:
print("Computer wins!")
replayFunc()
elif playerChoice == 3 and oppChoice == 2:
print("You win!")
replayFunc()
elif playerChoice == 3 and oppChoice == 3:
print("You tied!")
replayFunc()
else:
print("Didn't get that")
main()
except:
print("TypeError")
main()
main()
sys.exit(0) is basically implemented as raise SystemExit(0). It's an exception, because you need to bubble up so context managers (with statements) and finally blocks can clean up properly.
The reason bare except: is frowned upon is because it catches even exceptions that shouldn't be caught, e.g. SystemExit. So stop using it, and catch only exceptions you know how to handle, or at least change it to except Exception: which won't catch the special, shouldn't be caught exceptions (like SystemExit and KeyboardInterrupt).
Related
I made a simple rock paper scissors game in python to learn. Everything is working except the last else statement. I simply want to check if none of the previous if statements are true then it prints out 'not a valid command' but for some reason it prints it out regardless what i type. Must be something very basic I'm missing but I just can't see it.
import random
while True:
cpu_choice = random.randint(0, 2)
cpu = ["Rock", "Paper", "Scissors"]
print("Pick Rock,Paper or Scissors")
choice = input("")
if choice.capitalize() == "Paper":
if cpu_choice == 2:
print("You lose")
elif cpu_choice == 1:
print("Tied!")
else:
print("You won!")
if choice.capitalize() == "Rock":
if cpu_choice == 1:
print("You lose")
elif cpu_choice == 0:
print("Tied!")
else:
print("You won!")
if choice.capitalize() == "Scissors":
if cpu_choice == 0:
print("You lose")
elif cpu_choice == 2:
print("Tied!")
else:
print("You won!")
if choice.capitalize() == "Exit":
print("Exiting...")
break
else:
print("Not a valid command")
print("Computer picked: " + cpu[cpu_choice])
Your else statement will run whenever choice.capitalize() == "Exit" evaluates to False. You need to turn all your other if statements into elif statements to treat it all as one if/elif/else block.
if choice.capitalize() == "Paper":
...
elif choice.capitalize() == "Rock":
...
elif choice.capitalize() == "Scissors":
...
elif choice.capitalize() == "Exit":
...
else:
print("Not a valid command")
Before anyone marks this question as a duplicate of anyone else's relating to this type of program, know that I searched and read the answered questions on this topic and was unable to find anything that suits my needs.
In my program for rock, paper, scissors I am asked to figure out if the computer or the player wins, or if they tie. We are supposed to store computer win as -1, player win as 1, and tie as 0. I thought I wrote this function correctly and called it properly in my main function, however, when I run my code it skips right over my runGame function and instead skips to an infinite loop asking the player to input their choice. I do not know why this is happening. I should note that within my main function, we are supposed to keep a counter to see how many wins the computer has and the player has, and how many times they tie. I also am having difficulty getting this to execute.
import random
# Function: Display Menu
# Input: none
# Output: none
# displays the game rules to the user
def displayMenu():
print("Welcome! Let's play rock, paper, scissors.")
print("The rules of the game are:")
print("\tRock smashes scissors")
print("\tScissors cut paper")
print("\tPaper covers rock")
print("\tIf both the choices are the same, it's a tie")
# Function: Get Computer Choice
# Input: none
# Output: integer that is randomly chosen, a number between 0 to 2
def getComputerChoice():
computerChoice = random.randrange(0,3)
return computerChoice
# Function: Get Player Choice
# Input: none
# Output: integer that represents the choice
# Asks the user for their choice: 0 for rock, 1 for paper, or 2 for scissors
def getPlayerChoice():
playerChoice = int(input("Please choose (0) for rock, (1) for paper or (2) for scissors"))
return playerChoice
# Function: Play Round
# Input: two integers--one representing the computer's choice and the other representing the player's choice
# Output: integer (-1 if computer wins, 1 if player wins, 0 if there is a tie)
# This method contains the game logic so it stimulates the game and determines a winner
def playRound(computerChoice, playerChoice):
if playerChoice == 0 and computerChoice == 2:
return 1
elif computerChoice == 0 and playerChoice == 2:
return -1
elif playerChoice == 2 and computerChoice == 1:
return 1
elif computerChoice == 2 and playerChoice == 1:
return -1
elif playerChoice == 1 and computerChoice == 0:
return 1
elif computerChoice == 1 and playerChoice == 0:
return 1
else:
return 0
# Function: Continue Game
# Input: none
# Output: boolean
# Ask the user is they want to continue (Y/N), and then return True or False accordingly
def continueGame():
playAgain = input("Do you want to continue playing? Enter (y) for yes or (n) for no.")
if playAgain.lower() == "y":
return True
elif playAgain.lower() == "n":
return False
# Function: main
# Input: none
# Output: none
def main():
playerCounter = 0
computerCounter = 0
tieCounter = 0
displayMenu()
p_choice = getPlayerChoice()
if p_choice == 0:
choicePlayer = "rock"
elif p_choice == 1:
choicePlayer = "paper"
elif p_choice == 2:
choicePlayer = "scissors"
getComputerChoice()
c_choice = getComputerChoice()
if c_choice == 0:
choiceComputer = "rock"
elif c_choice == 1:
choiceComputer = "paper"
elif c_choice == 2:
choiceComputer = "scissors"
print("You chose", choicePlayer + ".")
print("The computer chose", choiceComputer + ".")
playRound(getComputerChoice(), getPlayerChoice())
while playRound(c_choice, p_choice) == -1:
computerCounter += 1
while playRound(getPlayerChoice(), getPlayerChoice()) == 1:
playerCounter += 1
while playRound(getPlayerChoice(), getPlayerChoice()) == 0:
tieCounter += 1
continueGame()
while continueGame() == True:
displayMenu()
getPlayerChoice()
getComputerChoice()
playRound(getComputerChoice(), getPlayerChoice())
continueGame()
while continueGame() == False:
print()
print("You won", playerCounter, "game(s).")
print("The computer won", computerCounter, "game(s).")
print("You tied with the computer", tieCounter, "time(s).")
print()
print("Thanks for playing!")
# Call Main
main()
You don't have a "runGame" method, I believe you are referring to playRound.
In that case, once again, in this line:
playRound(getComputerChoice(), getPlayerChoice())
You are calling the getComputerChoice() and getPlayerChoice() methods again, and this is not what you want. Because of that it is asking you for the input again. You should do:
playRound(c_choice, p_choice)
There are some issues with your code. Firstly, you unnecessary call getComputerChoice(), getPlayerChoice() and continueGame() functions multiple times when it is not needed. Secondly, you have multiple weird while loops that don't do what you actually think they do.
Here is how you can modify your function in order to have a working program.
def main():
playerCounter = 0
computerCounter = 0
tieCounter = 0
displayMenu()
next_game = True
while next_game:
p_choice = getPlayerChoice()
if p_choice == 0:
choicePlayer = "rock"
elif p_choice == 1:
choicePlayer = "paper"
elif p_choice == 2:
choicePlayer = "scissors"
c_choice = getComputerChoice()
if c_choice == 0:
choiceComputer = "rock"
elif c_choice == 1:
choiceComputer = "paper"
elif c_choice == 2:
choiceComputer = "scissors"
print("You chose", choicePlayer + ".")
print("The computer chose", choiceComputer + ".")
result = playRound(p_choice, c_choice)
if result == -1:
computerCounter += 1
elif result == 0:
tieCounter += 1
else:
playerCounter += 1
next_game = continueGame()
print("You won", playerCounter, "game(s).")
print("The computer won", computerCounter, "game(s).")
print("You tied with the computer", tieCounter, "time(s).")
print()
print("Thanks for playing!")
In my programming class we are to make a Rock, Paper, Scissors Game that can load previous saves of the game, display the statistics of the game, and allow the user to continue playing if desired. I have a good chunk of the program created, I just need help with the loading of the file as I just get an endless loop of "What is your name?". My code is below and any help would be appreciated!
#Rock, Paper, Scissors Program
#A menu-based RPS program that keeps stats of wins, losses, and
ties
#12/2/18
import sys, os, random, pickle
#Functions
def print_menu():
print("\n1. Start New Game")
print("2. Load Game")
print("3. Quit")
def print_roundmenu():
print("What would you like to do?")
print("\n1. Play Again")
print("2. View Statistics")
print("3. Quit")
def start_game(username, playing):
print("Hello", username + ".", "let's play!")
playAgain = play_game()
if playAgain == True:
playing = True
elif playAgain == False:
playing = False
return playing
def play_game():
roundNo = 1
wins = 0
losses = 0
ties = 0
playing_round = True
while playing_round:
print("Round number", roundNo)
print("1. Rock")
print("2. Paper")
print("3. Scissors")
roundNo += 1
choices = ["Rock", "Paper", "Scissors"]
play = get_choice()
comp_idx = random.randrange(0,2)
comp_play = choices[comp_idx]
print("You chose", play, "the computer chose",
comp_play+".")
if (play == comp_play):
print("It's a tie!")
ties += 1
print_roundmenu()
gameFile.write(str(ties))
elif (play == "Rock" and comp_play == "Scissors" or play == "Paper" and comp_play == "Rock" or play == "Scissors" and comp_play == "Paper"):
print("You win!")
wins += 1
print_roundmenu()
gameFile.write(str(wins))
elif (play == "Scissors" and comp_play == "Rock" or play == "Rock" and comp_play == "Paper" or play == "Paper" and comp_play == "Scissors"):
print("You lose!")
losses += 1
print_roundmenu()
gameFile.write(str(losses))
response = ""
while response != 1 and response != 2 and response != 3:
try:
response = int(input("\nEnter choice: "))
except ValueError:
print("Please enter either 1, 2, or 3.")
if response == 1:
continue
elif response == 2:
print(username, ", here are your game play statistics...")
print("Wins: ", wins)
print("Losses: ", losses)
print("Ties: ", ties)
print("Win/Loss Ratio: ", wins, "-", losses)
return False
elif response == 3:
return False
def get_choice():
play = ""
while play != 1 and play != 2 and play != 3:
try:
play = int(input("What will it be? "))
except ValueError:
print("Please enter either 1, 2, or 3.")
if play == 1:
play = "Rock"
if play == 2:
play = "Paper"
if play == 3:
play = "Scissors"
return play
playing = True
print("Welcome to the Rock Paper Scissors Simulator")
print_menu()
response = ""
while playing:
while response != 1 and response != 2 and response != 3:
try:
response = int(input("Enter choice: "))
except ValueError:
print("Please enter either 1, 2, or 3.")
if response == 1:
username = input("What is your name? ")
gameFile = open(username + ".rps", "w+")
playing = start_game(username, playing)
elif response == 2:
while response == 2:
username = input("What is your name? ")
try:
gameFile = open("username.rps", "wb+")
pickle.dump(username, gameFile)
except IOError:
print(username + ", your game could not be found.")
elif response ==3:
playing = False
This code block:
while response == 2:
username = input("What is your name? ")
try:
gameFile = open("username.rps", "wb+")
pickle.dump(username, gameFile)
except IOError:
print(username + ", your game could not be found.")
will repeat infinitely unless you set response to something other than 2. Notice here that all you're doing in this block is (1) asking for username, (2) opening the file, and (3) dumping the file contents with pickle. You're not actually starting the game, like you are in the if response == 1 block. So the same prompt keeps repeating infinitely.
A good thing to do in these situations is to manually step through your code by hand - "what did I do to get here, and what is happening as a result of that?"
I'm coming up with a simple piece of code to play a game of rock, paper, stick and stones using input and random functions. In the code below, I'm trying to figure out how to loop my_input if the user enters an integer that is not a valid choice.
import random
import time
def my_input():
#validinput = False
#while not validinput:
while True:
try:
mychoice = int(input("Your choice? (1. paper, 2. scissor, 3. stick or 4. stone) "))
except ValueError:
print('You did not enter a valid input. Enter again.')
continue
else:
if mychoice == 1:
return 'paper'
elif mychoice == 2:
return 'scissor'
elif mychoice == 3:
return 'stick'
elif mychoice == 4:
return 'stone'
else:
return 'invalid choice'
def randomized():
choice = ['paper', 'scissor', 'stick', 'stone']
return random.choice(choice)
def game():
user_continue = True
while user_continue:
myinput = my_input()
print('YOU: ' + str(myinput))
randomval = randomized()
time.sleep(1)
print('COMPUTER: ' + randomval)
won = 'You won!'
lost = 'Sorry, you lost.'
draw = "It's a draw."
if myinput == 'paper' and randomval == 'scissor':
time.sleep(1)
print(lost)
elif myinput == 'scissor' and randomval == 'paper':
time.sleep(1)
print(won)
elif myinput == 'paper' and randomval == 'stick':
time.sleep(1)
print(lost)
elif myinput == 'stick' and randomval == 'paper':
time.sleep(1)
print(won)
elif myinput == 'paper' and randomval == 'stone':
time.sleep(1)
print(won)
elif myinput == 'stone' and randomval == 'paper':
time.sleep(1)
print(lost)
elif myinput == 'scissor' and randomval == 'stick':
time.sleep(1)
print(lost)
elif myinput == 'stick' and randomval == 'scissor':
time.sleep(1)
print(won)
elif myinput == 'scissor' and randomval == 'stone':
time.sleep(1)
print(lost)
elif myinput == 'stick' and randomval == 'stone':
time.sleep(1)
print(lost)
elif myinput == 'stone' and randomval == 'stick':
time.sleep(1)
print(won)
else:
print(draw)
#continue looping until user says no
user_yn = str.upper(input('Do you want to continue? Press Enter or type any value other than N '))
if user_yn != 'N':
print('continuing...')
continue
else:
break
game()
Any other suggestion to make this code shorter would be greatly appreciated.
You are almost there.
Short Answer:
Replace return 'invalid choice' with print('invalid choice') This works.
Explination:
After comparing the entered input value with the desired values of 1 to 4, you are returning from the infinite loop with return statement. If the value is the desired one, this works, but even for invalid values you are exiting with return 'invalid value'. So instead of returning it, print the same message to the user, and as it is in infinite while loop the menu prints again prompting the user to input his choice again. This won't exit the loop until the user enters the desired value between 1 to 4.
You could use a dictionary for mychoice:
mychoice = {1:"paper", 2:"scissors", 3:"stick"}
that would condense some. also would help with your randomized function
I am creating a rock paper scissors lizard spock game in Python for my class and i am trying to figure out why whatever choice I make I am always winning even though I set up all my if statements correct. `
import random
def instructions():
play = input("Would you like to play Rock, Paper, Scissors, Lizard, Spock(y/n): ").lower()
if play == "y":
print("1.Rock")
print("2.Paper")
print("3.Scissors")
print("4.Lizard")
print("5.Spock")
elif play != "n":
print("error has accured please type y for yes or n for no:")
instructions()
def getPlayerChoice():
choice = int(input("What is your choice user?: "))
if choice > 5:
print("Invalid number please try again....")
getPlayerChoice()
elif choice < 1:
print("Invalid number please try again....")
getPlayerChoice()
elif choice == 1:
print("You picked Rock")
elif choice == 2:
print("You picked Paper")
elif choice == 3:
print("You picked Scissors")
elif choice == 4:
print("You picked Lizard")
elif choice == 5:
print("You picked Spock")
return choice
def getCPUChoice():
choice = random.randint(1,5)
if choice == 1:
print("CPU picked Rock")
elif choice == 2:
print("CPU picked Paper")
elif choice == 3:
print("CPU picked Scissors")
elif choice == 4:
print("CPU picked Lizard")
elif choice == 5:
print("CPU picked Spock")
return choice
def winner(playerChoice, CPUChoice, playerWins, CPUWins, ties):
if playerChoice == 1 and CPUChoice == 3 or CPUChoice == 4:
print("Player wins.")
playerWins = playerWins.append(1)
elif playerChoice == 2 and CPUChoice == 1 or CPUChoice == 5:
print("Player wins.")
playerWins = playerWins.append(1)
elif playerChoice == 3 and CPUChoice == 2 or CPUChoice == 4:
print("Player wins.")
playerWins = playerWins.append(1)
elif playerChoice == 4 and CPUChoice == 2 or CPUChoice == 5:
print("Player wins.")
playerWins = playerWins.append(1)
elif playerChoice == 5 and CPUChoice == 1 or CPUChoice == 3:
print("Player wins.")
playerWins = playerWins.append(1)
elif playerChoice == CPUChoice:
print("Tie")
ties = ties.append(1)
else:
print("CPU won")
CPUWins = CPUWins.append(1)
return
def gameTotal(playerWins, CPUWins, ties):
playerWins = sum(playerWins)
CPUWins = sum(CPUWins)
ties = sum(ties)
print("Player final score: ", playerWins)
print("CPU final Score: ", CPUWins)
print("Total ties: ",ties)
def main():
playerChoice = 0
playerWins = []
CPUChoice = 0
CPUWins = []
ties = []
finalPlayerWins = 0
finalCPUWins = 0
finalTies = 0
Continue = 'y'
instructions()
while Continue == 'y':
playerChoice = getPlayerChoice()
CPUChoice = getCPUChoice()
winner(playerChoice,CPUChoice,playerWins, CPUWins, ties)
Continue = input("Would you like to play again (y/n):").lower()
if Continue == 'n':
print("Printing final scores.")
break
gameTotal(playerWins, CPUWins, ties)
main()
`
To summarize all of the things you should pay attention to:
boolean conditions - the result changes with the parentheses that are inside the condition.
if True or (True and False) --> this basically calculates the True and False part first (like in regular math) and then you have True or False which evaluates to True.
if True or True and False --> this basically calculates the True or True part first (like in regular math) and then you have True and False which evaluates to False - because you don't use parentheses.
Do not call a function within the same function - this is called recursion, and it's not relevant for what you need. Use a while loop, that runs as long as i.e. - you didn't get a proper choice input (while choice!='n' and choice!='y':).
Your instructions choice - the choice made by the user doesn't really change the flow of the game. the game starts also if the user entered no. You should add an exit statement in the instructions function.
The reason is you are missing parentheses on all of the "if" conditions.
if False and True or True # =True
if False and (True or False) # =False