Rock Paper Scissors not working - python

I have a game of Rock Paper Scissors with an AI that learns from you by trying everything until it gets a good algorithm, but my code stops working as soon as the AI gets a point, can someone help?
import random
print "Rock. Paper. Scissors. Awesome, a quick project made by me"
a = ["R", "P", "S"]
Ai = 0
Player = 0
samples = ['R']
l = 't'
c = random.choice(a)
play = 0
rndm = ['r.c', '+', '-']
count = 0
max = len(samples)
it = 0
def learn():
global rndm
global samples
global Ai
global Player
global l
global play
global c
global max
global it
number = random.randint(1,5)
if l == 'p':
#Random Learning
choice = random.choice(rndm)
if choice == "-":
choicetwo = random.randint(0,len(samples))
if choicetwo == len(samples):
choicetwo -= 1
samples.pop(choicetwo)
if len(samples) == 0:
q = random.choice(a)
samples.append(q)
if choice == "+":
q = random.choice(a)
samples.append(q)
if choice == "r.c":
choicetwo = random.randint(0,len(samples))
if choicetwo == len(samples):
choicetwo -= 1
samples.pop(choicetwo)
samples.insert(choicetwo,random.choice(a))
if l == 'a':
if it > max:
it = 0
print "oh"
if it < max:
it += 1
it1 = it - 1
c = samples[it1:it1 + 1]
print "Ok"
loop()
def loop():
global a
global Ai
global Player
global l
global c
global play
b = raw_input("R, P, or S? :")
b = b.upper()
if b != "R" and b != "P" and b != "S":
loop()
elif b == "R" and c == "S":
print "Rock .VS. Scissors"
print "You win!"
Player += 1
l = 'p'
elif b == "R" and c == "P":
print "Rock .VS. Paper"
print "You lose!"
Ai += 1
l = 'a'
elif b == c:
print "Tie!"
l = 'p'
elif b == "R" and c == "R":
# Just for errors
print "Tie!"
l = 'p'
elif b == "P" and c == "R":
print "Paper .VS. Rock"
print "You win!"
Player += 1
l = 'p'
elif b == "P" and c == "S":
print "Paper .VS. Scissors"
print "You lose!"
Ai += 1
l = 'a'
elif b == "S" and c == "R":
print "Scissors .VS. Rock"
print "You lose!"
Ai += 1
l = 'a'
elif b == "S" and c == "P":
print "Scissors .VS. Paper"
print "You win!"
Player +=1
l = 'p'
print ""
print "Ai: " + str(Ai) + ", Player: " + str(Player)
print ""
play += 1
learn()
loop()

Related

How to make a function to score a Rock, Paper and Scissor game in Python?

I wrote a Rock, Paper and Scissor game in Python. And I want to have a function that scores the game. The only way I managed to do that was by using global variables inside the function. I know that's not a good practice and I'd like to know how can I make this function without the need for global variables.
import random
def validate_user_input(input):
"""Verify if user input is a valid."""
try:
usr_input = int(input)
except:
return 0
else:
if (usr_input >= 1) and (usr_input <= 3):
return usr_input
else:
return 0
def compare_results(player_choice):
"""Get computer choice and compare it with user choice"""
computer_option = random.randint(1,3)
result_to_word = {0:'- Draw', 1:'- You loose.', 2:'- You Win'}
if player_choice == computer_option:
result = 0
if (player_choice == 1 and computer_option == 2):
result = 1
if (player_choice == 1 and computer_option == 3):
result = 2
if (player_choice == 2 and computer_option == 1):
result = 2
if (player_choice == 2 and computer_option == 3):
result = 1
if (player_choice == 3 and computer_option == 1):
result = 1
if (player_choice == 3 and computer_option == 2):
result = 2
return (result, result_to_word[result], computer_option)
def codify_result(input):
"Transform number of choice into word"
num_to_word = {1: "Rock", 2: "Paper", 3:"Scissor"}
return num_to_word[input]
def make_score(result):
global computer_score
global player_score
if result == 1:
computer_score += 1
elif result == 2:
player_score += 1
player_score = 0
computer_score = 0
intro = "\nHello!\nLet's play 'Rock, Paper and Scissors'.\nChoose an option and wait to see the result (Press 'q' at any time to exit)"
print(intro)
while True:
user_input = input("\n1) Rock, 2) Paper os 3) Scissors?: ")
if (user_input == 'q'):
break
else:
user_choice = validate_user_input(user_input)
if user_choice == 0:
print("You have to choose a number between 1 and 3.")
else:
result = compare_results(user_choice)
print("You chose: " + codify_result(user_choice) + ".")
print("The computer chose: " + codify_result(result[2]) + '.')
print(result[1])
make_score(result[0])
print("You: " + str(player_score) + "\nComputer: " + str(computer_score))
So how could I implement this function in a better way?
A "pure functional" approach could be to change your make_score function to take the old scores as arguments, and then return the updated scores:
def make_score(result, computer_score, player_score):
if result == 1:
computer_score += 1
elif result == 2:
player_score += 1
return computer_score, player_score
When you call make_score you pass the old scores and assign the new scores:
computer_score, player_score = make_score(result[0], computer_score, player_score)
Taking a step back, though, I might suggest taking an approach that doesn't require you to have a function that translates an opaque result int value into a modification to one or another variable. Maybe put the scores in a dict:
scores = {
"computer": 0,
"player": 0,
}
and then instead of a magic result int, assign a winner that matches one of the dict keys:
if (player_choice == 1 and computer_option == 2):
winner = "computer"
and then you can get rid of the make_score function completely and just do:
scores[winner] += 1
I would recommend making a dictionary which you can then pass into make_score
score_dict = {'computer_score': 0, 'player_score': 0}
make_score(score_dict, result):
if result == 1:
score_dict['computer_score'] += 1
...

