Error in rock paper scissors game with Python - python

I'm trying to create a rock paper scissors game for a class assignment with Python, but I can't get the result out.
The game is supposed to start with the 1) user's input, 2) show what computer randomly chose, 3) the result (You win, You lose, or Tie with how you won or lost), 4) then ask if you want to Play again, and 5) finally escape.
I did succeed on the first 2 parts, but I can't figure out why 3, 4, 5 is not printing...
The result after showing what the computer played(2), it says 'None' then it loops back to (1) getting the input from the user.
Below is the code. Please advise me on how to fix them. Thank you so much!!
import random
while True :
player = input("Enter a number (0 for rock, 1 for paper, 2 for scissors) >>")
RPS = [0,1,2]
computer = random.choics(RPS)
RPS_dict = {0:'Rock', 1:'Paper', 2:'Scissors'}
print("The computer played", RPC_dict.get(computer))
def game(player, computer):
RPS_dict = {0:'Rock', 1:'Paper', 2:'Scissors'}
if player == computer:
print("Tie!")
elif player == 0:
if computer == 1:
print("You lose!", RPS_dict.get(computer), 'covers', RPS_dict.get(player))
else:
print("You win!", RPS_dict.get(player), 'cut', RPS_dict.get(computer))
elif player == 1:
if computer == 2:
print("You lose!", RPS_dict.get(computer), 'cut', RPS_dict.get(player))
else:
print("You win!", RPS_dict.get(player), 'covers', RPS_dict.get(computer))
game(player, computer)
print(game(player, computer))
again = input("Play again? 0 for no, 1 for yes\n")

Your function should be outside your while loop and you don't need to call it within a print statement...
import random
def game(player, computer):
if player == computer:
print('game tied')
else:
if (player == 1 and computer == 3) or (player == 2 and computer == 1) or (player == 3 and computer == 2):
print('you win')
else:
print('computer wins')
def choice(x):
y = None
if x == 1:
y = 'rock'
elif x == 2:
y = 'paper'
elif x == 3:
y = 'scissors'
return y
playing = True
while playing == True:
player_input = int(input("Enter 1 for rock, 2 for paper, 3 for scissors"))
print('You chose:'+ choice(player_input))
computer_input = random.choice([1,2,3])
print('Computer chose:'+ choice(computer_input))
game(player_input, computer_input)
restart = int(input("Enter 1 to play again or 2 to quit"))
if restart == 2:
playing = False

Related

My main function is repeating in an infinite loop and I do not know why

I am running a program that plays rock, paper, scissors. I have executed the code multiple times and everytime I do, the input asking the user to pick 0,1,2 repeats more than one time. It is only supposed to be asked one time per game cycle. Can anyone help me figure out why this is happening, and how to fix it?
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(getcomputerChoice, getplayerChoice):
if getplayerChoice == 0 and getcomputerChoice == 2:
return 1
elif getcomputerChoice == 0 and getplayerChoice == 2:
return -1
elif getplayerChoice == 2 and getcomputerChoice == 1:
return 1
elif getcomputerChoice == 2 and getplayerChoice == 1:
return -1
elif getplayerChoice == 1 and getcomputerChoice == 0:
return 1
elif getcomputerChoice == 1 and getplayerChoice == 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():
displayMenu()
getPlayerChoice()
if getPlayerChoice() == 0:
choicePlayer = "rock"
elif getPlayerChoice() == 1:
choicePlayer = "paper"
elif getPlayerChoice() == 2:
choicePlayer = "scissors"
getComputerChoice()
if getComputerChoice() == 0:
choiceComputer = "rock"
elif getComputerChoice() == 1:
choiceComputer = "paper"
elif getComputerChoice() == 2:
choiceComputer = "scissors"
print("You chose", choicePlayer + ".")
print("The computer chose", choiceComputer + ".")
playRound(getComputerChoice(), getPlayerChoice())
continueGame()
while continueGame() == True:
displayMenu()
getPlayerChoice()
getComputerChoice()
playRound(getComputerChoice(), getPlayerChoice())
continueGame()
playerCounter = 0
computerCounter = 0
tieCounter = 0
while playRound(getPlayerChoice(), getPlayerChoice()) == -1:
computerCounter += 1
while playRound(getPlayerChoice(), getPlayerChoice()) == 1:
playerCounter += 1
while playRound(getPlayerChoice(), getPlayerChoice()) == 0:
tieCounter += 1
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()
It's because when you do:
if getPlayerChoice() == 0:
choicePlayer = "rock"
You are actually calling the method again.
You should do:
p_choice = getPlayerChoice()
if p_choice == 0:
...

