If statements not correctly printing - python-3.x

I am not sure as to why but for the if statements it does not correctly print the messages. Whenever I run the program it only runs the else statement but not the rest of the if statements
import random
import sys
def main():
while True:
aimove = random.randint(1, 3)
print("|//////////////|")
print("| 1 - Rock |")
print("| 2 - Paper |")
print("| 3 - Scissors |")
print("|//////////////|")
usermove = input("Choose your move")
# decides who wins or loses
if aimove == "1" and usermove == "2":
print("you won!")
elif aimove == "1" and usermove == "1":
print("you tied")
elif aimove == "1" and usermove == "3":
print("you lost")
elif aimove == "2" and usermove == "3":
print("you won!")
elif aimove == "2" and usermove == "2":
print("you tied")
elif aimove == "2" and usermove == "1":
print("you lost")
elif aimove == "3" and usermove == "1":
print("you won!")
elif aimove == "3" and usermove == "3":
print("you tied")
elif aimove == "3" and usermove == "1":
print("you lost")
else:
sys.exit()
# Print messages of match
print("User aimove: " + str(usermove))
print("Opponent aimove: " + str(aimove))
main()

random.randint gives an integer, not a string. so, if you compare string with int, it'll never be the same.
You can remove quotes around every number like Russ J said in comments, or, you can just convert that into str()
import random
import sys
def main():
while True:
aimove = str(random.randint(1, 3))
print("|//////////////|")
print("| 1 - Rock |")
print("| 2 - Paper |")
print("| 3 - Scissors |")
print("|//////////////|")
usermove = input("Choose your move")
# decides who wins or loses
if aimove == "1" and usermove == "2":
print("you won!")
elif aimove == "1" and usermove == "1":
print("you tied")
elif aimove == "1" and usermove == "3":
print("you lost")
elif aimove == "2" and usermove == "3":
print("you won!")
elif aimove == "2" and usermove == "2":
print("you tied")
elif aimove == "2" and usermove == "1":
print("you lost")
elif aimove == "3" and usermove == "1":
print("you won!")
elif aimove == "3" and usermove == "3":
print("you tied")
elif aimove == "3" and usermove == "1":
print("you lost")
else:
sys.exit()
# Print messages of match
print("User aimove: " + str(usermove))
print("Opponent aimove: " + str(aimove))
main()

Here is your error:
elif aimove == "3" and usermove == "1":
print("you won!")
elif aimove == "3" and usermove == "3":
print("you tied")
elif aimove == "3" and usermove == "1":
print("you lost")
3 and 1 combination is for both - won and lost
Also I discovered your error when coding as below:
dct = dict()
dct["12"] = "you won!"
dct["11"] = "you tied!"
dct["13"] = "you lost!"
dct["23"] = "you won!"
dct["22"] = "you tied!"
dct["21"] = "you lost!"
dct["31"] = "you won!"
dct["33"] = "you tied!"
dct["32"] = "you lost!"
# OR
#dct = {'12': 'you won!', '11': 'you tied!', '13': 'you lost!', '23': 'you won!', '22': 'you tied!', '21': 'you lost!', '31': 'you won!', '33': 'you tied!', '32': 'you lost!'}
if dct.get(aimove+usermove)
print(dct[aimove+usermove])
else:
sys.exit()
So replace your corresponding code and get rid of all elifs

Related

I keep getting this IndentationError: unexpected indent error