Rock Paper Scissor Loop Issue Python

As most learning python I have been tasked with making a game of rock paper scissor. As of right now I have a put together a code that works if you just run it through once. My issue is that it needs to run on a loop, running until either the user or the computer wins three times. This is what I have without putting the loop in place:
ug = input("Please enter your choice for: rock, paper, or scissors: ")
comp = [ ]
user = [ ]
random = np.random.randint(0, 3, 1)
# 1). Converts the randomly generated computer guess to str
def guessC(random):
if random == 0:
return ("R")
if random == 1:
return ("S")
if random == 2:
return ("P")
compg = guessC(random)
# prints the user guess (ug) and comp guess (compg)
print("You guessed: ", ug)
print("The computer guessed: ", compg)
#2). Determine winner
def rockpaperscisccor(compg, ug):
if compg == "R":
if ug == "R":
return 0,0
elif ug == "S":
return 1,0
elif ug == "P":
return 0,1
if compg == "P":
if ug == "P":
return 0,0
elif ug == "R":
return 1,0
elif ug == "S":
return 0,1
if compg == "S":
if ug == "S":
return 0,0
elif ug == "P":
return 1,0
elif ug == "R":
return 0,1
cs,us = rockpaperscisccor(compg, ug)
# 3). take scores of game and append comp score to its own list and user score to
# own list
def tallyuserH(us):
user = [ ]
user.append(us)
tus = 0
for i in user:
tus += i
return tus
sus = tallyuserH(us)
def compuserH(cs):
comp = [ ]
comp.append(cs)
tcs = 0
for i in comp:
tcs += i
return tcs
scs = compuserH(cs)
# 4). Score counter to determine score
def scorecounter(scs, sus):
if scs == 3:
print("The computer wins!", cs, "-", us, "!")
elif sus == 3:
print("You win!", us, "-", cs, "!")
elif scs > sus:
print("The computer leads!", cs, "-", us, "!")
elif sus > scs:
print("You lead!", us, "-", cs, "!")
elif sus == scs:
print("The score is tied at", cs, "-", us, "!")
else:
print("That doesn't seem to be a valid input")
scorecounter(scs,sus)
This is what I have got so far when I put it into a while loop. it's running infinitely where as I wanted it to stop when one player gets to 3:
print("Lets play rock, paper, scissor!")
def thegame():
i = 0
ug = input("Please enter your choice for: rock, paper, or scissors: ")
random = np.random.randint(0, 3, 1)
compg = guess(random)
print("You guessed: ", ug)
print("The computer guessed: ", compg)
cs,us = rockpaperscisccor(compg, ug)
sus = tallyuser(us)
scs = compuser(cs)
print ("user score is", sus)
print ("comp score is", scs)
while i < 6:
if scs == 3:
print("The computer wins!", cs, "-", us, "!")
elif sus == 3:
print("You win!", us, "-", cs, "!")
elif scs > sus:
print("The computer leads!", cs, "-", us, "!")
elif sus > scs:
print("You lead!", us, "-", cs, "!")
elif sus == scs:
print("The score is tied at", cs, "-", us, "!")
else:
print("That doesnt seem to be a valid input")
i += 1
return i
def guess(random):
if random == 0:
return ("R")
if random == 1:
return ("S")
if random == 2:
return ("P")
def tallyuser(us):
user = [ ]
user.append(us)
tus = 0
for i in user:
tus += i
return tus
def compuser(cs):
comp = [ ]
comp.append(cs)
tcs = 0
for i in comp:
tcs += i
return tcs
thegame()
I can't figure out how to structure the While loop. Also the "score counter function" needs to remain its own piece, just meaning I can't nest that part in where I determine the winner. If that makes sense!
Thank you,
Rachel
Tried my best to keep the essence of your existing code, and not change it too much:
import random
def get_round_points(comp_choice, user_choice):
if comp_choice == "R":
if user_choice == "R":
return 0, 0
elif user_choice == "S":
return 1, 0
elif user_choice == "P":
return 0, 1
if comp_choice == "P":
if user_choice == "P":
return 0, 0
elif user_choice == "R":
return 1, 0
elif user_choice == "S":
return 0, 1
if comp_choice == "S":
if user_choice == "S":
return 0, 0
elif user_choice == "P":
return 1, 0
elif user_choice == "R":
return 0, 1
def get_choice():
valid_choices = {'R', 'P', 'S'}
choice = ''
while choice not in valid_choices:
choice = input("Please enter your choice from (R)ock, (P)aper, or (S)cissors: ")
return choice
def score_counter(current_comp_score, current_user_score, win_threshold):
if current_comp_score == win_threshold:
print("The computer wins!", current_comp_score, "-", current_user_score, "!")
elif current_user_score == win_threshold:
print("You win!", current_user_score, "-", current_comp_score, "!")
elif current_comp_score > current_user_score:
print("The computer leads!", current_comp_score, "-", current_user_score, "!")
elif current_user_score > current_comp_score:
print("You lead!", current_user_score, "-", current_comp_score, "!")
elif current_user_score == current_comp_score:
print("The score is tied at", current_comp_score, "-", current_user_score, "!")
else:
print("That doesn't seem to be a valid input to score_counter...")
def play_rock_paper_scissors(win_threshold):
comp_score, user_score = 0, 0
while comp_score != win_threshold and user_score != win_threshold:
score_counter(comp_score, user_score, win_threshold)
user_choice = get_choice()
print("You guessed: ", user_choice)
comp_choice = ['R', 'P', 'S'][random.randint(0, 2)]
print("The computer guessed: ", comp_choice)
round_result = get_round_points(comp_choice, user_choice)
comp_score += round_result[0]
user_score += round_result[1]
score_counter(comp_score, user_score, win_threshold)
if __name__ == '__main__':
play_rock_paper_scissors(3)
Example Usage:
The score is tied at 0 - 0 !
Please enter your choice from (R)ock, (P)aper, or (S)cissors: R
You guessed: R
The computer guessed: S
You lead! 1 - 0 !
Please enter your choice from (R)ock, (P)aper, or (S)cissors: P
You guessed: P
The computer guessed: R
You lead! 2 - 0 !
Please enter your choice from (R)ock, (P)aper, or (S)cissors: S
You guessed: S
The computer guessed: R
You lead! 2 - 1 !
Please enter your choice from (R)ock, (P)aper, or (S)cissors: S
You guessed: S
The computer guessed: P
You win! 3 - 1 !