NameError: free variable 'player_one_rps' referenced before assignment in enclosing scope

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.

better write rock paper scissors (python)

Hey guys I'm new to python and I have made this simple rock paper scissors game but I wonder if there is a better way to program this without a super long if else statement.
import random
options = ["scissors", "paper", "rock"]
i = random.randint(0, (len(options) - 1))
playedHand = input("PLay rock, paper or scissors please: ")
computerPlayedHand = options[i]
if playedHand == "rock" and computerPlayedHand == "scissors":
print("the computer had scissors, you win")
elif playedHand == "rock" and computerPlayedHand == "paper":
print("the computer had paper, you lose")
elif playedHand == "rock" and computerPlayedHand == "rock":
print("the computer also had rock, its a tie")
elif playedHand == "paper" and computerPlayedHand == "rock":
print("the computer had rock, you win")
elif playedHand == "paper" and computerPlayedHand == "scissors":
print("the computer had scissors, you lose")
elif playedHand == "paper" and computerPlayedHand == "paper":
print("the computer also had paper, its a tie")
elif playedHand == "scissors" and computerPlayedHand == "paper":
print("the computer had paper, you win")
elif playedHand == "scissors" and computerPlayedHand == "scissors":
print("the computer also had scissors, its a tie")
elif playedHand == "scissors" and computerPlayedHand == "rock":
print("the computer had rock, you lose")
else:
print("please only state rock, paper or scissors")
Here is what I threw together trying to reuse your code where possible.
The key part is noticing that the options list can be treated as a cycle where an option always beats the next option. You can check this by finding the indices and then using modulo to make the indices cyclic.
import random
options = ["scissors", "paper", "rock"] # everything loses to the previous thing
comp_index = random.randint(0, (len(options) - 1))
playedHand = input("Play rock, paper or scissors please: ")
computerPlayedHand = options[comp_index]
try:
player_index = options.index(playedHand)
except ValueError:
print("please only state rock, paper or scissors")
else:
if player_index == comp_index:
res = "the computer also had {}, its a tie"
# the key part
elif (player_index - comp_index) % 3 == 1:
res = "the computer had {}, you lose"
else:
res = "the computer had {}, you win"
print(res.format(computerPlayedHand))
Using a dictionary to represent which hand beat which can significantly shorten your code. But since we are there, let's make this even neater with an object-oriented solution.
import random
class Hand:
_ordering = {
'rock': 'scissor',
'scissor': 'paper',
'paper': 'rock'
}
def __init__(self, kind):
if kind in self._ordering:
self.kind = kind
else:
raise ValueError(
"It's rock, paper, scissor... Not rock, {}, scissor.".format(kind)
)
#classmethod
def random_hand(cls):
return cls(random.choice(list(cls._ordering)))
def beats(self, other):
return self._ordering[self.kind] == other.kind
playedHand = Hand(input("Play rock, paper or scissors please: "))
computerPlayedHand = Hand.random_hand()
if playedHand.beats(computerPlayedHand):
print('You won! The computer had {}.'.format(computerPlayedHand.kind))
elif computerPlayedHand.beats(playedHand):
print('You lost... The computer had {}.'.format(computerPlayedHand.kind))
else:
print("It's a tie.")
You don't need to use any "if" statements other than typical error management. Look at the following example:
import random
def play():
table = [[2, 0, 1],
[1, 2, 0],
[0, 1, 2]]
options = ["Rock", "Paper", "Scissors"]
results = ["Defeat", "Win", "Tie"]
conv = {"R": 0 , "P": 1, "S": 2}
while True:
i = random.randint(0, (len(options) - 1))
p = input("Play rock, Paper or Scissors please (R, P, S): ")
if p not in conv.keys():
print("Unavailable option. Left the Game.")
return
print("Computer played %s. You have a %s"%(options[i], results[table[conv[p]][i]]))
play()
If you have a table like this:
# Rock Paper Scissor
# Rock 2 0 1
# Paper 1 2 0
# Scissor 0 1 2
...you can make the user play in rows, and the computer in columns. The result is being indexed directly by whatever is the number in the table. Thus playing the game in the example would look like this:
Here's another possible version:
import random
try:
options = [('rock', 'scissors'), ('paper', 'rock'), ('scissors', 'paper')]
human_choice = int(input("Play rock(0), paper(1) or scissors(2) please: "))
human_hand = options[human_choice]
computer_hand = options[random.randint(0, (len(options) - 1))]
text = "the computer {} {}, {}"
if human_hand[0] == computer_hand[0]:
print(text.format("also had", computer_hand[0], "it's a tie"))
elif human_hand[1] == computer_hand[0]:
print(text.format("had", computer_hand[0], "you win"))
else:
print(text.format("had", computer_hand[0], "you lose"))
except Exception as e:
print("please only state rock, paper or scissors")

