Function doesnt get called in while loop - python

I created the loss() , win() and draw() function to change the score following the events .The problem is that they are not getting called in the while loop to change the score and set it correctly. I had the score lines under every if and elif statement but decided to use a function to make the code shorter and more efficient.
from random import randint
print("Welcome to this game of rock paper scissors against the computer.")
print("Good luck and have fun! Enjoy this game! ")
print("To stop playing, type quit when the round ends.If you want to continue playing, press any key ")
scoreH=0
scoreAI=0
Round=0
def loss():
scoreH=scoreH+0
scoreAI=scoreAI+1
def win():
scoreH=scoreH+1
scoreAI=scoreAI+0
def draw():
scoreH=scoreH+0
scoreAI=scoreAi+0
x=True
while x == True :
# Choice
Round=Round+1
print("Round",Round,"is going to start. ")
print("1.Rock")
print("2.Paper")
print("3.Scissors")
choice=input("Enter your choice: ").lower()
IntChoice=randint(1,3)
#Transforming AI_choice from an int to a string
if IntChoice == 1:
AI_choice="rock"
elif IntChoice == 2:
AI_choice="paper"
elif IntChoice == 3:
AI_choice="scissors"
print(AI_choice)
# Draw
if choice==AI_choice:
draw()
print("The computer chose",choice,".You draw.")
# PlayerWins
elif choice=="paper" and AI_choice=="rock":
win()
print("The computer chose",choice,".You win.")
elif choice=="scissors" and AI_choice=="paper":
win()
print("The computer chose",AI_choice,".You win.")
elif choice=="rock" and AI_choice=="scissors":
win()
print("The computer chose",AI_choice,".You win.")
# AIwins
elif AI_choice=="paper" and choice=="rock":
loss()
print("The computer chose",AI_choice,".You lose.")
elif AI_choice=="scissors" and choice=="paper":
loss()
print("The computer chose",AI_choice,".You lose.")
elif AI_choice=="rock" and choice=="scissors":
loss()
print("The computer chose",AI_choice,".You lose.")
else:
print("Invalid input.")
continue
end=input()
# Stop Playing
if end == "stop" or end == "quit":
print("The score is :",scoreH,"-",scoreAI)
if scoreH > scoreAI:
print("You win.")
elif scoreH < scoreAI:
print("You lose.")
else:
print("You draw.")
break
else:
continue

They are indeed being called but they are modifying the local variable inside themselves.
To modify the values do something like this:
def loss(scoreAI):
return scoreAI+1
scoreAI = loss(scoreAI)
Actually, the functions are really simple and in some cases you're adding up 0 which is the same as doing nothing, so I wouldn't make functions for this. This is much simpler:
#Win
scoreH += 1
#Loss
scoreAI += 1
and you need nothing for draw.
I hope it helps!