Avoid a recurring loop that repeats an instruction every time it reaches the end

My problem is, my rock, paper, scissors program seems trapped in a loop somewhere. I suspect it's either the inner loop that asks the user for the number of rounds, or the outer loop that asks the user how many players should play; both might even have indentation problems but I am not sure.
import random
from os import system, name
from time import sleep
#variable declarations and initializations
computer,players, rounds, wins, loses, draws, yourPlay, count, rec, playerRange = 0, 0, 0, 0, 0, 0, 0, 0, 0, 3
#function definitions
def RoundsWonResult():
print ("You played:",playerMoves[yourPlay])
print ("The computer played:",playerMoves[computer])
print (playerMoves[yourPlay] + " beats " + playerMoves[computer] +"!")
print ("You win!")
return
def RoundsLostResult():
print ("You played:",playerMoves[yourPlay])
print ("The computer played:",playerMoves[computer])
print (playerMoves[computer] + " beats " + playerMoves[yourPlay] +"!")
print ("You lose!")
return
def DrawMatch():
global draws
while (yourPlay == computer):
print ("You played:",playerMoves[yourPlay])
print ("The computer played:",playerMoves[computer])
print ("It's a draw!")
draws+=1
return
def WinsMatch():
global wins
while (yourPlay != computer):
if (yourPlay == 0 and computer != 1):
if (computer == 2):
RoundsWonResult()
wins+=1
elif (yourPlay == 1 and computer == 0):
if (computer != 2):
RoundsWonResult()
wins+=1
elif (yourPlay == 2 and computer != 0):
if (computer == 1):
RoundsWonResult()
wins+=1
return
def LosesMatch():
global loses
while (yourPlay != computer):
if (yourPlay == 0 and computer == 1):
if (computer != 2):
RoundsLostResult()
loses+=1
elif (yourPlay == 1 and computer == 2):
if (computer != 0):
RoundsLostResult()
loses+=1
elif (yourPlay == 2 and computer == 0):
if (computer != 1):
RoundsLostResult()
loses+=1
return
try:
players = int(input("Enter number of players[1-3]:"))
while (players < 1 or players > playerRange):
print ("Invalid range selected!")
players = int(input("Enter number of players[1-3]:"))
except ValueError:
print ("Only numeric values are allowed!")
players = int(input("Enter number of players[1-3]:"))
if (players > 0 and players <= 3):
print ("Good luck to all " + str(players) + " of you. May the better player win!")
while (rec < players):
try:
rounds = int (input("Enter number of rounds to play:"))
while (rounds <= 0):
print ("Value must be greater than zero!")
rounds = int (input("Enter number of rounds to play:"))
print(rec)
print(rounds)
except ValueError:
print ("Only numeric values are allowed!")
rounds = int (input("Enter number of rounds to play:"))
if (rounds != "" and rounds > 0):
print ("Let the games begin!")
else:
print ("Rock beats Scissors, Scissors beats Paper, and Paper beats Rock. Good Luck!")
print("You entered " + str(rounds) + " round(s)!")
playerMoves = ["Rock","Paper","Scissors"]
while (count < rounds):
try:
yourPlay = int(input("(0)Rock,(1)Paper,(2)Scissors:"))
while (yourPlay < 0 or yourPlay > 2):
print ("Invalid selection!")
yourPlay = int(input("(0)Rock,(1)Paper,(2)Scissors:"))
except ValueError:
print ("Only numeric values are allowed!")
yourPlay = int(input("(0)Rock,(1)Paper,(2)Scissors:"))
else:
computer = random.randint(0,2) #randomizes the numbers 0 - 2
if (yourPlay == computer):
DrawMatch()
elif (yourPlay != computer):
WinsMatch()
LosesMatch()
count+=1
print ("End of Round ", count)
if (count == rounds):
print ("Wins:",wins)
print ("Loses:",loses)
print ("Draws:",draws)
#resultLog = {"Wins":wins,"Loses":loses,"Draws":draws}
fileName = input("Enter Your name: ")
#print (resultLog)
with open (fileName,"w") as plyrRec:
print ("Your file has been created!")
plyrRec.close()
with open (fileName, "a") as plyrRec:
plyrRec.write ("{}{}\n{}{}\n{}{}\n".format("Wins:",wins,"Loses:",loses,"Draws:",draws))
plyrRec.close()
rec+=1
print ("End of Record ", rec)
So the code works fairly well except that at the end of the first round it repeatedly asks the user to enter number of rounds to play. I hope someone can advise me please.
#Date first created: September 6, 2018 v.0
#Version: v.1, modified 2021/08/31
#This is a Rock, Paper, Scissors game.
#Rock beats scissors, scissors beats paper, and paper beats rock.
import random
#variable declaration and initialization
game_moves = ["Rock","Paper","Scissors"]
def is_input_numeric(str_val):
'''(string) -> bool
Returns whether a string input contains ONLY numeric values greater than zero
>>> is_input_numeric('4')
True
>>> is_input_numeric("like 7")
False
'''
return str_val.isnumeric() and int(str_val) > 0 and int(str_val) <= 20
def is_input_numeric_range(str_val):
'''(string) -> bool
Returns whether a string input contains ONLY a numeric value greater than zero but less than
or equal to two
>>> is_input_numeric_range('y')
False
>>> is_input_numeric_range('3')
False
>>> is_input_numeric_range('2')
True
'''
return str_val.isnumeric() and int(str_val) >= 0 and int(str_val) <= 2
def validate_rounds():
'''(string) -> string
checks str_val and passes control to is_input_numeric function, then returns a string value
>>> validate_rounds() -> is_input_numeric("time")
False
>>> validate_rounds() -> is_input_numeric('0')
False
>>> validate_rounds()-> is_input_numeric('10')
True
'''
valid_rounds = False
while not valid_rounds:
rounds = input("Enter number of rounds to play[min = 1, max = 20]: ")
valid_rounds = is_input_numeric(rounds)
return rounds
def validate_player_input():
'''(string) -> string
checks string and passes control to is_input_numeric_range function, then returns the string value
>>> validate_player_input() -> is_input_numeric_range('-1')
False
>>> validate_player_input() -> is_input_numeric_range('i')
False
>>> validate_player_input() -> is_input_numeric_range('3')
False
>>> validate_player_input() -> is_input_numeric_range('0')
True
'''
valid_player_control = False
while not valid_player_control:
player_move = input("ONLY (0)Rock,(1)Paper,(2)Scissors, allowed: ")
valid_player_control = is_input_numeric_range(player_move)
return player_move
def get_computer_play():
'''Returns a whole number in the range 0:2
'''
computer_move = random.randint(0,2)
return computer_move
def human_player_wins(plyr, comp):
wins = 0
rock_beats_scissors = False
paper_beats_rock = False
scissors_beats_paper = False
human_hand = plyr
computer_hand = comp
if human_hand == 0 and computer_hand == 2:
rock_beats_scissors = True
elif human_hand == 1 and computer_hand == 0:
paper_beats_rock = True
elif human_hand == 2 and computer_hand == 1:
scissors_beats_paper = True
if rock_beats_scissors or paper_beats_rock or scissors_beats_paper:
print(game_moves[human_hand] + " beats " + game_moves[computer_hand] + "!")
print("You Win!")
wins += 1
return wins
def human_player_lose(plyr, comp):
lose = 0
rock_beats_scissors = False
paper_beats_rock = False
scissors_beats_paper = False
human_hand = plyr
computer_hand = comp
if human_hand == 0 and computer_hand == 1:
paper_beats_rock = True
elif human_hand == 1 and computer_hand == 2:
scissors_beats_paper = True
elif human_hand == 2 and computer_hand == 0:
rock_beats_scissors = True
if rock_beats_scissors or paper_beats_rock or scissors_beats_paper:
print(game_moves[computer_hand] + " beats " + game_moves[human_hand] + "!")
print("You Lose!")
lose += 1
return lose
def players_draw():
draws = 0
print("It's a draw!")
draws += 1
return draws
def start_game():
rounds_played = 0
total_wins = 0
total_losses = 0
total_draws = 0
highest_score = 0
game_rounds = input("Enter number of rounds to play[Max = 20]: ")
rounds_valid = is_input_numeric(game_rounds)
if not rounds_valid:
game_rounds = validate_rounds()
while rounds_played < int(game_rounds):
player_hand = input("(0)Rock,(1)Paper,(2)Scissors: ")
valid_control = is_input_numeric_range(player_hand)
print('plyr:', player_hand)
if not valid_control:
player_hand = validate_player_input()
computer_hand = get_computer_play()
print('comp:', computer_hand)
if int(player_hand) == computer_hand:
total_draws += players_draw()
if int(player_hand) != computer_hand:
total_wins += human_player_wins(int(player_hand),computer_hand)
total_losses += human_player_lose(int(player_hand),computer_hand)
rounds_played += 1
if total_wins > highest_score:
highest_score = total_wins * 10
print('\n--------------------------GAME RESULTS--------------------------')
print('\nHigh Score = ', highest_score )
print('\nrounds played = ', rounds_played, '||','wins = ', total_wins,'||', 'losses = ', total_losses, '||','draws = ', total_draws )
print('\n--------------------------END OF RESULTS------------------------')
start_game()
Thanks to those who tried to helped me it was appreciated. This is the new version now after four years. Yikes!