Python: Rock Paper Scissors While Loop Issue

I'm having an issue with my programming of Rock, Paper, Scissors for Python. My issue occurs when there is a tie. When there is a tie, my program is supposed to going into a while loop within the if statement of the tie and reask the player the same question, rock, paper or scissors again until it breaks out of the tie. I have attached the link to the image of the issue:
In Round 5: you can see the issue.
I am taking an intro to programming class so I'm still a beginner and I do not know what I am doing wrong.
A Python program for the Rock, Paper, Scissors game.
import random
def rock_paper_scissors():
playerscore = 0
computerscore = 0
rounds = input('\nHow many points does it take to win?: ')
count = 1
while playerscore or computerscore != int(rounds):
print('\n********************* ROUND #',count,'*********************')
player = input('\nPick your throw: [r]ock, [p]aper, or [s]cissors?: ')
computerthrow = random.randint(0,2)
if (computerthrow == 0):
computer = "rock"
computer = 'r'
elif (computerthrow == 1):
computer = "paper"
computer = 'p'
elif (computerthrow == 2):
computer = "scissors"
computer = 's'
if (player == computer):
print('Tie!')
while (player == computer):
player = input('\nPick your throw: [r]ock, [p]aper, or [s]cissors?: ')
computerthrow = random.randint(0,2)
if (computerthrow == 0):
computer = "rock"
computer = 'r'
elif (computerthrow == 1):
computer = "paper"
computer = 'p'
elif (computerthrow == 2):
computer = "scissors"
computer = 's'
print(computer)
elif (player == 'r'):
if (computer == "p"):
print('Computer threw paper, you lose!')
computerscore=computerscore+1
else:
print('Computer threw scissors, you win!')
playerscore = playerscore+1
#count = count + 1
elif (player == 'p'):
if (computer == "r"):
print('Computer threw rock, you win!')
playerscore = playerscore+1
else:
print('Computer threw scissors, you lose!')
computerscore=computerscore+1
#count = count + 1
elif (player == 's'):
if (computer == "p"):
print('Computer threw paper, you win!')
playerscore = playerscore+1
else:
print('Computer threw rock, you lose!')
computerscore=computerscore+1
count = count + 1
print('\nYour score: ',playerscore)
print('Computer''s score: ',computerscore,'\n')
print('********************* GAME OVER ********************')
def main():
print('ROCK PAPER SCISSORS in Python')
print()
print('Rules: 1) Rock wins over Scissors.')
print(' 2) Scissors wins over Paper.')
print(' 3) Paper wins over Rock.')
rock_paper_scissors()
main()
Your problem comes from the way you have structured your control statements (if, elif, else). When you enter your tie while loop, you are constantly running it until someone wins and that looks like it works no problem. The issue is that once you do that, the python interpreter skips all elif and else statements in that control block (if I say if x == 3: do this else: do that) I don't want python to follow through with the else condition if x does indeed == 3). Sorry if that is confusing, long story short you need to make sure that even when your tie block gets executed you still move on to scoring the round and starting a new one. The easy way to do that is just change the elif (player == "r") to an if statement. That way the interpreter treats the scoring control sequence as its own block and it will always be executed once you assign the throws each player makes.
Example:
def f(x):
if (x == 0):
print("1")
x += 1
elif (x == 1):
print("2")
print("Done!")
def g(x):
if (x == 0):
print("1")
x += 1
if (x == 1):
print("2")
print("Done!")
if you call f(0):
Python will print out 1 and then Done!
if you call g(0):
Python will print out 1 then 2 then Done!
Your immediate problem is that you have the handling code for a tie in the same if/elif chain as the handling for the other scoring.
You say something like:
if tied
stuff
elif player == r
...
As a result, when there is a tie the game correctly loops until there is no tie. But then is skips over the code that updates the score, because that is how if/elif/else works!
An immediate fix would be to break that if/elif chain, and put the tie-handling into a separate if block:
if tied:
loop until not tied
# now do scoring
if player == 'r':
... etc
With that said, let me add a few more things:
You are assigning two values to the same variable, in sequence:
computer = 'rock'
computer = 'r'
This doesn't do anything, because the second overwrites the first. You should just delete the first line in each of those pairs.
You should probably write a function that repeatedly asks the user to pick one, until it gets either rock, paper, or scissors. Use a while loop.
There is a function in the random module that will pick an item from a list, tuple, or string and return it. You can use that to make the computer pick r,p,s directly.
You can simplify your code by determining the outcome in advance. Say you have the computer pick first. Then if the computer picks 'r', you know 'p' is a win and 's' is a lose. Store the win/lose picks in a pair of variables, and all your testing can be boiled down to one test:
computer = computer_pick()
if computer == 'r':
winner = 'p'
computer = 'rock'
elif computer == 'p':
...
player = player_pick()
if tied ...
if player == winner:
print("Computer picked", computer, "- you win!")
else:
...