import random
print("Welcome to this game of rock paper scissors against the computer.")
print("Good luck and have fun! Enjoy this game! ")
print("To stop playing, type quit when the round ends.If you want to continue playing, press any key ")
scoreH=0
scoreAI=0
Round=0
def loss():
global scoreH
global scoreAI
scoreH=scoreH+0
scoreAI=scoreAI+1
def win():
global scoreH
global scoreAI
scoreH=scoreH+1
scoreAI=scoreAI+0
def draw():
global scoreH
global scoreAI
scoreH=scoreH+0
scoreAI=scoreAI+0
x=True
while x == True :
# Choice
Round=Round+1
print("Round",Round,"is going to start. ")
print("1.Rock")
print("2.Paper")
print("3.Scissors")
choice=input("Enter your choice: ").lower()
IntChoice=random.randint(1,3)
#Transforming AI_choice from an int to a string
if IntChoice == 1:
AI_choice="rock"
elif IntChoice == 2:
AI_choice="paper"
elif IntChoice == 3:
AI_choice="scissors"
print(AI_choice)
# Draw
if choice==AI_choice:
draw()
print("The computer chose",choice,".You draw.")
# PlayerWins
elif choice=="paper" and AI_choice=="rock":
win()
print("The computer chose",choice,".You win.")
elif choice=="scissors" and AI_choice=="paper":
win()
print("The computer chose",AI_choice,".You win.")
elif choice=="rock" and AI_choice=="scissors":
win()
print("The computer chose",AI_choice,".You win.")
# AIwins
elif AI_choice=="paper" and choice=="rock":
scoreH,scoreAI=loss(scoreH,scoreAI)
print("The computer chose",AI_choice,".You lose.")
elif AI_choice=="scissors" and choice=="paper":
loss()
print("The computer chose",AI_choice,".You lose.")
elif AI_choice=="rock" and choice=="scissors":
loss()
print("The computer chose",AI_choice,".You lose.")
else:
print("Invalid input.")
#continue
end=input()
# Stop Playing
if end == "stop" or end == "quit":
x=False
print("The score is :",scoreH,"-",scoreAI)
if scoreH > scoreAI:
print("You win.")
elif scoreH < scoreAI:
print("You lose.")
else:
print("You draw.")
break
else:
continue
Expected Output:
Welcome to this game of rock paper scissors against the computer.
Good luck and have fun! Enjoy this game!
To stop playing, type quit when the round ends.If you want to continue playing, press any key
Round 1 is going to start.
1.Rock
2.Paper
3.Scissors
Enter your choice: rock
scissors
The computer chose scissors .You win.
Round 2 is going to start.
1.Rock
2.Paper
3.Scissors
Enter your choice: paper
paper
The computer chose paper .You draw.
Round 3 is going to start.
1.Rock
2.Paper
3.Scissors
Enter your choice: scissors
paper
The computer chose paper .You win.
Round 4 is going to start.
1.Rock
2.Paper
3.Scissors
Enter your choice: rock
scissors
The computer chose scissors .You win.
Round 5 is going to start.
1.Rock
2.Paper
3.Scissors
Enter your choice: rock
scissors
The computer chose scissors .You win.
Round 6 is going to start.
1.Rock
2.Paper
3.Scissors
Enter your choice: paper
scissors
The computer chose scissors .You lose.
Round 7 is going to start.
1.Rock
2.Paper
3.Scissors
Enter your choice: paper
scissors
The computer chose scissors .You lose.
Round 8 is going to start.
1.Rock
2.Paper
3.Scissors
Enter your choice:
paper
Invalid input.
stop
The score is : 4 - 2
You win.

Related

Do not want to let Computer play his turn once Player enters invalid choice. How to achieve?

I'm a beginner and writing a code for "Rock Paper Scissors" game. I don't want to run this game(code) over and over again, hence, used while loop. Now, at the "else:" step when any invalid choice is typed by the Player, Computer plays it's turn too after which "Invalid choice. Play your turn again!" is displayed.
I want when a Player types any invalid choice, the computer should not play it's turn and we get "Invalid choice. Play your turn again!" displayed, keeping the game running.
Please check my code and point me to the issue. Please explain with the correction. Thanks in advance!
print("Welcome to the famous Rock Paper Scissors Game. \n")
Choices = ["Rock", "Paper", "Scissors"]
while(True):
Player = input("Your turn: ")
Computer = random.choice(Choices)
print(f"Computer's turn: {Computer} \n")
if Player == Computer:
print("That's a tie, try again! \n")
elif Player == "Rock" and Computer == "Scissors":
print("You Won!!! \n")
elif Player == "Rock" and Computer == "Paper":
print("Computer won! \n")
elif Player == "Paper" and Computer == "Scissors":
print("Computer won! \n")
elif Player == "Paper" and Computer == "Rock":
print("You Won!!! \n")
elif Player == "Scissors" and Computer == "Paper":
print("You Won!!! \n")
elif Player == "Scissors" and Computer == "Rock":
print("Computer won! \n")
else:
print("Invalid choice. Play your turn again! \n")
You can check if the input is valid before the computer plays, and ask again if it is invalid using continue -
Choices = ["Rock", "Paper", "Scissors"]
while(True):
Player = input("Your turn: ")
if Player not in Choices: # If it is not in Choices list above
print("Invalid choice. Play your turn again! \n")
continue # This will re run the while loop again.
# If Player gives valid input, then continues this
Computer = random.choice(Choices)
print(f"Computer's turn: {Computer} \n")
# The next lines ....
Also check out - Break, Continue and Pass

Need code to let user make repeated attempts