File "E:\P-L\Atom\RPS.py\RPS.py", line 34
if user_choice == "r":
IndentationError: unexpected indent
i'm new to code and i'm making a project
someone said the you learn better by doing projects
so here i am
i'm getting this on Atom
i've tried the same code on repl.it and it works
import random
comp_wins = 0
player_wins = 0
def Choose_Option():
user_choice = input("Choose Rock, Paper or Scissors: ")
if user_choice in ["Rock", "rock", "r", "R"]:
user_choice = "r"
elif user_choice in ["Paper", "paper", "p", "P"]:
user_choice = "p"
elif user_choice in ["Scissors", "scissors", "s", "S"]:
user_choice = "s"
else:
print("I don't understand, try again.")
Choose_Option()
return user_choice
def Computer_Option():
comp_choice = random.randint(1, 3)
if comp_choice == 1:
comp_choice = "r"
elif comp_choice == 2:
comp_choice = "p"
else:
comp_choice = "s"
return comp_choice
while True:
print("")
user_choice = Choose_Option()
comp_choice = Computer_Option()
print("")
if user_choice == "r":
if comp_choice == "r":
print("You chose rock. The computer chose rock. You tied.")
elif comp_choice == "p":
print("You chose rock. The computer chose paper. You lose.")
comp_wins += 1
elif comp_choice == "s":
print("You chose rock. The computer chose scissors. You win.")
player_wins += 1
elif user_choice == "p":
if comp_choice == "r":
print("You chose paper. The computer chose rock. You win.")
player_wins += 1
elif comp_choice == "p":
print("You chose paper. The computer chose paper. You tied.")
elif comp_choice == "s":
print("You chose paper. The computer chose scissors. You lose.")
comp_wins += 1
elif user_choice == "s":
if comp_choice == "r":
print("You chose scissors. The computer chose rock. You lose.")
comp_wins += 1
elif comp_choice == "p":
print("You chose scissors. The computer chose paper. You win.")
player_wins += 1
elif comp_choice == "s":
print("You chose scissors. The computer chose scissors. You tied.")
print("")
print("Player wins: " + str(player_wins))
print("Computer wins: " + str(comp_wins))
print("")
user_choice = input("Do you want to play again? (y/n)")
if user_choice in ["Y", "y", "yes", "Yes"]:
pass
elif user_choice in ["N", "n", "no", "No"]:
break
else:
break
Pretty sure the problem is with atom but i don't know what it is would love any help.

How to carry variables into different function

First of all sorry for this heavy, blunt code.
I know there are some better and more eye-candy codes out there but I decided to write it by myself. I know there is a room for HUGE improvement but bear with me.
Almost all my code is working surprisingly except the score part.
Basically this is a Rock Paper Scissors game with recording the number of wins for player, for computer and total number of games.
I only couldn't pass the scores into another function. Can someone please let me know why I am getting this error when I am selecting "1 - Score" on repeat game function
Traceback (most recent call last):
File "forweb.py", line 123, in <module>
main_menu()
File "forweb.py", line 27, in main_menu
play_game()
File "forweb.py", line 95, in play_game
return player, computer, total, repeat_game()
File "forweb.py", line 112, in repeat_game
play_game()
File "forweb.py", line 47, in play_game
play_game()
File "forweb.py", line 95, in play_game
return player, computer, total, repeat_game()
File "forweb.py", line 107, in repeat_game
print("Total Game: "+ play_game(total))
NameError: name 'total' is not defined
note: please ignore "from game_text import game_information" since it is on another python file
import random
import sys
import os
import time
from game_text import game_information
os.system('clear')
name = input("Please write your name: ")
def main_menu():
menu_selection_word = input("1-Help, 2-Play, 3-Quit \n"))
try:
menu_selection_int = int(menu_selection_word)
print("you have selected: ", menu_selection_int)
except ValueError:
print(" Invalid selection")
main_menu()
if menu_selection_int == 1:
os.system('clear')
game_information()
main_menu()
elif menu_selection_int == 2:
play_game()
elif menu_selection_int == 3:
game_quit()
else:
print("Invaild selection \n")
main_menu()
def play_game(player=0,computer=0,total=0):
total += 1
player_selection_input = input("R-Rock, S-Scissors, P-Paper \n")
if player_selection_input == "R" or player_selection_input == "r":
print("You have selected Rock")
elif player_selection_input == "S" or player_selection_input == "s":
print("You have selected Scissors")
elif player_selection_input == "P" or player_selection_input == "p":
print("You have selected Paper")
else:
print("Invaild selection \n")
play_game()
comp_random = ["R", "r", "S", "s", "P", "p"]
comp_selection = random.choice(comp_random)
if comp_selection == "R" or comp_selection == "r":
print("Computer Selected: Rock")
elif comp_selection == "P" or comp_selection == "p":
print("Computer Selected: Paper")
else:
print("Computer Selected: Scissors")
if player_selection_input == "R" or player_selection_input == "r":
if comp_selection == "S" or comp_selection == "s":
print("Your Rock crushed computer's scissors! You Won!")
player += 1
time.sleep(1.5)
elif comp_selection == "R" or comp_selection == "r":
print("It is a tie!")
time.sleep(1.5)
else:
print("Computer's Paper covered your Rock! You Lost!")
computer += 1
time.sleep(1.5)
elif player_selection_input == "S" or player_selection_input == "s":
if comp_selection == "S" or comp_selection == "s":
print(" It is a tie!")
time.sleep(1.5)
elif comp_selection == "R" or comp_selection == "r":
print("Computer's Rock crushed your Scissors. You Lost!")
computer += 1
time.sleep(1.5)
else:
print("Your Scissors cut computer's Paper. You Won!")
player += 1
time.sleep(1.5)
elif player_selection_input == "P" or player_selection_input == "p":
if comp_selection == "R" or comp_selection == "r":
print("Your Paper covered computer's Rock. You Won!")
player += 1
time.sleep(1.5)
elif comp_selection == "S" or comp_selection == "s":
print("Computer's Scissors cut your Paper. You Lost!")
computer += 1
time.sleep(1.5)
else:
print(" It is a tie!")
time.sleep(1.5)
return player, computer, total, repeat_game()
def repeat_game():
repeat_game_selection = input("1-Score, 2-New game, 3-Quit \n")
try:
repeat_game_select = int(repeat_game_selection)
except ValueError:
print(" Invalid selection")
repeat_game()
if repeat_game_select == 1:
os.system('clear')
print("Total Game: "+ play_game(total))
Print("Player Win: "+ play_game(player))
print("Computer Win: "+ play_game(computer))
elif repeat_game_select == 2:
print("New Game begins \n")
play_game()
elif repeat_game_select == 3:
game_quit()
else:
print("Invaild selection \n")
repeat_game()
def game_quit():
os.system('clear')
sys.exit("Thank you for Playing. See you next time!")
main_menu()
You want to pair
return player, computer, total, repeat_game()
with a call like this:
player, computer, total, repeat_game = play_game()
That is, if the public API returns four values, you will want to pick up those values.
Four is starting to become an inconveniently largish number.
You'd probably be better off defining a class and storing four object attributes,
such as self.player.

