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.
Related
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.
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
First of im sorry about bombarding my post with a bunch of code, but im putting it here hoping that it will help you guys understanding my question better.
I am trying to figure out why my IDE is unwilling to execute the first function of my code. Obviously im doing something wrong, but im to unexperienced to see it for myself. All help would be greatly appriciated.
If you have any further comments or tips on my code feel free contribute.
import random
print("Press '1' for New Single Player Game - Play against computer component: ")
print("Press '2' for New Two Player Game - Play against another person, using same computer: ")
print("Press '3' for Bonus Feature - A bonus feature of choice: ")
print("Press '4' for User Guide - Display full instructions for using your application: ")
print("Press '5' for Quit - Exit the program: ")
def choose_program():
what_program = int(input("What program would you like to initiate?? Type in the 'number-value' from the chart above: "))
if what_program == 1 or 2 or 3 or 4 or 5:
program_choice = int(input("Make a choice: "))
if (program_choice > 5) or (program_choice < 1):
print("Please choose a number between 1 through 5 ")
choose_program()
elif program_choice == 1:
print("You picked a New Single Player Game - Play against computer component")
def single_player():
start_game = input("Would you like to play 'ROCK PAPER SCISSORS LIZARD SPOCK'?? Type 'y' for YES, and 'n' for NO): ").lower()
if start_game == "y":
print("Press '1' for Rock: ")
print("Press '2' for Paper: ")
print("Press '3' for Scissors: ")
print("Press '4' for Lizard: ")
print("Press '5' for Spock: ")
elif start_game != "n":
print("Please type either 'y' for YES or 'n' for NO: ")
single_player()
def player_one():
human_one = int(input("Make a choice: "))
if (human_one > 5) or (human_one < 1):
print("Please choose a number between 1 through 5 ")
player_one()
elif human_one == 1:
print("You picked ROCK!")
elif human_one == 2:
print("You picked PAPER!")
elif human_one == 3:
print("You picked SCISSORS!")
elif human_one == 4:
print("You picked LIZARD!")
elif human_one == 5:
print("You picked SPOCK!")
return human_one
def computers_brain():
cpu_one = random.randint(1, 5)
if cpu_one == 1:
print("Computers choice iiiiiis ROCK!")
elif cpu_one == 2:
print("Computers choice iiiiiis PAPER!")
elif cpu_one == 3:
print("Computers choice iiiiiis SCISSORS!")
elif cpu_one == 4:
print("Computers choice iiiiiis LIZARD!")
elif cpu_one == 5:
print("Computers choice iiiiiis SPOCK!")
return cpu_one
def who_won(human, cpu, human_wins, cpu_wins, draw):
if human == 1 and cpu == 3 or cpu == 4:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == 2 and cpu == 1 or cpu == 5:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == 3 and cpu == 2 or cpu == 4:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == 4 and cpu == 2 or cpu == 5:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == 5 and cpu == 1 or cpu == 3:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == cpu:
print("Human & computer think alike, such technology")
draw = draw.append(1)
else:
print("Computer have beaten it's master, incredible..")
cpu_wins = cpu_wins.append(1)
return
def end_score(human_wins, cpu_wins, draw):
human_wins = sum(human_wins)
cpu_wins = sum(cpu_wins)
draw = sum(draw)
print("Humans final score is: ", human_wins)
print("Computers final score is: ", cpu_wins)
print("Total draws: ", draw)
def main():
human = 0
human_wins = []
cpu = 0
cpu_wins = []
draw = []
finalhuman_wins = 0
finalcpu_wins = 0
finaldraw = 0
Continue = 'y'
single_player()
while Continue == 'y':
human = player_one()
cpu = computers_brain()
who_won(human, cpu, human_wins, cpu_wins, draw)
Continue = input("Would you like to play again (y/n):").lower()
if Continue == 'n':
print("Printing final scores.")
break
end_score(human_wins, cpu_wins, draw)
main()
elif program_choice == 2:
print("You picked a New Two Player Game - Play against another person, using same computer")
elif program_choice == 3:
print("You picked the Bonus Feature - A bonus feature of choice")
elif program_choice == 4:
print("You picked the User Guide - Display full instructions for using your application")
elif program_choice == 5:
print("You picked to Quit - Exit the program")
return program_choice
elif what_program != 1 or 2 or 3 or 4 or 5:
print("To initiate a program you need to type in the appropriate number to initiate this program, either 1, 2, 3, 4 & 5 ")
choose_program()
Outout in IDE:
Press '1' for New Single Player Game - Play against computer component:
Press '2' for New Two Player Game - Play against another person, using same computer:
Press '3' for Bonus Feature - A bonus feature of choice:
Press '4' for User Guide - Display full instructions for using your application:
Press '5' for Quit - Exit the program:
Process finished with exit code 0
Thank you in advance for your help :)
I don't have a lot of experience with python but I think this can be much simpler. If anything available for the same result. Using a dictionary mapping to functions instead of all those elif maybe?
choice = input("Select an option: ")
if choice == "1":
try:
new_contact = create_contact()
except NotAPhoneNumberException:
print("The phone number entered is invalid, creation aborted!")
else:
contacts[new_contact['name']] = new_contact
save_contacts(contacts, filename)
elif choice == "2":
print_contact()
elif choice == "3":
search = input("Please enter name (case sensitive): ")
try:
print_contact(contacts[search])
except KeyError:
print("Contact not found")
elif choice == "0":
print("Ending Phone Book.\nHave a nice day!")
break
else:
print("Invalid Input! Try again.")
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.')