Rock, Paper, Scissor, Spock, Lizard in python, Player 2 automatically wins

for an exercise we need to recreate the game played by the members of the bigbang theory: Rock, Paper, Scissor, Spock, Lizard. I managed to recreate it almost completely, the only problem is: Player 2 automatically wins. Can someone tell me where I need to change the code and also explain why?
import sys
t = len(sys.argv)
if(t < 2 or t > 3):
print("Usage: rpsls.py symbool1 symbool2")
exit()
i = 1
while (i > 0):
a = sys.argv[1]
b = sys.argv[2]
a = a.lower()
b = b.lower()
if(a != "rock" and a != "paper" and a != "scissor" and a != "lizard" and a != "spock"):
print("What's that? please use a real symbol!")
elif(b != "rock" and b != "paper" and b != "scissor" and b != "lizard" and b != "spock"):
print("What's that? please use a real symbol!")
else:
if (a == "paper" and b == "scissor"):
s = True
i = 0
else:
s = False
i = 0
if(a == "paper" and b == "rock"):
s = True
i = 0
else:
s = False
i = 0
if(a == "rock" and b == "lizard"):
s = True
i = 0
else:
s = False
i = 0
if(a == "lizard" and b == "spock"):
s = True
i = 0
else:
s = False
i = 0
if(a == "spock" and b == "scissors"):
s = True
i = 0
else:
s = False
i = 0
if(a == "scissor" and b == "lizard"):
s = True
i = 0
else:
s = False
i = 0
if(a == "lizard" and b == "paper"):
s = True
i = 0
else:
s = False
i = 0
if(a == "paper" and b == "spock"):
s = True
i = 0
else:
s = False
i = 0
if(a == "spock" and b == "rock"):
s = True
i = 0
else:
s = False
i = 0
if(a == "rock" and b == "scissor"):
s = True
i = 0
else:
s = False
i = 0
if(a == b):
print("It's a tie!")
i = 0
exit()
if(s == True):
print("Player 1 wins!")
if(s == False):
print("Player 2 wins!")
Each of your if statements has an else. Only one of the if statements can be true, so that means that all the other else statements are evaluated. The result of that is that the last else statement - which sets s to False - will "win", so player 2 wins.
You should drop all your else statements, and restructure your code as a series of if...elif... blocks:
if a == "paper" and b == "scissor":
s = True
i = 0
elif a == "paper" and b == "rock":
(Note, if conditions don't need parentheses.)

Simple Rock Paper Scissors game, problems with returning score?

I'm writing this Rock Paper Scissors program for my Programming class, and having some problems getting the full score to show up at the end of the program. I'm super beginner in Python, so nothing too fancy here. For some reason, as I run the program, the only score that shows up is 1 regardless of how many times the game loops. What am I doing wrong here?
from myro import *
from random import *
def announceGame():
""" Announces the game to the user """
speak("Welcome to Rock, Paper, Scissors. I look forward to playing you.")
def computerMove():
""" Determines a random choice for the computer """
randomNumber = random()
if randomNumber == 1:
compMove = "R"
elif randomNumber == 2:
compMove = "P"
else:
compMove = "S"
return compMove
def userMove():
""" Asks the user to input their choice."""
userChoice = raw_input("Please enter R, P, or S: ")
return userChoice
def playGame(userChoice, compMove):
""" Compares the user's choice to the computer's choice, and decides who wins."""
global userWin
global compWin
global tie
userWin = 0
compWin = 0
tie = 0
if (userChoice == "R" and compMove == "S"):
userWin = userWin + 1
print "You win."
elif (userChoice == "R" and compMove == "P"):
compWin = compWin + 1
print "I win."
elif (userChoice == "S" and compMove == "R"):
compWin = compWin + 1
print "I win."
elif (userChoice == "S" and compMove == "P"):
userWin = userWin + 1
print "You win"
elif (userChoice == "P" and compMove == "S"):
compWin = compWin + 1
print "I win"
elif (userChoice == "P" and compMove == "R"):
userWin = userWin + 1
print "You win"
else:
tie = tie + 1
print "It's a tie"
return compWin, userWin, tie
def printResults(compWin, userWin, tie):
""" Prints the results at the end of the game. """
print " Rock Paper Scissors Results "
print "------------------------------------"
print "Computer Wins: " + str(compWin)
print "User Wins: " + str(userWin)
print "Ties: " + str(tie)
def main():
announceGame()
for game in range(1,6):
u = userMove()
c = computerMove()
game = playGame(u,c)
printResults(compWin, userWin, tie)
main()
Inside playGame, you set userWin, compWin, and tie to zero. So every time you call that function, they get set to zero before the new values are added. You should initialize these variables outside the function that you are calling in the loop. (For instance, you could initialize them in announceGame.)

Categories

Resources