Broken loop in Python

I am working on learning python (version 3), and as you are probably aware, one of the exercises is to create a game of rock paper scissors lizard spock (rpsls) I was required to start with the if statements featured below, then modify the code to include loops and use a random function to add a computer player. I have spent a few days adjusting the code and googling things, but I have not been able to fix the break in the loop. It gets stuck asking player one for input endlessly and never loads the comparison with player2 or finishes the round. I realize this is a messy way to code the game, but I would like to keep the formatting if possible.
import random
print("")
print("**** Welcome to Rock Paper Scissors ****")
print("")
inputOK = False
player2choices = ['rock', 'paper', 'scissors', 'lizard', 'spock']
while inputOK == False:
stringPlayer1 = input("Player 1, choose: rock, paper, scissors, lizard, or spock: ")
stringPlayer2 = random.choice(player2choices)
if stringPlayer1 == stringPlayer2:
print("Tie: Both players chose:" +
stringPlayer1)
elif stringPlayer1 == 'scissors' and stringPlayer2 == 'paper':
print("Player 1 wins: scissors cuts paper.")
elif stringPlayer1 == 'paper' and stringPlayer2 == 'rock':
print("Player 1 wins: paper covers rock.")
elif stringPlayer1 == 'rock' and stringPlayer2 == 'lizard':
print("Player 1 wins: rock crushes lizard.")
elif stringPlayer1 == 'lizard' and stringPlayer2 == 'spock':
print("Player 1 wins: lizard poisons spock.")
elif stringPlayer1 == 'spock' and stringPlayer2 == 'scissors':
print("Player 1 wins: Spock smashes scissors.")
elif stringPlayer1 == 'scissors' and stringPlayer2 == 'lizard':
print("Player 1 wins: scissors decapitates lizard.")
elif stringPlayer1 == 'lizard' and stringPlayer2 == 'paper':
print("Player 1 wins: lizard eats paper.")
elif stringPlayer1 == 'paper' and stringPlayer2 == 'spock':
print("Player 1 wins: paper disproves Spock.")
elif stringPlayer1 == 'spock' and stringPlayer2 == 'rock':
print("Player 1 wins: Spock vaporizes rock.")
elif stringPlayer1 == 'rock' and stringPlayer2 == 'scissors':
print("Player 1 wins: rock crushes scissors.")
elif stringPlayer1 == 'paper' and stringPlayer2 == 'scissors':
print("Player 2 wins: scissors cuts paper.")
elif stringPlayer1 == 'rock' and stringPlayer2 == 'paper':
print("Player 2 wins: paper covers rock.")
elif stringPlayer1 == 'lizard' and stringPlayer2 == 'rock':
print("Player 2 wins: rock crushes lizard.")
elif stringPlayer1 == 'spock' and stringPlayer2 == 'lizard':
print("Player 2 wins: lizard poisons spock.")
elif stringPlayer1 == 'scissors' and stringPlayer2 == 'spock':
print("Player 2 wins: Spock smashes scissors.")
elif stringPlayer1 == 'lizard' and stringPlayer2 == 'scissors':
print("Player 2 wins: scissors decapitates lizard.")
elif stringPlayer1 == 'paper' and stringPlayer2 == 'lizard':
print("Player 2 wins: lizard eats paper.")
elif stringPlayer1 == 'spock' and stringPlayer2 == 'paper':
print("Player 2 wins: paper disproves Spock.")
elif stringPlayer1 == 'rock' and stringPlayer2 == 'spock':
print("Player 2 wins: Spock vaporizes rock.")
elif stringPlayer1 == 'scissors' and stringPlayer2 == 'rock':
print("Player 2 wins: rock crushes scissors.")
else:
inputOK = False
print("Error: Not a valid choice.")
quit = input("Do you want to quit? ")
if quit.lower() == "y" or quit.lower() == "yes":
done = True
User will be stuck in infinite loop unless somewhere within the while loop the condition is changed by setting inputOK = True.
Before that you need to determine what will be the condition for valid input, such as user input being one of the valid choices (if stringPlayer1 in player1choices):
player2choices = ['rock', 'paper', 'scissors', 'lizard', 'spock']
player1choices = player2choices
while inputOK == False:
stringPlayer1 = input("Player 1, choose: rock, paper, scissors, lizard, or spock: ")
if stringPlayer1 in player1choices: # a condition for valid input?
inputOK = True
stringPlayer2 = random.choice(player2choices)
That should at least fix the broken loop and allow you to move along developing the game more.
The while loop will continue looping until your variable, inputOk, equals True. Your error is that inputOK is not being updated to True when the player wants to end the game. Perhaps you meant to set inputOk equal to True instead of done?
quit = input("Do you want to quit? ")
if quit.lower() == "y" or quit.lower() == "yes":
inputOk = True
Edit: Also as already mentioned, you must indent in python. Any code not indented under while statement will not loop.

