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
Related
I am looking for ways to shorten and simplify my python code. Here is one example of one small rock/paper/scissors game I wrote earlier. The code kinda looks too long to me and I want to try to learn how to shorten my code.
import random
user_wins = 0
comp_wins = 0
game_limit = 0
options = ["rock","paper","scissors"]
print("Welcome to Rock Paper Scissors, This is a Best of 5")
while True:
user_input = input("Type in Rock/Paper/Scissors or Q to quit: ").lower()
if user_input == "q":
break
elif user_input not in options:
print("type in a valid word next time")
continue
game_limit += 1
if game_limit == 5 and comp_wins > user_wins:
print("The game is over, YOU LOST!")
elif game_limit == 5 and comp_wins < user_wins:
print("The game is over, YOU WON!")
random_number = random.randint(0,2)
comp_input = options[random_number]
print("Computer picked", comp_input)
if user_input == "rock" and comp_input == "scissors":
print("You win")
user_wins += 1
elif user_input == "rock" and comp_input == "rock":
print("its a draw")
elif user_input == "rock" and comp_input == "paper":
print("You lose!")
comp_wins += 1
if user_input == "scissors" and comp_input == "paper":
print("You win")
user_wins += 1
elif user_input == "scissors" and comp_input == "scissors":
print("its a draw")
elif user_input == "scissors" and comp_input == "rock":
print("You lose!")
comp_wins += 1
if user_input == "paper" and comp_input == "rock":
print("You win")
user_wins += 1
elif user_input == "paper" and comp_input == "paper":
print("its a draw")
elif user_input == "paper" and comp_input == "scissors":
print("You lose!")
comp_wins += 1
Yes. You could simplify your logic by having compound and/or tests for the player and user. Following is a revised version of your code with some simplified logic.
import random
user_wins = 0
comp_wins = 0
game_limit = 0
options = ["rock","paper","scissors"]
print("Welcome to Rock Paper Scissors, This is a Best of 5")
while True:
if game_limit >= 5: # Tweak
if comp_wins > user_wins:
print("The game is over, YOU LOST!")
break
if comp_wins < user_wins:
print("The game is over, YOU WON!")
break
else:
print("We go to sudden death!")
user_input = input("Type in Rock/Paper/Scissors or Q to quit: ").lower()
if user_input == "q":
break
elif user_input not in options:
print("type in a valid word next time")
continue
game_limit += 1
random_number = random.randint(0,2)
comp_input = options[random_number]
print("Computer picked", comp_input)
if user_input == "rock" and comp_input == "scissors" or user_input == "paper" and comp_input == "rock" or user_input == "scissors" and comp_input == "paper":
print("You win")
user_wins += 1
elif user_input == "rock" and comp_input == "paper" or user_input == "paper" and comp_input == "scissors" or user_input == "scissors" and comp_input == "rock":
print("You lose!")
comp_wins += 1
else:
print("It's a draw")
This way all of the scenarios where the user can win are in one logical test and all of the scenarios where the computer can win are in another logical test. If neither test is true, then the default would have to be a draw.
Also, I tweaked game limit test because if the computer and user have the same score when the game limit is reached, the test result would be false and the game would then continue on and not stop. So there is a bit of additional code to handle a tie after five rounds.
Give that a try.
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")
I am attempting to make a basic rock, paper, scissors game. When I input either rock, paper, or scissors, I sometimes have to enter the same thing multiple times for it to continue to the if statements. See code below:
# Rock, Paper, Scissors
player_total = 0
computer_total = 0
def get_computer_hand():
choice = randint(1, 3)
if choice == 1:
return "scissors"
elif choice == 2:
return "paper"
else:
return "rock"
def ask_user():
global player_total
global computer_total
player = input("Enter your hand (stop to stop): ")
if player == "stop":
print("Computer had ", computer_total, "points, you had ", player_total, " points.")
exit(0)
computer = get_computer_hand()
if player == "rock":
if computer == "paper":
return "win"
elif computer == "scissors":
return "lose"
else:
return "tie"
elif player == "paper":
if computer == "paper":
return "tie"
elif computer == "scissors":
return "lose"
else:
return "win"
elif player == "scissors":
if computer == "scissors":
return "tie"
elif computer == "paper":
return "win"
else:
return "lose"
def count_winner():
global player_total
global computer_total
player_total = 0
computer_total = 0
while True:
outcome = ask_user()
if outcome == "win":
print("You won that one.")
player_total += 1
elif outcome == "lose":
print("Computer won that one.")
computer_total += 1
count_winner()
I expect it to work the first time and to continue as usual, but I can't seem to figure out why it just asks "Enter your hand (stop to stop): " instead sometimes when I enter either rock, paper, or scissors.
This is happening because there is a tie happening between the computer and the user. This could be fixed by adding the end with the code of
else outcome == "tie":
print("You have tied with the Computer!")
computer_total += 1
player_total += 1
This would add a point to both sides and if you don't want that just delete the last two lines of my code
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!")
as my homework (using codeskulptor.org) I put together a simple Rock-Paper-Scissors-Lizard-Spock 'game' in Python, where hard coded player's guesses were running the programme. Translation from name to number and other way round, random computer choice and printing... everything worked fine.
Then I tried to introduce input so that player gets to type their guess. However, the console prints only the log about wrong input but doesn't launch the rest of the programme if the input is actually correct... Tried various modifications, but I'm stuck... am I missing something obvious? Thanks!
import simplegui
import random
def get_guess(guess):
if guess == "rock":
return 0
elif guess == "Spock":
return 1
elif guess == "paper":
return 2
elif guess == "lizard":
return 3
elif guess == "scissors":
return 4
else:
print "Error guess_to_number:", guess, "is not a rpsls-element"
return
def number_to_name(number):
if number == 0:
return "rock"
elif number == 1:
return "Spock"
elif number == 2:
return "paper"
elif number == 3:
return "lizard"
elif number == 4:
return "scissors"
else:
print "Error number_to_name:", number, "is not in [0, 4]"
return
def rpsls(guess):
print
print "Player chooses", guess
player_number = get_guess(guess)
computer_number = random.randrange(5)
computer_choice = number_to_name(computer_number)
print "Computer chooses", computer_choice
diff_mod = (player_number - computer_number) % 5
if diff_mod == 0:
print "Player and computer tie!"
elif diff_mod == 1 or diff_mod == 2:
print "Player wins!"
else:
print "Computer wins!"
frame = simplegui.create_frame("GUI-based RPSLS", 200, 200)
frame.add_input("Enter guess for RPSLS", get_guess, 200)
frame.start()