```import random
from random import randint
pc = randint(1, 3)
playerinput = input("1 = Rock, 2 = Paper, 3 = Scissors")
def start():
pc = randint(1, 3)
if playerinput == 1:
if pc == 2:
print("You lose!")
elif pc == 1:
print("You draw!")
else:
print("You win!")
elif playerinput == 2:
if pc == 2:
print("You draw!")
elif pc == 3:
print ("You lose!")
else:
print("You win!")
else:
if pc == 3:
print("You draw!")
elif pc == 2:
print("You win!")
else:
print("You lose!")
again = input("Would you like to play again? Type 'YES' if so")
if again == "YES" or "yes" or "Yes" or "yEs" or "yeS" or "YEs" or "YeS":
start()```
It prints the rock paper or scissors, then it just goes would you like to play again. if you say yes, it then prints whether you won, lost or tied. what's wrong?
You call the Player-input only once, so once the Player made on decision calling start() will only generate a new random int. From what I understand you want to change the code into something like this, asking the player for input each time start() is called:
(Note that the pc before the definition is not needed aswell, since you reset it in start())
import random
from random import randint
def start():
pc = randint(1, 3)
playerinput = input("1 = Rock, 2 = Paper, 3 = Scissors")
if playerinput == 1:
if pc == 2:
print("You lose!")
elif pc == 1:
print("You draw!")
else:
print("You win!")
elif playerinput == 2:
if pc == 2:
print("You draw!")
elif pc == 3:
print ("You lose!")
else:
print("You win!")
else:
if pc == 3:
print("You draw!")
elif pc == 2:
print("You win!")
else:
print("You lose!")
start()
while True:
again = input("Would you like to play again? Type 'YES' if so")
if again == "YES" or "yes" or "Yes" or "yEs" or "yeS" or "YEs" or "YeS":
start()
else:
break
EDIT: As stated in the comment to your question by a different user, you shuold change the if to just if again.lower() = "yes" to be more clean. Alsoimport randomis not necessary if you callfrom random import randint` afterwards.
That's because 'randint' randomly initialize a number from 1-3 whenever invoked.
randint(1, 3)
So, whichever number the user enters, the function reinitialize the number and prints:
either "You win!", "You lose!", or "You draw!".
You probably want to read input inside start.
Also, your if statement will always be True because
if "yes":
will pass.
In any case you want to do something like again.lower() == 'yes'
You forgot to call your function after defined it.
You need to add start() before again.
Also if you want to play everytime the user said yes you need to had a loop
import random
from random import randint
pc = randint(1, 3)
playerinput = input("1 = Rock, 2 = Paper, 3 = Scissors")
def start():
pc = randint(1, 3)
if playerinput == 1:
if pc == 2:
print("You lose!")
elif pc == 1:
print("You draw!")
else:
print("You win!")
elif playerinput == 2:
if pc == 2:
print("You draw!")
elif pc == 3:
print ("You lose!")
else:
print("You win!")
else:
if pc == 3:
print("You draw!")
elif pc == 2:
print("You win!")
else:
print("You lose!")
start()
while True:
again = input("Would you like to play again? Type 'YES' if so")
if again == "YES" or "yes" or "Yes" or "yEs" or "yeS" or "YEs" or "YeS":
start()
else:
break;
Consider adding the first input to the function start, remove the first pc = randint and then call the function below its definition.
Related
import random
user_wins = 0
computer_wins = 0
options = ["Rock", "Paper", "Scissors"]
while True:
user_input = input("Type Rock/Paper/Scissors or Q to quit: ")
if user_input == "q":
break
if user_input not in [options]:
continue
random_number = random.randint(0, 2)
# rock: 0, paper: 1, scissors: 2
computer_pick = options[random_number]
print("computer picked", computer_pick + ".")
if user_input == "rock" and computer_pick == "scissors":
print("You won!")
user_wins += 1
elif user_input == "scissors" and computer_pick == "paper":
print("You won!")
user_wins += 1
elif user_input == "paper" and computer_pick == "rock":
print("You won!")
user_wins += 1
else:
print("You lost!")
computer_wins += 1
print("You won", user_wins, "times.")
print("The cpu won", computer_wins, "times.")
print("Goodbye!")
I'm sorry if im not using this site the correct way but I've been following along with Tech With Tim on youtube trying to write 5 mini python games to just practice. I expect if i put q it will break, but now that i'm typing this i'm realizing that if it were to break i shouldn't get the print statements on line 37,38, and 39. either way, when i input rock , paper, or scissors it comes back as "Type Rock/Paper/Scissors or Q to quit:". I'm having a hard time understanding why my code doesnt work, while Tim has the exact same code, line for line, and his works fine. Any and all help would be appreciated.. even if its directing me to slow my roll
if user_input not in [options] isn't correct. [options] is a list containing one element: all of options. A string can never be all of options, so user_input not in [options] will always be true.
You want
if user_input not in options:
New to python and coded a simple rock, paper scissors game below. Why does the scores show after entering q while running it in visual studio code but this doesn't happen after entering q while opening the file.
import random
user_wins = 0
computer_wins = 0
options = ["rock", "paper", "scissors"]
while True:
user_input = input("Type Rock/Paper/Scissors or Q to quit: ").lower()
if user_input == "q":
break
if user_input not in options:
continue
random_number = random.randint(0, 2)
# Rock: 0 Paper: 1 Scissors: 2
computer_pick = options[random_number]
print("Computer picked", computer_pick + ".")
if user_input == "rock" and computer_pick == "scissors":
print("You Won!")
user_wins += 1
elif user_input == "paper" and computer_pick == "rock":
print("You Won!")
user_wins += 1
elif user_input == "scissors" and computer_pick == "paper":
print("You Won!")
user_wins += 1
elif user_input == computer_pick:
print ("It's a Draw")
else:
print("You lose")
computer_wins += 1
print("You won", user_wins, "rounds!")
print("The Computer won", computer_wins,"rounds!")
print("Thank you for playing")
When opening a program as a file, the window will immediately close when the code ends - this means that as soon as q is entered, the program exits the while loop, shows the scores and closes instantly after, leaving no time for you to read it. Visual studio code doesn't have a window to close, leaving the text able to be read.
To fix this, you can add input() at the end of the code, meaning that the user would have to press enter to end the program.
I built this simple rock/paper/scissor game by watching some tutorials. Everything is working fine. The issue is that I want to implement something where if the user and the computer choose the same word, then it should say something like "draw."
I could go ahead and add a bunch of "if" and "else" statements, but I don't want that. Can you guys think of any other way to implement that with fewer lines of code?
#Simple rock, paper and scissor game
import random
user_wins = 0
computer_wins = 0
options = ["rock", "paper", "scissors"]
while True:
user_pick = input("Please choose Rock/Paper/Scissors Or Press Q to quit: ")
if user_pick.lower() == "q":
print("You quit.")
break
elif user_pick not in options:
print("Please enter a valid input.")
continue
random_number = random.randint(0, 2)
computer_pick = options[random_number]
print("The computer picked", computer_pick)
if computer_pick == "rock" and user_pick == "scissors":
print("You lost!")
computer_wins += 1
elif computer_pick == "paper" and user_pick == "rock":
print("You lost!")
computer_wins += 1
elif computer_pick == "scissors" and user_pick == "paper":
print("You lost!")
computer_wins += 1
else:
print('You win!')
user_wins += 1
You could use a dictionary to map which choices beat each other. This will enable to you make the conditional part of the code, which determines who wins, more concise. It is also more easily expanded to rock-paper-scissors variants with more options, without the need for many more conditional statements.
#Simple rock, paper and scissor game
import random
user_wins = 0
computer_wins = 0
options = ["rock", "paper", "scissors"]
beaten_by = {
"rock": "scissors",
"scissors": "paper",
"paper": "rock"
}
while True:
user_pick = input("Please choose Rock/Paper/Scissors Or Press Q to quit: ")
if user_pick.lower() == "q":
print("You quit.")
break
elif user_pick not in options:
print("Please enter a valid input.")
continue
random_number = random.randint(0, 2)
computer_pick = options[random_number]
print("The computer picked", computer_pick)
if user_pick == computer_pick:
print("Draw!")
elif user_pick == beaten_by[computer_pick]:
print("You lost!")
computer_wins += 1
else:
print("You win!")
user_wins += 1
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.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am using Python. Currently new to it. I'm creating a rock paper scissors game with win counter. I've look up some solution online but it doesn't work for me.I'm close to completing it.But there's just an error to it.I can't get the tally counter working.It doesn't shows any win count at the end of the program
from random import randint
print ("Rock ,Paper,Scissors game.")
#Function to get computer input
def generate():
comlist = ["rock","paper","scissors"]
comans = comlist[randint(-1,2)]
if comans == "rock":
print ("Computer choose rock.")
elif comans == "paper" :
print ("Computer choose paper.")
elif comans == "scissors":
print ("Computer choose scissors.")
return comans
#Function to get user input
def user():
userchoice = input ("Choose rock, paper , or scissors.")
while userchoice != 'rock' and userchoice != 'paper' and userchoice != 'scissors':
print ("Invalid input. Please enter again")
userchoice = input ("Choose rock, paper , or scissors.")
if userchoice == "rock":
print ("You choose rock.")
choice = userchoice
elif userchoice == "paper" :
print ("You choose paper.")
choice = userchoice
else:
userchoice == "scissors"
print ("You choose scissors.")
choice = userchoice
return choice
#Function to determine winner
def result(comans ,choice):
global result_set
if choice == comans:
print ("Tie")
elif choice == "rock":
if computer == "paper":
print ("You lose")
else :
print("You win")
result_set ='win'
elif choice == "paper":
if computer == "scissors":
print("You lose")
else:
print("You win")
result_set ='win'
elif choice == "scissors":
if computer == "rock":
print("You lose")
else:
print("You win")
result_set ='win'
#Function to get win taly
def wincounter (result,guess,computer):
if result_set == 'win':
win += 1
else:
pass
print (win)
#Main program
counter = 0
win = 0
diffulty = input(' Please enter diffulty.( "1" for easy , "2" for medium, "3" for hard)')
while diffulty != '1' and diffulty != '2' and diffulty != '3':
print ('Invalid input')
diffulty = input(' Please enter diffulty.( "1" for easy , "2" for medium, "3" for hard)')
if diffulty == '1':
print ("You have choose easy")
counter = 1
guess = user()
computer = generate()
result (computer, guess)
while counter < 3:
guess = user()
computer = generate()
result (computer, guess)
counter +=1
if diffulty == '2':
print ("You have choose medium")
counter = 1
guess = user()
computer = generate()
result (computer, guess)
while counter < 5:
guess = user()
computer = generate()
result (computer, guess)
counter +=1
if diffulty == '3':
print ("You have choose hard")
counter = 1
guess = user()
computer = generate()
result (computer, guess)
while counter < 10:
guess = user()
computer = generate()
result (computer, guess)
counter +=1
Here is my code. It is slightly messy. Sorry for that since than I am still new in python. Thanks for the help.
After running.
Choose rock, paper , or scissors.rock
You choose rock.
Computer choose scissors.
You win
Choose rock, paper , or scissors.rock
You choose rock.
Computer choose rock.
Tie
Choose rock, paper , or scissors.rock
You choose rock.
Computer choose rock.
Tie
It is suppose to show the win results after the end of the last round.
I have fixed your code . . .
from random import randint
print ("Rock ,Paper,Scissors game.")
#Function to get computer input
def generate():
comlist = ["rock","paper","scissors"]
comans = comlist[randint(-1,2)]
if comans == "rock":
print ("Computer choose rock.")
elif comans == "paper" :
print ("Computer choose paper.")
elif comans == "scissors":
print ("Computer choose scissors.")
return comans
#Function to get user input
def user():
userchoice = input ("Choose rock, paper , or scissors.")
while userchoice != 'rock' and userchoice != 'paper' and userchoice != 'scissors':
print ("Invalid input. Please enter again")
userchoice = input ("Choose rock, paper , or scissors.")
if userchoice == "rock":
print ("You choose rock.")
choice = userchoice
elif userchoice == "paper" :
print ("You choose paper.")
choice = userchoice
else:
userchoice == "scissors"
print ("You choose scissors.")
choice = userchoice
return choice
#Function to determine winner
def result(comans ,choice):
result_set = ''
if choice == comans:
print ("Tie")
elif choice == "rock":
if computer == "paper":
print ("You lose")
else :
print("You win")
result_set ='win'
elif choice == "paper":
if computer == "scissors":
print("You lose")
else:
print("You win")
result_set ='win'
elif choice == "scissors":
if computer == "rock":
print("You lose")
else:
print("You win")
result_set ='win'
wincounter(result_set)
#Function to get win taly
def wincounter (result):
global win
if result == 'win':
win += 1
else:
pass
#print (win)
def print_win_count():
global win
print ('you have win '+ str(win) + ' times')
#Main program
counter = 0
win = 0
diffulty = input(' Please enter diffulty.( "1" for easy , "2" for medium, "3" for hard)')
while diffulty != '1' and diffulty != '2' and diffulty != '3':
print ('Invalid input')
diffulty = input(' Please enter diffulty.( "1" for easy , "2" for medium, "3" for hard)')
if diffulty == '1':
print ("You have choose easy")
counter = 1
guess = user()
computer = generate()
result (computer, guess)
while counter < 3:
guess = user()
computer = generate()
result (computer, guess)
counter +=1
print_win_count()
if diffulty == '2':
print ("You have choose medium")
counter = 1
guess = user()
computer = generate()
result (computer, guess)
while counter < 5:
guess = user()
computer = generate()
result (computer, guess)
counter +=1
print_win_count()
if diffulty == '3':
print ("You have choose hard")
counter = 1
guess = user()
computer = generate()
result (computer, guess)
while counter < 10:
guess = user()
computer = generate()
result (computer, guess)
counter +=1
print_win_count(0)