I'm making a rock, paper, scissors game with a pointing system and it seems to always give me a value of zero every time the scores are revealed. Help is appreciated.-------------------------------------------------------------------------------------------------------------------------------------------------------------
def play():
player = input("Which will you choose? Rock, Paper or Scissors? Type 'E' to exit ")
elements = ['rock', 'paper', 'scissors']
cpu = random.choice(elements)
scoreplayer = 0
scorecpu = 0
if player.lower() == cpu:
print("This is a tie, no one scores a point")
play()
elif player.lower() == "rock":
if cpu == "paper":
print("Paper beats Rock, CPU gains 1 point")
scorecpu = scorecpu + 1
play()
elif cpu == "scissors":
print("Rock beats Scissors, you gain 1 point")
scoreplayer = scoreplayer + 1
play()
elif player.lower() == "paper":
if cpu == "scissors":
print("Scissors beats Paper, CPU gains 1 point")
scorecpu = scorecpu + 1
play()
elif cpu == "rock":
print("Paper Beats Rock, you gain 1 point")
scoreplayer = scoreplayer + 1
play()
elif player == "scissors":
if cpu == "rock":
print("Rock beats Scissors, CPU gains 1 point")
scorecpu = scorecpu + 1
play()
elif cpu == "paper":
print("Scissors beats Paper, you gain 1 point")
scoreplayer = scoreplayer + 1
play()
elif player.lower() == "e":
print("")
print("You have " + str(scoreplayer) + " points")
print("")
print("CPU has " + str(scorecpu) + " points")
sys.exit()
else:
play()
scoreplayer = 0 and the other assignment are running every time play is called, which creates new variables with values of 0 each time. Pass the current scores as arguments to play instead:
def play(scoreplayer, scorecpu):
# Get rid of these lines
# scoreplayer = 0
# scorecpu = 0
. . .
# Update the scores here
else:
play(scoreplayer, scorecpu)
play(0, 0) # Start with scores of 0
Or switch to using a loop construct like while from recursion and update the scores within the loop. In a language like Python, recursion isn't really suitable here anyways.
because you're setting your variables in your function it will by definition be reset each time it runs. like #Carcigenicate said you could pass them as arguments to it or
use a while loop but you might also want to look into the global statement.
As already mentioned, you're resetting the score every time you call the play() function.
A solution to your problem is to make your score variable a global variable
scoreplayer = 0
scorecpu = 0
def play():
player = input("Which will you choose? Rock, Paper or Scissors? Type 'E' to exit ")
elements = ['rock', 'paper', 'scissors']
cpu = random.choice(elements)
global scoreplayer
global scorecpu
# rest of your code
play()
When defining variables outside of functions we can access them by using the global keyword
You can read more about the global keyword here: https://www.programiz.com/python-programming/global-keyword
Related
This is a rock,paper,scissors game.
import random
options = ("rock", "paper", "scissors") # three options
running = True
score = 0
while running: # continuing the game
player = "" # storing the player's choices
computer = random.choice(options) # computer will choose a random choice from the options
while player not in options: # the player has to choose one of the options, if not, it will still keep on looping
player = input("Enter a choice (rock, paper, scissors): ")
print("Player: " + player) # player(user) vs. computer
print("Computer: " + computer)
if player == computer:
score = 0
print("It's a tie!")
elif player == "rock" and computer == "scissors":
score += 1
print("You win!")
elif player == "paper" and computer == "rock":
score += 1
print("You win!")
elif player == "scissors" and computer == "paper":
score += 1
print("You win!")
else:
score += 1
print("You lose!")
print(score, "for computer")
print(score)
play_again = input("Play again? (y/n): ").lower()
if play_again == "y":
running = True
print("Yes sir!")
else:
running = False
print("Thanks for playing! ")
My goal was trying to keep score for player and computer. If the user wins, they get a point. If the computer wins, they get a point. If its a tie, neither of them gets a point.
The following code shows you three rounds of three games of a simulated user input game with its result. It is your code only slightly changed to count properly the results:
import random
lst_user_input = [
"list faking user input:"
,"scissors"
,"paper"
,"rock"
,"y"
,"scissors"
,"paper"
,"rock"
,"y"
,"scissors"
,"paper"
,"rock"
,"n"
]
options = ("rock", "paper", "scissors") # three options
running = True
computer_score = 0
player_score = 0
round_no = 0
while running: # continuing the game
#player = "" # storing the player's choices
round_no += 1
computer = random.choice(options) # computer will choose a random choice from the options
#while player not in options: # the player has to choose one of the options, if not, it will still keep on looping
# player = input("Enter a choice (rock, paper, scissors): ")
print(round_no)
player = lst_user_input[round_no]
print("Player : " + player) # player(user) vs. computer
print("Computer: " + computer)
if player == computer:
print("It's a tie!")
elif player == "rock" and computer == "scissors":
player_score += 1
print("You win!")
elif player == "paper" and computer == "rock":
player_score += 1
print("You win!")
elif player == "scissors" and computer == "paper":
player_score += 1
print("You win!")
else:
computer_score += 1
print("You lose!")
print("Player score:", player_score)
print("Computer score:", computer_score)
if not round_no % 3: # ask only each 3 rounds
#play_again = input("Play next 3-rounds? (y/n): ").lower()
round_no +=1
play_again = lst_user_input[round_no]
if play_again == "y":
running = True
print("Yes sir!")
else:
running = False
print("Thanks for playing! ")
Here an example of printed output:
1
Player : scissors
Computer: paper
You win!
Player score: 1
Computer score: 0
2
Player : paper
Computer: scissors
You lose!
Player score: 1
Computer score: 1
3
Player : rock
Computer: paper
You lose!
Player score: 1
Computer score: 2
Yes sir!
5
Player : scissors
Computer: paper
You win!
Player score: 2
Computer score: 2
6
Player : paper
Computer: rock
You win!
Player score: 3
Computer score: 2
Thanks for playing!
I have been assigned of developing a Rock Paper Scissors game in Python with some modifications. However, I am quite new to programming, and I do not know how to go about in infinite looping the program unless if the user inputs 'q'. I have a general idea of that I have to use a while loop, however I cannot figure out where to put it.
Attached here is the code that the rock paper scissors game works regularly without trying to infinitely loop and breaking the loop in the program. I have tried to mess around with the indentation of the code after the while loop and had varying results, most of which just broke the program.
import random
def play():
user_option = input("'r for rock:', 'p for paper:', or 's for scissors: or q to quit':")
cpu = random.choice(['r', 's', 'p'])
#while user_option != 'y':
if user_option == cpu:
return("You tie!")
if win(user_option, cpu):
return("You won!")
return "You lost!"
def win(player, computerOpponent):
if (player == 'r' and computerOpponent == 's') or (player == 's' and computerOpponent == 'p') or (player == 'p' and computerOpponent == 'r'):
return True
print(play())
If you want to make the game automatically start a new round without asking the players if they want to play again, you can remove the part of the code that asks for player input and simply have the game loop back to the beginning after each round. Here's one way to do that:
while True:
# Get player input
player1 = input("Player 1, make your move (rock, paper, scissors): ")
player2 = input("Player 2, make your move (rock, paper, scissors): ")
# Determine the winner
if player1 == player2:
print("It's a tie!")
elif player1 == "rock" and player2 == "scissors":
print("Player 1 wins!")
elif player1 == "paper" and player2 == "rock":
print("Player 1 wins!")
elif player1 == "scissors" and player2 == "paper":
print("Player 1 wins!")
else:
print("Player 2 wins!")
# Start a new round automatically
print("Starting a new round...")
I want to display the current statistics of the game after every match
import random
while True:
user_action = input("Enter a choice: (rock, paper, scissors): ")
possible_actions = ["rock", "paper", "scissors"]
comp_action = random.choice(possible_actions)
wins = 0
losses = 0
ties = 0
print(f"\nYou chose {user_action}, computer chose {comp_action}.\n")
if user_action == comp_action:
print(f"Both players selected {user_action}. It's a tie!")
ties +=1
elif user_action == "rock":
if comp_action == "scissors":
print("Rock beats scissors. You win!")
wins += 1
else:
print("Paper beats Rock. You lose! ")
losses +=1
elif user_action == "paper":
if comp_action == "rock":
print("Paper beats rock. You win!")
wins += 1
else:
print("Scissors beats paper! You lose.")
losses += 1
elif user_action == "scissors":
if comp_action == "paper":
print("Scissors beats paper! You win!")
wins += 1
else:
print("Rock beats scissors! You lose.")
losses +=1
print(f"won {wins / sum((wins, losses, ties))}%, {ties} ties")
again = input("Want to play again? (y/n): ")
if again.lower() != "y":
break
I want to show the computer's wins, the user's wins, and the amount of ties along with their win/loss percentages.
Player wins: 0 (0.0%)
Computer wins: 1 (100.0%)
Any help is greatly appreciated.
make 3 counters for the game endings:
wins = losses = ties = 0
and increase them every time it happens like so:
print("Rock beats scissors. You win!")
wins += 1
at the end print them:
print(f"won {wins / sum((wins, losses, ties))}%, {ties} ties")
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
I am trying to complete a rock, paper, scissors assignment for class.
I'm getting a "UnboundLocalError: local variable 'tied' referenced before assignment" error.
Can someone please tell me why I'm getting this error?
import random
user_score = 0
computer_score = 0
tied = 0
def main():
print ("Let's play the game of Rock, Paper, Scissors. ")
while True:
print ("Your current record is", user_score, "wins,", computer_score, "losses and", tied, "ties")
computer_choice = random.randint(1,3)
if computer_choice == 1:
computer_rock()
elif computer_choice == 2:
computer_paper()
else:
computer_scissors()
def computer_rock():
user_choice = input("1 for Rock, 2 for Paper, 3 for Scissors: ")
if user_choice == "1":
print ("Draw! You both chose Rock.")
tied += 1
try_again()
elif user_choice == "2":
print ("You Win! The computer chose Rock, while you picked Paper.")
user_score += 1
try_again()
elif user_choice == "3":
print ("You Lose! You chose scissors, while the computer picked Rock.")
computer_score += 1
try_again()
else:
print ("ERROR: Invalid entry, please re-enter your choice. ")
computer_rock()
def computer_paper():
user_choice = input("1 for Rock, 2 for Paper, 3 for Scissors: ")
if user_choice == "1":
print ("You Lose! You chose rock, while the computer picked Paper.")
computer_score += 1
try_again()
elif user_choice == "2":
print ("Draw! You both picked Paper.")
tied += 1
try_again()
elif user_choice == "3":
print ("You Win! The computer chose Paper, while you picked Scissors.")
user_score += 1
try_again()
else:
print ("ERROR: Invalid entry, please re-enter your choice. ")
computer_paper()
def computer_scissors():
user_choice = input("1 for Rock, 2 for Paper, 3 for Scissors: ")
if user_choice == "1":
print ("You Win! You chose rock, while the computer picked Scissors.")
user_score += 1
try_again()
elif user_choice == "2":
print ("You Lose! The computer chose Scissors, while you picked Paper.")
computer_score += 1
try_again()
elif user_choice == "3":
print ("Draw! You both picked Scissors.")
tied += 1
try_again()
else:
print ("ERROR: Invalid entry, please re-enter your choice. ")
computer_scissors()
def try_again():
choice = input("Play again? Yes or no. ")
if choice == "y" or choice == "Y" or choice == "yes" or choice == "Yes":
main()
elif choice == "n" or choice == "N" or choice == "no" or choice == "No":
print ("Thanks for playing. ")
else:
print ("Try again")
try_again()
main()
Adding the following code as the first line in each of the three computer_() functions should fix your problem.
global tied, user_score, computer_score
There are better ways to accomplish what you're doing, but that should get you over the hump here :)
While Triptych's answer is perfectly acceptable (and also widely used), for a relatively novice-level programmer it is usually better practice to pass arguments into functions instead of utilizing the global keyword.
More info can be found at the Python Documentation: https://docs.python.org/3/tutorial/controlflow.html#defining-functions
In essence, the point is for the programmer to pass what is called an argument (or arguments) into the function, and the function containing those parameters can process this data and return values back to the location where it was called, similar to how the print() function works. You pass a string (ex. "Hi") into the print() function (ex. print("Hi")), and code within this built-in function displays the characters "Hi" onto the screen.
In this case, your code would look something like this:
# In your main function:
def main():
print ("Let's play the game of Rock, Paper, Scissors. ")
while True:
print ("Your current record is", user_score, "wins,", computer_score, "losses and", tied, "ties")
computer_choice = random.randint(1,3)
if computer_choice == 1:
result = computer_rock(user_score, computer_score, tied) ## Notice the difference here
elif computer_choice == 2:
result = computer_paper(user_score, computer_score, tied) ## Those variables you put in the function call are arguments
else:
result = computer_scissors(user_score, computer_score, tied)
# ...
# In the computer_rock() function:
# Even though I only modified this function, you should probably modify all three to suit your needs.
def computer_rock(user_score, computer_score, tied): ## <-- See the parameters?
user_choice = input("1 for Rock, 2 for Paper, 3 for Scissors: ")
if user_choice == "1":
print ("Draw! You both chose Rock.")
tied += 1
try_again()
elif user_choice == "2":
print ("You Win! The computer chose Rock, while you picked Paper.")
user_score += 1
try_again()
elif user_choice == "3":
print ("You Lose! You chose scissors, while the computer picked Rock.")
computer_score += 1
try_again()
return [user_score, computer_score, tied] # Returning a list so it is easier to sort variables
Another thing to note, even though you are calling try_again() to restart the game, it is not a very good idea to call main() inside of a function that will be called by main(). It is better to use a while loop in the main function to regulate and control the flow of the program.
Hopefully this helped!
It caused from a feature in Python.
The following example emits the same Exception. Note that You can't assign to Global-Variable in Local-Scope.
>>> variable = 1
>>> def function():
... variable += 1
...
>>> function()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in function
UnboundLocalError: local variable 'variable' referenced before assignment
So if you write as the following, the value of Globale-Variable is not changed. This variable in function() is not Global-Variable but Local-Variable. Right?
>>> variable = 1
>>> def function():
... variable = 2
...
>>> function()
>>> variable
1
By the way, this feature is useful for us, because we want to use functions as small as possible, if speaking loudly, simply because we humans don't understand long functions.
Perhaps you want to use the Global-Variable here now, but when you write many and many codes, and can use Global-Variable, you will be panic such as "Where did this variable change?" because there are many places you changed.
If we have codes which we can't know where we change, these codes will be mysterious codes. It's so disgusting.
#Triptych 's answer is also right. If you adopt his answer, this codes will work. However I recommend that you don't use global.
p.s. You can do it in JavaScript.