My variables for my python camel game aren't udating

I'm a freshman in a computer science degree and I was given this assignment to complete this camel game. I can't seem to find a way for the variables to update when checking the status after moving. They always print miles traveled is 0 and the natives are -20 miles behind. Any help is greatly appreciated thanks!
Here is my code.
# The comments are from my friend who helped me fix the while loop from repeating over and over
def main ():
global executed
executed = 1
if executed == 1: # This will only show the intro once
print("Welcome to Camel!")
print("You have stolen a camel to make your way across the great Mobi desert.")
print("The natives want their camel back and are chasing you down!")
print("Survive your desert trek and out run the natives.")
global done # Add global next to a variable if you're calling it from outside the function
executed = 0
main()
done = False
while not done:
# Game variables
miles_traveled = int(0)
thirst = int(0)
camel_tiredness = int(0)
native_distance = int(-20)
canteen_drinks = int(3)
print("A. Drink from your canteen.")
print("B. Ahead moderate speed.")
print("C. Ahead full speed.")
print("D. Stop for the night.")
print("E. Status check.")
print("Q. Quit.")
user_choice = (input("What is your choice? "))
# Quit the game
if user_choice.upper() == "Q":
done = True
print("Quitting...")
# Status check
elif user_choice.upper() == "E":
print("Miles traveled:", miles_traveled)
print("Drinks in Canteen:", canteen_drinks)
print("The natives are", native_distance, "miles behind you.")
# Stopping for the night
elif user_choice.upper() == "D":
camel_tiredness = int(0)
print("Your camel is happy.")
import random
native_distance += random.randint(7, 14)
print("The natives are", native_distance, "miles behind you.")
#Full speed
elif user_choice.upper() == "C":
thirst += int(1)
camel_tiredness += int(1)
import random
miles_traveled += random.randint(10, 20)
print("You have traveled", miles_traveled, "miles.")
import random
native_distance += random.randint(7, 14)
# Moderate speed
elif user_choice.upper() == "B":
import random
miles_traveled += random.randint(5, 12)
print("You have traveled", miles_traveled,"miles.")
thirst += int(1)
camel_tiredness += int(1)
import random
native_distance += random.randint(7, 14)
# Drinking from canteen
elif user_choice.upper() == "A":
if canteen_drinks >= 1:
print("You have taken a sip from your canteen")
print("You have", canteen_drinks - int(1), "sips left in your canteen.")
elif canteen_drinks == 0:
print("You are out of water.")
# The other stuff at the end
if thirst > 4 < 6:
print("You are thirsty.")
if thirst > 6:
print("You have died of thirst!")
done = True
if camel_tiredness > 5 < 8:
print("Your camel is tired.")
if camel_tiredness > 8:
print("Your camel has died.")
if native_distance >= 0:
print("The natives have caught you.")
done = True
if native_distance >= -15:
print("The natives are getting close!")
if miles_traveled >= 200:
print("You have won and got away from the natives!")
done = True
import random
oasis = random.randint(0, 20)
if oasis == 20:
print("You have found an oasis.")
thirst = 0
camel_tiredness = 0
Your variables should be out of the while loop in order not to get the same values over and over and also you should have update canteen_drinks variable eachtime.
Updated code
def main ():
global executed
executed = 1
if executed == 1: # This will only show the intro once
print("Welcome to Camel!")
print("You have stolen a camel to make your way across the great Mobi desert.")
print("The natives want their camel back and are chasing you down!")
print("Survive your desert trek and out run the natives.")
global done # Add global next to a variable if you're calling it from outside the function
executed = 0
main()
import random
done = False
miles_traveled = int(0)
thirst = int(0)
camel_tiredness = int(0)
native_distance = int(-20)
canteen_drinks = int(3)
while not done:
# Game variables
print("A. Drink from your canteen.")
print("B. Ahead moderate speed.")
print("C. Ahead full speed.")
print("D. Stop for the night.")
print("E. Status check.")
print("Q. Quit.")
user_choice = (input("What is your choice? "))
# Quit the game
if user_choice.upper() == "Q":
done = True
print("Quitting...")
# Status check
elif user_choice.upper() == "E":
print("Miles traveled:", miles_traveled)
print("Drinks in Canteen:", canteen_drinks)
print("The natives are", native_distance, "miles behind you.")
# Stopping for the night
elif user_choice.upper() == "D":
camel_tiredness = int(0)
print("Your camel is happy.")
native_distance += random.randint(7, 14)
print("The natives are", native_distance, "miles behind you.")
#Full speed
elif user_choice.upper() == "C":
thirst += int(1)
camel_tiredness += int(1)
miles_traveled += random.randint(10, 20)
print("You have traveled", miles_traveled, "miles.")
native_distance += random.randint(7, 14)
# Moderate speed
elif user_choice.upper() == "B":
miles_traveled += random.randint(5, 12)
print("You have traveled", miles_traveled,"miles.")
thirst += int(1)
camel_tiredness += int(1)
native_distance += random.randint(7, 14)
# Drinking from canteen
elif user_choice.upper() == "A":
if canteen_drinks >= 1:
print("You have taken a sip from your canteen")
canteen_drinks = canteen_drinks - int(1) # you should update the centeen_drinks
print("You have", canteen_drinks, "sips left in your canteen.")
elif canteen_drinks == 0:
print("You are out of water.")
# The other stuff at the end
if thirst > 4 < 6:
print("You are thirsty.")
if thirst > 6:
print("You have died of thirst!")
done = True
if camel_tiredness > 5 < 8:
print("Your camel is tired.")
if camel_tiredness > 8:
print("Your camel has died.")
if native_distance >= 0:
print("The natives have caught you.")
done = True
if native_distance >= -15:
print("The natives are getting close!")
if miles_traveled >= 200:
print("You have won and got away from the natives!")
done = True
oasis = random.randint(0, 20)
if oasis == 20:
print("You have found an oasis.")
thirst = 0
camel_tiredness = 0