I am new to coding so I am trying to create a Rock Paper Scissors Game. I have almost completed the game, but when the user and computer input the same number, I want the program to repeat until either one of the player wins. How can I do this? Any help is appreciated. Here is my code.
game = input("Want to play Rock Paper Scissors? (Y/N) ")
if game == "Y":
print("1 = Rock, 2 = Paper, 3 = Scissors")
print('')
user = int(input("You have one chance of beating me. Input a number. "))
print('')
import random
computer = random.randint(1,3)
if user == 1 and computer == 1:
print("Must play again! We both played Rock!")
elif user == 1 and computer == 2:
print("You lose! You played Rock and I played Paper!")
elif user == 1 and computer == 3:
print("You win! You played Rock and I played Scissors!")
elif user == 2 and computer == 1:
print("You win! You played Paper and I played Rock!")
elif user == 2 and computer == 2:
print("Must play again! We both played Paper!")
elif user == 2 and computer == 3:
print("You lose! You played Paper and I played Scissors!")
elif user == 3 and computer == 1:
print("You lose! You played Scissors and I played Rock!")
elif user == 3 and computer == 2:
print("You win! You played Scissors and I played Paper!")
elif user == 3 and computer == 3:
print("Must play again! We both played Scissors!")
else:
print("Not a number.")
else:
print("Fine. Bye.")
You could put the whole if-elif-block in a while-loop that will repeat until you have a winner. In order to determine if there is a winner, use a boolean variable.
winner = False
while not winner:
if ...... ## Your if-elif-block
elif user == 1 and computer == 2:
print("You lose! You played Rock and I played Paper!")
winner = True
## Your remaining if-elif-block
You only put the command winner=True in the command blocks of the conditions that have a winner. So, the loop will continue until you hit one of these conditions.
You could also choose to use a more advanced winner variable (0 for draw, 1 for player, 2 for computer) to use the value in a goodbye-message.
One way would be to use a while loop, breaking when a condition is satisfied.
while True:
if (condition):
print("")
break
...
The while statement repeats the loop until one of the conditions is satisfied. The break statement causes the program to exit the loop and move on to the next executable statement.
(to learn more google anything in quotes :)
using a "while loop" to create a "game loop". I learned this trick from making small games in python. Also, you want to learn to use "classes" as the logic and the code can be improved using "OOP concepts".T code has been tested and works.
import random
#Create a "function" that meets the requirements of a "game loop"
def gameloop():
game = input("Want to play Rock Paper Scissors? (Y/N) ")
if game == "Y":
#Create a "while loop" to host the logic of the game.
#Each If statement will enable one "rule" of the game logic.
#game logic could be redesigned as an "Event".
#You can add a game "Event System" to your future project backlog
winner = False
while not winner:
print("1 = Rock, 2 = Paper, 3 = Scissors")
print('')
user = int(
input("You have one chance of beating me. Input a number. "))
print('')
computer = random.randint(1, 3)
if user == 1 and computer == 2:
print("You lose! You played Rock and I played Paper!")
winner = True
elif user == 1 and computer == 3:
print("You win! You played Rock and I played Scissors!")
winner = True
elif user == 2 and computer == 1:
print("You win! You played Paper and I played Rock!")
winner = True
elif user == 2 and computer == 3:
print("You lose! You played Paper and I played Scissors!")
winner = True
elif user == 3 and computer == 1:
print("You lose! You played Scissors and I played Rock!")
winner = True
elif user == 3 and computer == 2:
print("You win! You played Scissors and I played Paper!")
winner = True
elif user == 1 and computer == 1:
print("Must play again! We both played Rock!")
elif user == 2 and computer == 2:
print("Must play again! We both played Paper!")
elif user == 3 and computer == 3:
print("Must play again! We both played Scissors!")
else:
print("Not a number.")
else:
print("game....over?")
gameloop()
I took the time to do an OOP Class example too! it could be optimized in many ways. However, I hope it shows you the next level of study! I also hope it helps you look into all the crazy design patterns and Game Programming Techniques you can apply as you learn.
import random
# we can create a player class to be used as an "interface" as we design the games logic
# this will let us scale the features be build in our game
# in this case i will leave it to you to add Wins to the scoreboard to help you learn
class player:
# your games requerment wants your players to make a choice from 1-3
choice = 0
# your games may requerment a player to be defined as the winner
win = 0
# your games may requerment a player to be defined as the losser
loss = 0
class game:
# by using classes and OOP we can scale the data and logic of your game
# here we create instances of the class player and define new objects based on your "requerments"
# your "requerments" where to have one Computer as a player, and one user as a player
computer = player()
user = player()
# this "function" will create a Scoreboard feature that can be called in the 'game loop' or in a future "event" of the game.
# Like a "Game Stats stage" at the end of the game
def Scoreboard(self, computer, user):
Computer = computer.loss
User = user.loss
print("+============= FINAL RESULTS: SCOREBOARD!! ======+ ")
print(" ")
print("Computer losses: ", Computer)
print("Player losses: ", User)
print(" ")
# Create a "function" that meets the requirements of a "game loop"
def main_loop(self, computer, user):
gameinput = input("Want to play Rock Paper Scissors? (Y/N) ")
if gameinput == "Y":
# Create a "while loop" to host the logic of the game.
# Each If statement will enable one "rule" of the game logic.
# game logic could be redesigned as an "Event".
# You can add a game "Event System" to your future project backlog
winner = False
while not winner:
print("1 = Rock, 2 = Paper, 3 = Scissors")
print('')
# we create 'Player1' as the user
Player1 = user
# we change the 'Player1' 'choice' to the user input
Player1.choice = int(
input("You have one chance of beating me. Input a number. "))
print('')
# we pull in to the game the computer player and call them 'Player1'
Player2 = computer
# we change the 'Player2' 'choice' to a random number
Player2.choice = random.randint(1, 3)
if user.choice == 1 and computer.choice == 2:
print("You lose! You played Rock and I played Paper!")
winner = True
user.loss += 1
elif user.choice == 1 and computer.choice == 3:
print("You win! You played Rock and I played Scissors!")
winner = True
computer.loss += 1
elif user.choice == 2 and computer.choice == 1:
print("You win! You played Paper and I played Rock!")
winner = True
computer.loss += 1
elif user.choice == 2 and computer.choice == 3:
print("You lose! You played Paper and I played Scissors!")
winner = True
user.loss += 1
elif user.choice == 3 and computer.choice == 1:
print("You lose! You played Scissors and I played Rock!")
winner = True
user.loss += 1
elif user.choice == 3 and computer.choice == 2:
print("You win! You played Scissors and I played Paper!")
winner = True
computer.loss += 1
elif user.choice == 1 and computer.choice == 1:
print("Must play again! We both played Rock!")
elif user.choice == 2 and computer.choice == 2:
print("Must play again! We both played Paper!")
elif user.choice == 3 and computer.choice == 3:
print("Must play again! We both played Scissors!")
else:
print("Not a number.")
# by returning "self" you call the same 'instances' of game that you will define below
return self.Scoreboard(user, computer)
else:
print("game....over?")
# define Instance of game as "test_game"
test_game = game()
# run game loop
test_game.main_loop()