Python rock paper scissors score counter

I am working on a rock paper scissors game. Everything seems to be working well except the win/loss/tie counter. I have looked at some of the other games people have posted on here and I still cannot get mine to work. I feel like I am soooooo close but I just can't get it! thanks for any help guys. this is my first time posting in here so I am sorry if I messed up the formatting.
I edited the code but still cannot get the program to recognize the counter without using global variables. at one point of my editing I managed to get it to count everything as a tie... i dont know how and I lost it somewhere along my editing. lol. -thanks again everyone!
here is what I get when I run the program:
Prepare to battle in a game of paper, rock, scissors!
Please input the correct number according
to the object you want to choose.
Select rock(1), paper(2), or scissors(3): 1
Computer chose PAPER .
You chose ROCK .
You lose!
Play again? Enter 'y' for yes or 'n' for no. y
Prepare to battle in a game of paper, rock, scissors!
Please input the correct number according
to the object you want to choose.
Select rock(1), paper(2), or scissors(3): 2
Computer chose PAPER .
You chose PAPER .
It's a tie!
Play again? Enter 'y' for yes or 'n' for no. y
Prepare to battle in a game of paper, rock, scissors!
Please input the correct number according
to the object you want to choose.
Select rock(1), paper(2), or scissors(3): 3
Computer chose SCISSORS .
You chose SCISSORS .
It's a tie!
Play again? Enter 'y' for yes or 'n' for no. n
Your total wins are 0 .
Your total losses are 0 .
Your total ties are 0 .
#import the library function "random" so that you can use it for computer
#choice
import random
#define main
def main():
#assign win, lose, and tie to zero for tallying
win = 0
lose = 0
tie = 0
#control loop with 'y' variable
play_again = 'y'
#start the game
while play_again == 'y':
#make a welcome message and give directions
print('Prepare to battle in a game of paper, rock, scissors!')
print('Please input the correct number according')
print('to the object you want to choose.')
#Get the player and computers choices and
#assign them to variables
computer_choice = get_computer_choice()
player_choice = get_player_choice()
#print choices
print('Computer chose', computer_choice, '.')
print('You chose', player_choice, '.')
#determine who won
winner_result(computer_choice, player_choice)
#ask the user if they want to play again
play_again = input("Play again? Enter 'y' for yes or 'n' for no. ")
#print results
print('Your total wins are', win, '.')
print('Your total losses are', lose, '.')
print('Your total ties are', tie, '.')
#define computer choice
def get_computer_choice():
#use imported random function from library
choice = random.randint(1,3)
#assign what the computer chose to rock, paper, or scissors
if choice == 1:
choice = 'ROCK'
elif choice == 2:
choice = 'PAPER'
else:
choice = 'SCISSORS'
#return value
return choice
#define player choice
def get_player_choice():
#assign input to variable by prompting user
choice = int(input("Select rock(1), paper(2), or scissors(3): "))
#Detect invalid entry
while choice != 1 and choice != 2 and choice != 3:
print('The valid numbers are rock(type in 1), paper(type in 2),')
print('or scissors(type in 3).')
choice = int(input('Enter a valid number please: '))
#assign what the player chose based on entry
if choice == 1:
choice = 'ROCK'
elif choice == 2:
choice = 'PAPER'
else:
choice = 'SCISSORS'
#return value
return choice
#determine the winner from the variables
def winner_result(computer_choice, player_choice):
#if its a tie, add 1 to tie variable and display message
if computer_choice == player_choice:
result = 'tie'
print("It's a tie!")
#if its a win, add to win tally and display message
elif computer_choice == 'SCISSORS' and player_choice == 'ROCK':
result = 'win'
print('ROCK crushes SCISSORS! You win!')
elif computer_choice == 'PAPER' and player_choice == 'SCISSORS':
result = 'win'
print('SCISSORS cut PAPER! You win!')
elif computer_choice == 'ROCK' and player_choice == 'PAPER':
result = 'win'
print('PAPER covers ROCK! You win!')
#if it does not match any of the win criteria then add 1 to lose and
#display lose message
else:
result = 'lose'
print('You lose!')
def result(winner_result,player_choice, computer_choice):
# accumulate the appropriate winner of game total
if result == 'win':
win += 1
elif result == 'lose':
lose += 1
else:
tie += 1
return result
main()
Your winner_result function returns before it increments the win counters. If you remove all the return statements from it, the counters should be updated. The return statements aren't needed anyway because the if/elif/else structure ensures that only one of the possible outcomes will be executed.
As Junuxx says in a comment, you also need to assign values to the winner_result variable properly, i.e. winner_result = 'win' instead of winner_result == 'win'. I'd also rename the winner_result variable or the function, because it's confusing to have both use the same name.
And the win/lose/tie variables are currently local, which means that main and winner_result will have their own copies of these variables, so main's values will always be zero. What you can do is make them global variables: Assign them to zero in the global scope (outside any function), and add the line global win, lose, tie inside the function winner_result.
Obviously been a few years since this question was answered but it came up while I was looking the same info. Here's my code if anyone is interested.
#! usr/bin/python3
import random
def game():
computer_count = 0
user_count = 0
while True:
base_choice = ['scissors', 'paper', 'rock']
computer_choice = random.choice(base_choice)
user_choice = input('(scissors, paper, rock) Type your choice: ').strip().lower()
print()
computer_wins = 'The computer wins!'
you_win = 'You win!'
print(f'You played {user_choice}, the computer played {computer_choice}')
if user_choice == 'scissors' and computer_choice == 'rock' or \
user_choice == 'paper' and computer_choice == 'scissors' or \
user_choice == 'rock' and computer_choice == 'paper':
print(computer_wins)
computer_count += 1
elif user_choice == 'rock' and computer_choice == 'scissors' or \
user_choice == 'scissors' and computer_choice == 'paper' or \
user_choice == 'paper' and computer_choice == 'rock':
print(you_win)
user_count += 1
else:
if user_choice == computer_choice:
print('Its a draw!')
computer_count += 1
user_count += 1
print(f'Computer: {computer_count} - You: {user_count}')
print()
game()
I was trying to do the same project, and I have found a solution that works well for me.
from random import randint
win_count = 0
lose_count = 0
tie_count = 0
# create a list of play options
t = ["Rock", "Paper", "Scissors"]
# assign a random play to the computer
computer = t[randint(0, 2)]
# set player to false
player = False
print()
print("To stop playing type stop at any time.")
print()
while player == False:
# set player to True
player = input("Rock, Paper or Scissors? ")
if player.lower() == "stop":
print()
print(
f"Thanks for playing! Your final record was {win_count}-{lose_count}-{tie_count}")
print()
break
if player.title() == computer:
print()
print("Tie!")
tie_count += 1
print()
elif player.title() == "Rock":
if computer == "Paper":
print()
print(f"You lose. {computer} covers {player.title()}.")
lose_count += 1
print()
else:
print()
print(f"You win! {player.title()} smashes {computer}.")
win_count += 1
print()
elif player.title() == "Paper":
if computer == "Scissors":
print()
print(f"You lose. {computer} cuts {player.title()}.")
lose_count += 1
print()
else:
print()
print(f"You win!, {player.title()} covers {computer}.")
win_count += 1
print()
elif player.title() == ("Scissors"):
if computer == "Rock":
print()
print(f"You lose. {computer} smashes {player.title()}.")
lose_count += 1
print()
else:
print()
print(f"You win! {player.title()} cuts {computer}.")
win_count += 1
print()
else:
print()
print("Sorry, we couldn't understand that.")
print()
# player was set to True, but we want it to be false to continue loop
print(f"Your record is {win_count}-{lose_count}-{tie_count}")
print()
player = False
computer = t[randint(0, 2)]
This works (kinda)
there are many issues with the code at the top of the page.
Firstly, Scoring doesn't work.
Secondly, nothing is indented meaning that nothing inside of the other def functions will work.
Thirdly, The other def functions are referred to in the first def main statement which causes Python to show an invalid syntax due to Python not knowing the other functions as they were referred to before they were introduced to python.

Categories

Resources