Rock Paper Scissors with winner or loser result - python

I just started to learn Python and tried to make this game by myself for self-training.
I have made the game taking 2 more hours.
But I'd like to make score result(either 3 win or 3 lose) with break.
I don't know how to use while statement with break on this situation.
Hope to help me please.
import random
user_choice = input("select one of rock, paper, scissors. ")
Rock_paper_scissors = ['rock', 'paper', 'scissors']
computer_choice = Rock_paper_scissors[random.randint(0,2)]
if user_choice == computer_choice:
print("Draw.")
elif user_choice == "rock":
if computer_choice == "paper":
computer_score += 1
print("lose.")
else:
user_score += 1
print("win.")
elif user_choice == "scissors":
if computer_choice == "rock":
computer_score += 1
print("lose.")
else:
user_score += 1
print("win.")
elif user_choice == "paper":
if computer_choice == "scissors":
computer_score += 1
print("lose")
else:
user_score += 1
print("win")

Well first youll want to add those score variables at the begging of your code.
computer_score=0
user_score=0
then you want to have a while statement that also encloses the user input
Rock_paper_scissors = ['rock', 'paper', 'scissors']
while True:
user_choice = input("select one of "rock, paper, scissors. ")
computer_choice = Rock_paper_scissors[random.randint(0,2)]
#Your if/elif statements go here
And at the end and an if statement to check if someone has a score of 3 or more
if user_score >= 3:
print('You win')
break

You can loop your procedure for 3 times, stop when one of 2 opponent reach score of 2.
It will look something like this
while (user_score < 3 and computer_score < 3):
<continue playing>
If you want to use break:
while True:
<continue playing>
if user_score == 3 or computer score == 3:
break
Hope this help

The while loop in python works like this:
while condition:
do something...
While the condition is true the loop will keep going, in this case you don't need a break statement, you could simply do:
user_score = 0
computer_score = 0
while (user_score < 3 and computer_score < 3):
game...
If you really want to use a break statement, you could do it like this:
user_score = 0
computer_score = 0
while True:
if (user_score >= 3 or computer_score >= 3):
break
game...
That way the loop will keep going forever, since the condition is True, but the if inside the loop will call a break when a player scores 3 points.
user_score and computer_score are initialized to zero, you always have to initialize your variables.

Related

How to keep score for player and computer?

This is a rock,paper,scissors game.
import random
options = ("rock", "paper", "scissors") # three options
running = True
score = 0
while running: # continuing the game
player = "" # storing the player's choices
computer = random.choice(options) # computer will choose a random choice from the options
while player not in options: # the player has to choose one of the options, if not, it will still keep on looping
player = input("Enter a choice (rock, paper, scissors): ")
print("Player: " + player) # player(user) vs. computer
print("Computer: " + computer)
if player == computer:
score = 0
print("It's a tie!")
elif player == "rock" and computer == "scissors":
score += 1
print("You win!")
elif player == "paper" and computer == "rock":
score += 1
print("You win!")
elif player == "scissors" and computer == "paper":
score += 1
print("You win!")
else:
score += 1
print("You lose!")
print(score, "for computer")
print(score)
play_again = input("Play again? (y/n): ").lower()
if play_again == "y":
running = True
print("Yes sir!")
else:
running = False
print("Thanks for playing! ")
My goal was trying to keep score for player and computer. If the user wins, they get a point. If the computer wins, they get a point. If its a tie, neither of them gets a point.
The following code shows you three rounds of three games of a simulated user input game with its result. It is your code only slightly changed to count properly the results:
import random
lst_user_input = [
"list faking user input:"
,"scissors"
,"paper"
,"rock"
,"y"
,"scissors"
,"paper"
,"rock"
,"y"
,"scissors"
,"paper"
,"rock"
,"n"
]
options = ("rock", "paper", "scissors") # three options
running = True
computer_score = 0
player_score = 0
round_no = 0
while running: # continuing the game
#player = "" # storing the player's choices
round_no += 1
computer = random.choice(options) # computer will choose a random choice from the options
#while player not in options: # the player has to choose one of the options, if not, it will still keep on looping
# player = input("Enter a choice (rock, paper, scissors): ")
print(round_no)
player = lst_user_input[round_no]
print("Player : " + player) # player(user) vs. computer
print("Computer: " + computer)
if player == computer:
print("It's a tie!")
elif player == "rock" and computer == "scissors":
player_score += 1
print("You win!")
elif player == "paper" and computer == "rock":
player_score += 1
print("You win!")
elif player == "scissors" and computer == "paper":
player_score += 1
print("You win!")
else:
computer_score += 1
print("You lose!")
print("Player score:", player_score)
print("Computer score:", computer_score)
if not round_no % 3: # ask only each 3 rounds
#play_again = input("Play next 3-rounds? (y/n): ").lower()
round_no +=1
play_again = lst_user_input[round_no]
if play_again == "y":
running = True
print("Yes sir!")
else:
running = False
print("Thanks for playing! ")
Here an example of printed output:
1
Player : scissors
Computer: paper
You win!
Player score: 1
Computer score: 0
2
Player : paper
Computer: scissors
You lose!
Player score: 1
Computer score: 1
3
Player : rock
Computer: paper
You lose!
Player score: 1
Computer score: 2
Yes sir!
5
Player : scissors
Computer: paper
You win!
Player score: 2
Computer score: 2
6
Player : paper
Computer: rock
You win!
Player score: 3
Computer score: 2
Thanks for playing!

My input sometimes takes multiple times for it to go in the if statements

I am attempting to make a basic rock, paper, scissors game. When I input either rock, paper, or scissors, I sometimes have to enter the same thing multiple times for it to continue to the if statements. See code below:
# Rock, Paper, Scissors
player_total = 0
computer_total = 0
def get_computer_hand():
choice = randint(1, 3)
if choice == 1:
return "scissors"
elif choice == 2:
return "paper"
else:
return "rock"
def ask_user():
global player_total
global computer_total
player = input("Enter your hand (stop to stop): ")
if player == "stop":
print("Computer had ", computer_total, "points, you had ", player_total, " points.")
exit(0)
computer = get_computer_hand()
if player == "rock":
if computer == "paper":
return "win"
elif computer == "scissors":
return "lose"
else:
return "tie"
elif player == "paper":
if computer == "paper":
return "tie"
elif computer == "scissors":
return "lose"
else:
return "win"
elif player == "scissors":
if computer == "scissors":
return "tie"
elif computer == "paper":
return "win"
else:
return "lose"
def count_winner():
global player_total
global computer_total
player_total = 0
computer_total = 0
while True:
outcome = ask_user()
if outcome == "win":
print("You won that one.")
player_total += 1
elif outcome == "lose":
print("Computer won that one.")
computer_total += 1
count_winner()
I expect it to work the first time and to continue as usual, but I can't seem to figure out why it just asks "Enter your hand (stop to stop): " instead sometimes when I enter either rock, paper, or scissors.
This is happening because there is a tie happening between the computer and the user. This could be fixed by adding the end with the code of
else outcome == "tie":
print("You have tied with the Computer!")
computer_total += 1
player_total += 1
This would add a point to both sides and if you don't want that just delete the last two lines of my code

I am having trouble building a Rock Paper Scissors Game (Best out of 3 version) [closed]

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 3 years ago.
Improve this question
I am new to Python and am currently up-skilling myself. I am trying to build a best out of 3 version of Rock Paper Scissors - here is my attempt.
Why is this not working?
I am trying to create 2 new variables players_win and computer_wins to count the number of wins and then use that to define whether I've won a best out of 3 game, not sure if the way in which I've used "or" in the while loop is correct either - I don't think the variable increases are being picked up.
Rock Scissors Paper game (Best out of 2 version)
from random import randint
t = ["Rock", "Paper", "Scissor"]
print("Hi, what is your name?")
player_wins = 0
computer_wins = 0
games_played = 0
myName = input()
print(f"Hi {myName}, Lets play a game of Rock, Paper, Scissors - actually make that a best out of 3! Lets do this")
computer = t[randint(0,2)]
player = False
while (computer_wins < 3 or player_wins < 3):
player_wins = 0
computer_wins = 0
games_played = 0
player = input()
games_played = games_played + 1
if player == computer:
print("thats a tie! again!")
elif player == "Rock":
if computer == "Paper":
print("You lose!", computer, "covers", f"{myName}")
computer_wins = computer_wins + 1
else:
print("You win!", f"{myName}", "smashes", computer)
player_wins = player_wins + 1
elif player == "Paper":
if computer == "Scissor":
print("You lose", computer, "slices", f"{myName}")
computer_wins = computer_wins + 1
else:
print("You win", f"{myName}", "cover", computer)
player_wins = player_wins + 1
elif player == "Scissor":
if computer == "Rock":
print("You lose!", computer, "smashes", f"{myName}")
computer_wins = computer_wins + 1
else:
print("You win!", f"{myName}", "slices", computer)
player_wins = player_wins + 1
else:
print(f"Thats not a valid play {myName}! Check your spelling!")
print(games_played)
player = False
computer = t[randint(0,2)]
print(player_wins)
print(computer_wins)
print(games_played)
if player_wins == 2:
print(f"Well done {myName}, you won!")
else:
print(f"Unlucky {myName}, you lost!")
You can't end the while loop because you set player_wins and computer_wins to 0 after every round. Also you set games_played to 0 though that isn't a confition to the loop:
To fix this you need to change this:
while (computer_wins < 3 or player_wins < 3):
player_wins = 0
computer_wins = 0
games_played = 0
…
to
player_wins = 0
computer_wins = 0
games_played = 0
while (computer_wins < 3 or player_wins < 3):
…
PS:
Good luck with learning python. To write a little less you could use var += 1 instead of var = var + 1. See Python References for more info.
At first: In the while loop use and instead of or.
Next, don't set the
player_wins = 0
computer_wins = 0
games_played = 0
variables inside the while loop.
If you set them to 0 inside the loop, after each "round" you will start a new game.
The shorten for of increasing the variable value looks like this:
player_wins += 1
It's the same as player_wins = player_wins +1

How to add rounds option to rock paper scissors game? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'd like some assistance on my rock paper scissors game code. I'd like to add a function where the player can choose a specific number of rounds, instead of having a preset number of rounds. I am quite stuck on how to do this and I've just started to pick up Python again, so i am a bit rusty. Thank you so much ! (Please ignore spelling ;D)
CODE:
import random #imports a random moduel for the computer.
game = ["ROCK", "PAPER", "SCISSORS"] #sets the game answers.
count = 0 #game count is set to zero.
score = 0 #player score is set to zero.
computerscore =0 #computers score is set to zero.
print ("Welcome")
while count == 0: #starts game if count is zero.
for i in range (3): #repeats the turns 3 times.
answer = input ("Pick rock, paper or scissors.") #users answer.
print (answer.upper()) # prints the users answer
computer= random.choice(game) #computer picks randomly
print ("Computer picks",computer) #prints the computers choice.
if answer.upper() == "ROCK" and computer == "ROCK": #This whole set of code sets the game that what beats what.
print ("Its a tie!") # prints after each response that who won.
count +=1 #the count variable is increased.
elif answer.upper() == "PAPER" and computer == "PAPER":
print ("Its a tie!")
count +=1
elif answer.upper() == "SCISSORS" and computer == "SCISSORS":
print ("Its a tie!")
count +=1
elif answer.upper() == "PAPER" and computer == "ROCK":
print ("You win!")
count +=1
score +=1 #user score is added.
elif answer.upper() == "PAPER" and computer == "SCISSORS":
print ("You lose!")
count +=1
computerscore +=1 #computers score is added.
elif answer.upper() == "ROCK" and computer == "PAPER":
print ("You lose!")
count +=1
computerscore +=1
elif answer.upper() == "ROCK" and computer == "SCISSORS":
print ("You win!")
count +=1
score +=1
elif answer.upper() == "SCISSORS" and computer == "ROCK":
print ("lose!")
count +=1
computerscore +=1
elif answer.upper() == "SCISSORS" and computer == "PAPER":
print ("You win!")
count +=1
score +=1
if score < computerscore: #prints out at the end who scored how much and who won.
print ("Your score is", score)
print ("Computers socre is",computerscore)
print ("Computer wins!.")
if score > computerscore:
print ("Your score is", score)
print ("Computers socre is",computerscore)
print ("You win!.")
if score == computerscore:
print ("Your score is", score)
print ("Computers socre is",computerscore)
print ("Its a tie!!.")
Change the while count == 0:
to while count < x:
where x is the number of games you want to play
also i suggest to split your code into more functions, it will be much cleaner
Create a rounds variable to store the user input:
rounds = 3
Add this just before the while-loop:
user_input = input('How many rounds do you want to play?')
try:
rounds = int(user_input)
except ValueError:
print('Not a number')
And change your loop's condition to for i in range(rounds):

rock paper scissors lizard spock, Python

I am creating a rock paper scissors lizard spock game in Python for my class and i am trying to figure out why whatever choice I make I am always winning even though I set up all my if statements correct. `
import random
def instructions():
play = input("Would you like to play Rock, Paper, Scissors, Lizard, Spock(y/n): ").lower()
if play == "y":
print("1.Rock")
print("2.Paper")
print("3.Scissors")
print("4.Lizard")
print("5.Spock")
elif play != "n":
print("error has accured please type y for yes or n for no:")
instructions()
def getPlayerChoice():
choice = int(input("What is your choice user?: "))
if choice > 5:
print("Invalid number please try again....")
getPlayerChoice()
elif choice < 1:
print("Invalid number please try again....")
getPlayerChoice()
elif choice == 1:
print("You picked Rock")
elif choice == 2:
print("You picked Paper")
elif choice == 3:
print("You picked Scissors")
elif choice == 4:
print("You picked Lizard")
elif choice == 5:
print("You picked Spock")
return choice
def getCPUChoice():
choice = random.randint(1,5)
if choice == 1:
print("CPU picked Rock")
elif choice == 2:
print("CPU picked Paper")
elif choice == 3:
print("CPU picked Scissors")
elif choice == 4:
print("CPU picked Lizard")
elif choice == 5:
print("CPU picked Spock")
return choice
def winner(playerChoice, CPUChoice, playerWins, CPUWins, ties):
if playerChoice == 1 and CPUChoice == 3 or CPUChoice == 4:
print("Player wins.")
playerWins = playerWins.append(1)
elif playerChoice == 2 and CPUChoice == 1 or CPUChoice == 5:
print("Player wins.")
playerWins = playerWins.append(1)
elif playerChoice == 3 and CPUChoice == 2 or CPUChoice == 4:
print("Player wins.")
playerWins = playerWins.append(1)
elif playerChoice == 4 and CPUChoice == 2 or CPUChoice == 5:
print("Player wins.")
playerWins = playerWins.append(1)
elif playerChoice == 5 and CPUChoice == 1 or CPUChoice == 3:
print("Player wins.")
playerWins = playerWins.append(1)
elif playerChoice == CPUChoice:
print("Tie")
ties = ties.append(1)
else:
print("CPU won")
CPUWins = CPUWins.append(1)
return
def gameTotal(playerWins, CPUWins, ties):
playerWins = sum(playerWins)
CPUWins = sum(CPUWins)
ties = sum(ties)
print("Player final score: ", playerWins)
print("CPU final Score: ", CPUWins)
print("Total ties: ",ties)
def main():
playerChoice = 0
playerWins = []
CPUChoice = 0
CPUWins = []
ties = []
finalPlayerWins = 0
finalCPUWins = 0
finalTies = 0
Continue = 'y'
instructions()
while Continue == 'y':
playerChoice = getPlayerChoice()
CPUChoice = getCPUChoice()
winner(playerChoice,CPUChoice,playerWins, CPUWins, ties)
Continue = input("Would you like to play again (y/n):").lower()
if Continue == 'n':
print("Printing final scores.")
break
gameTotal(playerWins, CPUWins, ties)
main()
`
To summarize all of the things you should pay attention to:
boolean conditions - the result changes with the parentheses that are inside the condition.
if True or (True and False) --> this basically calculates the True and False part first (like in regular math) and then you have True or False which evaluates to True.
if True or True and False --> this basically calculates the True or True part first (like in regular math) and then you have True and False which evaluates to False - because you don't use parentheses.
Do not call a function within the same function - this is called recursion, and it's not relevant for what you need. Use a while loop, that runs as long as i.e. - you didn't get a proper choice input (while choice!='n' and choice!='y':).
Your instructions choice - the choice made by the user doesn't really change the flow of the game. the game starts also if the user entered no. You should add an exit statement in the instructions function.
The reason is you are missing parentheses on all of the "if" conditions.
if False and True or True # =True
if False and (True or False) # =False

Categories