I am working on a rock, paper, scissors program using functions and it is always returning else cases

I am looking for some input on a rock, paper, scissors program that I am making where the statements in the main() and determineWinner that use playerChoice always terminate in the else: case. Each trial will output the player chooses scissors and that the game is tied. I am not sure where I went wrong here as I've printed the input to confirm it is correct before sending to it to the other functions. I cannot figure what pare of the above to function is causing the problem, if anyone could point me in the right direction here I would be grateful.
Here is the code I have so far:
import random
# define main function
def main():
# initialize playAgain to start game, set stats to 0
playAgain = 'y'
numberTied = 0
numberPlayerWon = 0
numberComputerWon = 0
print("Let's play a game of rock, paper, scissors.")
# loop back to play again if user confirms
while playAgain == 'y' or playAgain == 'Y':
computerChoice = processComputerChoice()
playerChoice = processPlayerChoice()
# display computer choice
if computerChoice == 1:
print('The computer chooses rock.')
elif computerChoice == 2:
print('The computer chooses paper.')
else:
print('The computer chooses scissors.')
# display player choice
if playerChoice == 1:
print('You choose rock.')
elif playerChoice == 2:
print('You choose paper.')
else:
print ('You choose scissors.')
# assign who won to result and add total wins/ties to accumulator
result = determineWinner(playerChoice, computerChoice)
if result == 'computer':
numberComputerWon += 1
elif result == 'player':
numberPlayerWon += 1
else:
numberTied += 1
# ask player if they would like to play again
print('')
print
playAgain = input('Do you want to play again? (Enter y or Y to start another game)')
print('')
else:
# print accumulated wins and ties for computer and player
print('There were', numberTied, 'tie games played.')
print('The computer won', numberComputerWon, 'game(s).')
print('The player won', numberPlayerWon, 'game(s).')
print('')
# define computer choice function
def processComputerChoice():
# randomly select an option for the computer to play
randomNumber = random.randint(1,3)
print(randomNumber)
return randomNumber
# define player choice function
def processPlayerChoice():
choice = int(input(('What is your choice? Enter 1 for rock, 2 for paper, or 3 for scissors. ')))
print (choice)
# throw error if player makes invalid choice
while choice != 1 and choice != 2 and choice != 3:
print('ERROR: please input a valid choice of 1, 2, or 3')
choice = int(input('Please enter a correct choice: '))
return choice
# definition for the function to determine the winner
def determineWinner(playerChoice, computerChoice):
# determine player choice and compare to computer choice to determine the winner
if computerChoice == 1:
if playerChoice == 2:
print('Paper covers rock. You are victorious!')
winner = 'player'
elif playerChoice == 3:
print('Rock bashes scissors. The computer is victorious!')
winner = 'computer'
else:
print('The game is tied. Try again 1')
winner = 'tied'
if computerChoice == 2:
if playerChoice == 1:
print('Paper covers rock. The computer is victorious!')
winner = 'computer'
elif playerChoice == 3:
print('Scissors slice paper. You are victorious!')
winner = 'player'
else:
print('The game is tied. Try again 2')
winner = 'tied'
if computerChoice == 3:
if playerChoice == 1:
print('Rock bashes scissors. You are victorious!')
winner = 'player'
elif playerChoice == 2:
print('Scissors slice paper. The computer is victorious!')
winner = 'computer'
else:
print('The game is tied. Try again 3')
winner = 'tied'
return winner
main()
input("Press Enter to continue")
The return statement of your function processPlayerChoice has incorrect indentation. It should be out of while loop (unindent it one level)
At the moment, if player enters correct choice your function will return None.
If user enters incorrect choice, it will enter the while loop and will return whatever the second input from user is.
def processPlayerChoice():
choice = int(input(('What is your choice? Enter 1 for rock, 2 for paper, or 3 for scissors. ')))
print (choice)
# throw error if player makes invalid choice
while choice != 1 and choice != 2 and choice != 3:
print('ERROR: please input a valid choice of 1, 2, or 3')
choice = int(input('Please enter a correct choice: '))
return choice
Make sure to align your return statements with the function body. Currently in both processPlayerChoice and determineWinner they are aligned with the conditional loops, and thus will not be reached every time.