Python 3 Rock, Paper, Scissors game NameError: name 'computer_choice_rock' is not defined

I am making a rock, paper, scissors game for a programming class. This is where I got and then PowerShell spits out that error. I don't understand what is wrong (I am a beginning Python programmer). My programming teacher is not much help and prefers the "Figure it out" approach to learning. I am genuinely stuck at this point. Any help is appreciated, thank you!
import random
def rps():
computer_choice = random.randint(1,3)
if computer_choice == 1:
comuter_choice_rock()
elif computer_choice == 2:
comuter_choice_paper()
else:
comuter_choice_scissors()
def computer_choice_rock():
user_choice = input("1 for Rock, 2 for Paper, 3 for Scissors: ")
if user_choice == "1":
print ("It's a Tie!")
try_again()
if user_choice == "2":
print ("You Win! Paper covers Rock!")
try_again()
if user_choice == "3":
print ("I Win and You Lose! Rock crushes Scissors!")
try_again()
else:
print ("Please type in 1, 2, or 3")
computer_choice_rock()
def computer_choice_paper():
user_choice = input("1 for Rock, 2 for Paper, 3 for Scissors: ")
if user_choice == "1":
print ("I Win and You Lose! Paper covers Rock!")
try_again()
if user_choice == "2":
print ("It's a Tie!")
try_again()
if user_choice == "3":
print ("You Win! Scissors cut Paper!")
try_again()
else:
print ("Please type in 1, 2, or 3")
computer_choice_paper()
def computer_choice_paper():
user_choice = input("1 for Rock, 2 for Paper, 3 for Scissors: ")
if user_choice == ("1"):
print ("You Win! Rock crushes Scissors")
try_again()
if user_choice == "2":
print ("I Win! Scissors cut Paper!")
try_again()
if user_choice == "3":
print ("It's a Tie!")
try_again()
else:
print ("Please type in 1, 2, or 3")
computer_choice_paper()
def try_again():
choice = input("Would you like to play again? Y/N: ")
if choice == "Y" or choice == "y" or choice == "Yes" or choice == "yes":
rps()
elif choice == "n" or choice == "N" or choice == "No" or choice == "no":
print ("Thanks for Playing!")
quit()
else:
print ("Please type Y or N")
try_again()
rps()
You have a typo in you code
if computer_choice == 1:
comuter_choice_rock()
elif computer_choice == 2:
comuter_choice_paper()
else:
comuter_choice_scissors()
Comuter
Your code can be simplified to an extreme degree. See the following example program. To replace either of the players with a NPC, set player_1 or player_2 with random.choice(priority). If you want to, you could even have the computer play against itself.
priority = dict(rock='scissors', paper='rock', scissors='paper')
player_1 = input('Player 1? ')
player_2 = input('Player 2? ')
if player_1 not in priority or player_2 not in priority:
print('This is not a valid object selection.')
elif player_1 == player_2:
print('Tie.')
elif priority[player_1] == player_2:
print('Player 1 wins.')
else:
print('Player 2 wins.')
You could also adjust your game so people can play RPSSL instead. The code is only slightly different but shows how to implement the slightly more complicated game. Computer play can be implemented in the same way as mentioned for the previous example.
priority = dict(scissors={'paper', 'lizard'},
paper={'rock', 'spock'},
rock={'lizard', 'scissors'},
lizard={'spock', 'paper'},
spock={'scissors', 'rock'})
player_1 = input('Player 1? ')
player_2 = input('Player 2? ')
if player_1 not in priority or player_2 not in priority:
print('This is not a valid object selection.')
elif player_1 == player_2:
print('Tie.')
elif player_2 in priority[player_1]:
print('Player 1 wins.')
else:
print('Player 2 wins.')

Resources