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 !
Related
so i don't understand why my counter doesn't reset when i'm restarting the game, also, i believe its got something to do with the fact that i have no builder?
any help will be highly appriciated!
import random
import sys
from termcolor import colored
class RPS():
def show_welcome():
print(colored("Welcome to RPS !!!", 'blue'))
print(colored("RULES:",'yellow'), colored("*", 'red'), "Rock Beats Scissors",colored("*", 'red'))
print(colored(" *", 'grey'),"Scissors beats Paper", colored("*", 'grey'))
print(colored(" *", 'magenta'), "Paper beats Rock", colored("*", 'magenta'))
print(colored("!---=== GOOD LUCK ===---! ", 'green'))
def round_number():
x = 10
user_input = ""
while True:
try:
user_input = int(input("# Number Of Rounds? [Max 10]: "))
except:
print("Invalid Input!")
RPS.round_number()
if user_input < 1 or user_input > x:
print("Max 10 rounds!")
rundnum = 0
RPS.round_number()
else:
return user_input
def restart():
user_input = ""
try:
user_input = input("Would you like to restart? [Y/n]")
except:
print("\nInvalid Input! ")
RPS.show_welcome()
if user_input is "y" or user_input is "Y":
rounds = 0
RPS.round_number()
elif user_input is "n" or user_input is "N":
print(colored("Thanks for playing! Goodbye!", 'green'))
sys.exit()
else:
print("Bullshit input!")
RPS.restart()
def game():
player = 0
rounds = 0
moves = ['Rock', 'Paper', 'Scissors',]
r = rundnum
while rounds < r:
rounds += 1
comp = random.choice(moves)
print(colored("Choose : ", 'green'), colored("1)Rock", 'red'), colored("2)Paper", 'yellow'),
colored("3)Scissors", 'grey'))
try:
player = int(input("What's Your Guess? "))
except:
print(colored("No Valid Input! Restarting Game...", 'red'))
RPS.game()
if (player is 1 and comp is 'Rock') or (player is 2 and comp is 'Paper') \
or (player is 3 and comp is 'Scissors'):
print("Player Choose: {}".format(moves[player - 1]))
print("Computer Choose: {}".format(comp))
print(colored("*** Round #: {} | Result: It's A Draw !! *** ", 'blue').format(rounds))
if rounds >= r:
print(colored("*** GAME OVER *** ", 'grey'))
rounds = 0
RPS.restart()
else:
continue
elif (player is 1 and comp is 'Paper') or (player is 2 and comp is 'Scissors') \
or (player is 3 and comp is 'Rock'):
print("Player Choose: {}".format(moves[player - 1]))
print("Computer Choose: {}".format(comp))
print(colored("*** Round #: {} | Result: Player Lose !! *** ", 'blue').format(rounds))
if rounds >= r:
print(colored("*** GAME OVER *** ", 'grey'))
rounds = 0
RPS.restart()
else:
continue
elif (player is 1 and comp is 'Scissors') or (player is 2 and comp is 'Rock') \
or (player is 3 and comp is 'Paper'):
print("Player Choose: {}".format(moves[player - 1]))
print("Computer Choose: {}".format(comp))
print(colored("*** Round #: {} | Result: Player Wins !! *** ", 'blue').format(rounds))
if rounds >= r:
print(colored("*** GAME OVER *** ", 'grey'))
rounds = 0
RPS.restart()
else:
continue
else:
print(colored("No valid input!", 'red'))
RPS.game()
if __name__ == '__main__':
#rounds = ""
while True:
RPS.show_welcome()
rundnum = RPS.round_number()
RPS.game()
rounds = 0
rundnum = 0
The problem occurs when you call RPS.game() within the function itself. This creates a situation whereby all the variables reset, as defined by the function .game(). To avoid this, you could give the function default parameters and then call the function (within itself) with those parameters.
Example (using part of the original code):
def game(player=0, rounds=0):
# player = 0
# rounds = 0
moves = ['Rock', 'Paper', 'Scissors',]
r = rundnum
while rounds < r:
rounds += 1
comp = random.choice(moves)
print(colored("Choose : ", 'green'), colored("1)Rock", 'red'), colored("2)Paper", 'yellow'),
colored("3)Scissors", 'grey'))
try:
player = int(input("What's Your Guess? "))
except:
print(colored("No Valid Input! Restarting Game...", 'red'))
RPS.game(player, rounds) # Here's the magic...
I wanted to make a simple Rock, Paper, Scissor game in Python. It goes well with the game, but the final scores are always being showed as a 0.
I wanted to show a smaller section of the code but, I don't know where the problem lies, so I am sorry for the length of the code.
I am still a novice learner, so please pardon me if the question is too silly or the code is not well formatted.
#Rock-Paper-Scissor Game
import random
print("Please enter your name:")
userName = input()
print("Welcome " + userName)
print("The following are the rules of the game:")
print("Press 'R' for Rock")
print("Press 'P' for Paper")
print("Press 'S' for Scissor")
print("This will be a 10 point match")
userTally = 0
compTally = 0
def gameProcess(userTally, compTally): #The process of the game. It increments or decrements the value depending on the result
print("Your turn:")
userInput = input()
computerChoice = random.choice(["R","P","S"])
if userInput == "R": #User Inputs R for Rock
if computerChoice == "R":
print("The computer chose Rock")
print("It's a Tie")
elif computerChoice == "P":
print("The computer chose Paper")
print("Computer Won")
compTally = compTally + 1
elif computerChoice == "S":
print("The computer chose Scissor")
print("You Won")
userTally = userTally + 1
elif userInput == "P": #User Inputs P for Paper
if computerChoice == "R":
print("The computer chose Rock")
print("You Won")
userTally = userTally + 1
elif computerChoice == "P":
print("The computer chose Paper")
print("It's a Tie")
elif computerChoice == "S":
print("The computer chose Scissor")
print("Computer Won")
compTally = compTally + 1
elif userInput == "S": #User Inputs S for Scissor
if computerChoice == "R":
print("The computer chose Rock")
print("Computer Won")
compTally = compTally + 1
elif computerChoice == "P":
print("The computer chose Paper")
print("You Won")
userTally = userTally + 1
elif computerChoice == "S":
print("The computer chose Scissor")
print("It's a Tie")
return(userTally,compTally)
def tryCount(): #The number of tries....
tryNum = 1
while tryNum < 11:
gameProcess(0, 0)
tryNum = tryNum + 1
tryCount()
print("You scored " + str(userTally))
print("The computer scored " + str(compTally))
if userTally > compTally:
print("CONGRATULATIONS, YOU WON.")
elif userTally < compTally:
print("Sorry, better luck next time.")
close = input()
if close == "Random Input.":
exit()
else:
exit()
You pass 0, 0 to gameProcess, which you treat as the scores within the function, and then return them modified, but you do not actually use the return value in the only place you call gameProcess (in tryCount), so the global userTally, compTally variables remain unchanged.
This is how you should change tryCount:
def tryCount(): #The number of tries....
global userTally, compTally
tryNum = 1
while tryNum < 11:
userTally,compTally=gameProcess(userTally,compTally)
tryNum = tryNum + 1
I found a basic rock-paper-scissors game and wanted to know how to create a score table for it. Also, I'm confused how to make the game last forever until the player wants to end it. Here is the coding for the game:
import random;
wins_history = [0]
ties_history = [0]
losses_history = [0]
def initial_wins():
return wins_history[0]
def cur_wins():
return wins_history[-1]
def affect_wins(delta):
wins_history.append(cur_wins() + delta)
return cur_wins()
def initial_ties():
return ties_history[0]
def cur_ties():
return ties_history[-1]
def affect_ties(delta):
ties_history.append(cur_ties() + delta)
return cur_ties()
def initial_losses():
return losses_history[0]
def cur_losses():
return losses_history[-1]
def affect_losses(delta):
losses_history.append(cur_losses() + delta)
return cur_losses()
while True:
player = input("Enter your choice (rock/paper/scissors): ");
player = player.lower();
while (player != "rock" and player != "paper" and player != "scissors"):
print(player);
player = input("That choice is not valid. Enter your choice (rock/paper/scissors): ");
player = player.lower();
computerInt = random.randint(0,2);
if (computerInt == 0):
computer = "rock";
elif (computerInt == 1):
computer = "paper";
elif (computerInt == 2):
computer = "scissors";
else:
computer = "Huh? Error...";
if (player == computer):
print("Draw!");
affect_ties(+1)
print ("Your new tie score is, cur_ties()")
elif (player == "rock"):
if (computer == "paper"):
print("Computer wins!");
affect_losses(+1)
print ("Your new loss score is, cur_losses()")
else:
print("You win!");
affect_wins(+1)
print ("Your new win score is, cur_wins()")
elif (player == "paper"):
if (computer == "rock"):
print("You win!");
affect_wins(+1)
print ("Your new win score is, cur_wins()")
else:
print("Computer wins!")
affect_losses(+1)
print ("Your new loss score is, cur_losses()")
elif (player == "scissors"):
if (computer == "rock"):
print("Computer wins!");
affect_losses(+1)
print ("Your new loss score is, cur_losses()")
else:
print("You win!");
affect_wins(+1)
print ("Your new win score is, cur_wins()")
import random
name = input("What is your name?")
print ("Welcome to Rock Paper Scissors", name, "!")
def computerThrow():
throwOptions = ["rock","paper","scissors"]
randomChoice = random.randint(0,2)
return throwOptions [randomChoice]
def playerThrow():
player = input("rock, paper, scissors?")
return player
def compareThrows(player, computer):
if player == computer:
return("tie")
elif player == "rock":
if computer == "scissors":
return("win")
else:
return("lose")
elif player == "scissors":
if computer == "paper":
return("win")
else:
return("lose")
elif player == "paper":
if computer == "rock":
return("win")
else:
return("lose")
else:
return("invalid")
def printMatchOutcome(result, player, computer):
if result == "win":
print(player, "beats", computer, " — You win!")
if result == "lose":
print (computer,"beats",player, "- You lose!")
if result == "tie":
print("tie match!")
if result == "invalid":
print ("invalid...try again")
def oneRound():
player = playerThrow()
print("You threw:",player)
computer = computerThrow()
print("Computer threw:",computer)
compare = compareThrows(player, computer)
printMatchOutcome(compare, player, computer)
#define counter variable
gamesPlayed = 0
playerWins = 0
computerWins = 0
userWantsToPlay = True
while userWantsToPlay:
oneRound()
response = input("Do you want to play again? (yes / no)")
if response == 'yes':
userWantsToPlay = True
else:
userWantsToPlay = False
print("Thanks for playing!")
def score(result):
oneRound()
if result == "win":
return playerWins + 1
elif result == "lose":
return computerWins + 1
I am trying to add a score counter to my game so that once userWantsToPlay = False it will display the number of games played, and the score for the computer and the player. I have started it as a function but I am not sure if that is even right? How would I go about this?
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am using Python. Currently new to it. I'm creating a rock paper scissors game with win counter. I've look up some solution online but it doesn't work for me.I'm close to completing it.But there's just an error to it.I can't get the tally counter working.It doesn't shows any win count at the end of the program
from random import randint
print ("Rock ,Paper,Scissors game.")
#Function to get computer input
def generate():
comlist = ["rock","paper","scissors"]
comans = comlist[randint(-1,2)]
if comans == "rock":
print ("Computer choose rock.")
elif comans == "paper" :
print ("Computer choose paper.")
elif comans == "scissors":
print ("Computer choose scissors.")
return comans
#Function to get user input
def user():
userchoice = input ("Choose rock, paper , or scissors.")
while userchoice != 'rock' and userchoice != 'paper' and userchoice != 'scissors':
print ("Invalid input. Please enter again")
userchoice = input ("Choose rock, paper , or scissors.")
if userchoice == "rock":
print ("You choose rock.")
choice = userchoice
elif userchoice == "paper" :
print ("You choose paper.")
choice = userchoice
else:
userchoice == "scissors"
print ("You choose scissors.")
choice = userchoice
return choice
#Function to determine winner
def result(comans ,choice):
global result_set
if choice == comans:
print ("Tie")
elif choice == "rock":
if computer == "paper":
print ("You lose")
else :
print("You win")
result_set ='win'
elif choice == "paper":
if computer == "scissors":
print("You lose")
else:
print("You win")
result_set ='win'
elif choice == "scissors":
if computer == "rock":
print("You lose")
else:
print("You win")
result_set ='win'
#Function to get win taly
def wincounter (result,guess,computer):
if result_set == 'win':
win += 1
else:
pass
print (win)
#Main program
counter = 0
win = 0
diffulty = input(' Please enter diffulty.( "1" for easy , "2" for medium, "3" for hard)')
while diffulty != '1' and diffulty != '2' and diffulty != '3':
print ('Invalid input')
diffulty = input(' Please enter diffulty.( "1" for easy , "2" for medium, "3" for hard)')
if diffulty == '1':
print ("You have choose easy")
counter = 1
guess = user()
computer = generate()
result (computer, guess)
while counter < 3:
guess = user()
computer = generate()
result (computer, guess)
counter +=1
if diffulty == '2':
print ("You have choose medium")
counter = 1
guess = user()
computer = generate()
result (computer, guess)
while counter < 5:
guess = user()
computer = generate()
result (computer, guess)
counter +=1
if diffulty == '3':
print ("You have choose hard")
counter = 1
guess = user()
computer = generate()
result (computer, guess)
while counter < 10:
guess = user()
computer = generate()
result (computer, guess)
counter +=1
Here is my code. It is slightly messy. Sorry for that since than I am still new in python. Thanks for the help.
After running.
Choose rock, paper , or scissors.rock
You choose rock.
Computer choose scissors.
You win
Choose rock, paper , or scissors.rock
You choose rock.
Computer choose rock.
Tie
Choose rock, paper , or scissors.rock
You choose rock.
Computer choose rock.
Tie
It is suppose to show the win results after the end of the last round.
I have fixed your code . . .
from random import randint
print ("Rock ,Paper,Scissors game.")
#Function to get computer input
def generate():
comlist = ["rock","paper","scissors"]
comans = comlist[randint(-1,2)]
if comans == "rock":
print ("Computer choose rock.")
elif comans == "paper" :
print ("Computer choose paper.")
elif comans == "scissors":
print ("Computer choose scissors.")
return comans
#Function to get user input
def user():
userchoice = input ("Choose rock, paper , or scissors.")
while userchoice != 'rock' and userchoice != 'paper' and userchoice != 'scissors':
print ("Invalid input. Please enter again")
userchoice = input ("Choose rock, paper , or scissors.")
if userchoice == "rock":
print ("You choose rock.")
choice = userchoice
elif userchoice == "paper" :
print ("You choose paper.")
choice = userchoice
else:
userchoice == "scissors"
print ("You choose scissors.")
choice = userchoice
return choice
#Function to determine winner
def result(comans ,choice):
result_set = ''
if choice == comans:
print ("Tie")
elif choice == "rock":
if computer == "paper":
print ("You lose")
else :
print("You win")
result_set ='win'
elif choice == "paper":
if computer == "scissors":
print("You lose")
else:
print("You win")
result_set ='win'
elif choice == "scissors":
if computer == "rock":
print("You lose")
else:
print("You win")
result_set ='win'
wincounter(result_set)
#Function to get win taly
def wincounter (result):
global win
if result == 'win':
win += 1
else:
pass
#print (win)
def print_win_count():
global win
print ('you have win '+ str(win) + ' times')
#Main program
counter = 0
win = 0
diffulty = input(' Please enter diffulty.( "1" for easy , "2" for medium, "3" for hard)')
while diffulty != '1' and diffulty != '2' and diffulty != '3':
print ('Invalid input')
diffulty = input(' Please enter diffulty.( "1" for easy , "2" for medium, "3" for hard)')
if diffulty == '1':
print ("You have choose easy")
counter = 1
guess = user()
computer = generate()
result (computer, guess)
while counter < 3:
guess = user()
computer = generate()
result (computer, guess)
counter +=1
print_win_count()
if diffulty == '2':
print ("You have choose medium")
counter = 1
guess = user()
computer = generate()
result (computer, guess)
while counter < 5:
guess = user()
computer = generate()
result (computer, guess)
counter +=1
print_win_count()
if diffulty == '3':
print ("You have choose hard")
counter = 1
guess = user()
computer = generate()
result (computer, guess)
while counter < 10:
guess = user()
computer = generate()
result (computer, guess)
counter +=1
print_win_count(0)