Rock Paper Scissors Running Twice Error

I'm new to programming. I have written code for the rock paper scissors game but there is one bug that I can't seem to fix. When the game closes, the user is asked if he wants to play again. If the user answers yes the first time, then plays again then answers no the second time, the computer for some reason asks the user again if he wanted to play again. The user must enter no in this case. This is because although the user answers no, the answer gets reset to yes and goes over again. How can this be fixed?
# This code shall simulate a game of rock-paper-scissors.
from random import randint
from time import sleep
print "Welcome to the game of Rock, Paper, Scissors."
sleep(1)
def theGame():
playerNumber = 4
while playerNumber == 4:
computerPick = randint(0,2)
sleep(1)
playerChoice = raw_input("Pick Rock, Paper, or Scissors. Choose wisely.: ").lower()
sleep(1)
if playerChoice == "rock":
playerNumber = 0
elif playerChoice == "paper":
playerNumber = 1
elif playerChoice == "scissors":
playerNumber = 2
else:
playerNumber = 4
sleep(1)
print "You cookoo for coco puffs."
print "You picked " + playerChoice + "!"
sleep(1)
print "Computer is thinking..."
sleep(1)
if computerPick == 0:
print "The Computer chooses rock!"
elif computerPick == 1:
print "The Computer chooses paper!"
else:
print "The Computer chooses scissors!"
sleep(1)
if playerNumber == computerPick:
print "it's a tie!"
else:
if playerNumber < computerPick:
if playerNumber == 0 and computerPick == 2:
print "You win!"
else:
print "You lose!"
elif playerNumber > computerPick:
if playerNumber == 2 and computerPick == 0:
print "You lose!"
else:
print "You win!"
replay()
def replay():
sleep(1)
playAgain = "rerun"
while playAgain != "no":
playAgain = raw_input("Would you like to play again?: ").lower()
if playAgain == "yes":
sleep(1)
print "Alright then brotha."
sleep(1)
theGame()
elif playAgain == "no":
sleep(1)
print "Have a good day."
sleep(1)
print "Computer shutting down..."
sleep(1)
else:
sleep(1)
print "What you said was just not in the books man."
sleep(1)
theGame()
This is because of the way the call stack is created.
The First time you play and enter yes to play again, you are creating another function call to theGame(). Once that function call is done, your program will continue with the while loop and ask if they want to play again regardless if they entered no because that input was for the second call to theGame().
To fix it, add a break or set playAgain to no right after you call theGame() when they enter yes
while playAgain != "no":
playAgain = raw_input("Would you like to play again?: ").lower()
if playAgain == "yes":
sleep(1)
print "Alright then brotha."
sleep(1)
theGame()
break ## or playAgain = "no"
You should break out of the loop after calling theGame. Imagine you decided to play again 15 times. Then there are 15 replay loops on the stack, waiting to ask you if you want to play again. Since playAgain is "yes" in each of these loops, each is going to ask you again, since playAgain is not "no"

Rock paper scissors AI issue

I'm building a simple rock paper scissors game. It works fine, except for the fact that the game won't stop when comp_count reaches 3. I can't seem to understand why, since it works fine for player_count. Help me out please!
from random import randint
player_count = 0
comp_count = 0
def game():
player_choice = raw_input('Do you choose rock [r], paper [p], or scissors [s]? ')
computer_choice = randint(0,2)
#Rock = 0 Paper = 1 Scissors = 2
#Player chooses paper, computer chooses rock
if player_choice == "p" and computer_choice == 0:
print 'Computer chose rock'
player_won()
#Player chooses rock, computer chooses scissors
elif player_choice == 'r' and computer_choice == 2:
print 'Computer chose scissors'
player_won()
#Player chooses scissors, computer chooses paper
elif player_choice == 's' and computer_choice == 1:
print 'Computer chose paper'
player_won()
#Computer chooses paper, player chooses rock
elif player_choice == 'r' and computer_choice == 1:
print 'Computer chose paper'
computer_won()
#Computer chooses rock, player chooses scissors
elif player_choice == 's' and computer_choice == 0:
print 'Computer chose rock'
computer_won()
#Computer chooses scissors, player chooses paper
elif player_choice == 'p' and computer_choice == 2:
print 'Computer chose scissors'
computer_won()
#Ties
elif player_choice == 'r' and computer_choice == 0:
print "It's a tie!"
game()
elif player_choice == 's' and computer_choice == 2:
print "It's a tie!"
game()
elif player_choice == 'p' and computer_choice == 1:
print "It's a tie!"
game()
#Wrong input
else:
print 'Please try again.'
game()
def player_won():
global player_count
print 'You win!'
player_count += 1
print 'You have ' + str(player_count) + ' point(s).'
while player_count < 3:
game()
def computer_won():
global comp_count
print 'Computer wins!'
comp_count += 1
print 'Computer has ' + str(comp_count) + ' point(s).'
while comp_count < 3:
game()
print 'Welcome to Rock, Paper, Scissors! First to 3 points wins it all.'
game()
Your while loops are whats causing your problem. Simply change while to a if in your player_won and computer_won functions and it fixes the issue.
def player_won():
global player_count
print 'You win!'
player_count += 1
print 'You have ' + str(player_count) + ' point(s).'
if player_count < 3:
game()
def computer_won():
global comp_count
print 'Computer wins!'
comp_count += 1
print 'Computer has ' + str(comp_count) + ' point(s).'
if comp_count < 3:
game()
Now go rock paper scissors your heart out!
I admit this isn't really a direct answer to your question, but I feel it might be useful to have a potentially simpler way to write this brought up.
You could make the user choose from three different numbers in the input instead of letters, or just convert the letters to numbers. One advantage of this is that to test for a tie, you could simply write:
if player_choice == computer_choice:
Even checking for who won in a game if it wasn't a tie wouldn't be very difficult, since if it is all numeric, an option that beats another one will be one away from it in a certain direction. So, for example, you could test if the player won like so:
winning = computer_choice - 1
if winning == -1: winning = 2
if player_choice == wining:
player_won()
else: #assuming we have already checked if it is a tie, we can say that otherwise the computer won.
computer_won()
If each number represented a different option (for example if you had a dictionary linking 0 to rock, 1 to scissors, and 2 to paper), then this would check if the user chose the option before the computer's, which would be the winning option.
That would actually let you check for who won and with which options with relatively few if statements. Your check could look something like this:
options = {0: "rock", 1:"scissors", 2:"paper"}
#collect player and computer choice here
print "computer chose "+options[computer_choice] #We will probably tell them what the computer chose no matter what the outcome, so might as well just put it once up here now that a variable can determine what the computer chose.
if player_choice == computer_choice:
print "It's a tie!"
game()
winning = computer_choice - 1
if winning == -1: winning = 2
if player_choice == wining:
player_won()
else: #assuming we have already checked if it is a tie, we can say that otherwise the computer won.
computer_won()
This isn't really necessary for making your code work, but I think it will be useful if you are interested.

Categories