How to keep score for player and computer? - python

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!

Related

Always receive 'You Lose' message in RPS against computer

For my exercise, I have to get the computer to play against the user in RPS. However, after both the computer and I input our action, the user will always receive a 'You Lose'.
import random
def get_computer_move():
"""Deterministic 'random' move chooser"""
options = ['rock', 'paper', 'scissors']
return options[random.randint(0, 2)]
def game_result(move1, move2):
"""game_result *exactly* as defined in question one"""
options = ["rock", "paper", "scissors"]
if move1 == move2:
return 0
elif move1 == "paper" and move2 == "rock":
return 1
elif move1 == "rock" and move2 == "scissors":
return 1
elif move1 == "scissors" and move2 == "paper":
return 1
else:
return 2
def main():
"""Runs a single game of PSR"""
print("Let's Play Paper, Scissors, Rock!")
user1 = input("Player one move: ").lower()
computer1 = print("The computer plays " + get_computer_move())
game_result(computer1, user1)
if user1 == computer1:
return print("It's a draw")
elif user1 == "paper" and computer1 == "rock":
return print("You win")
elif user1 == "rock" and computer1 == "scissors":
return print("You win")
elif user1 == "scissors" and computer1 == "paper":
return print("You win")
else:
return print("You lose")
main()
Here is my code although it is quite messy.
What I want to happen is:
Let's Play Paper, Scissors, Rock!
Player one move: ROCK
The computer plays rock
It's a draw
But it will always come out as:
Let's Play Paper, Scissors, Rock!
Player one move: ROCK
The computer plays rock
You lose
Help would be appreciated.
print returns none, you want to save the computers move and then print that separately
computer1 = get_computer_move()
print("The computer plays", computer1)

Rock, Paper, Scissors Game Python Count Feature Not Counting full session using functions

The Python program generates rock, paper, scissors game. The game works; however, I am having trouble keeping up with the score. I use the count method to calculate the amount times the user wins, cpu wins, # of rocks/paper/scissors that have been used.
I looked at other similar questions similar to mine. I am stuck because I am using functions. I want to keep the function format for practice.
I tried setting the counter to equal to 0's as globals. That gave a lot of traceback errors.
I tried changing the while loop within the game() function, but that produced an infinite loop. I kept the while loop within the main() function.
What is the best way to approach this? I want to be able to keep scores and for the count to update until the user quits the program.
Thank you!
import sys
import random
def get_user_input():
print("\nWhat do you choose to play? (r, p, s) or q to QUIT ")
player = input().lower()
if player == 'r':
print("You chose: ROCK")
return player
elif player == 'p':
print("You chose: PAPER")
return player
elif player == "s":
print(" You chose: SCISSORS")
return player
elif player == "q":
sys.exit(0)
else:
sys.exit(0)
def game(player):
possible_actions = ["r", "p", "s"]
computer = random.choice(possible_actions)
print("\nYou chose: ", player, "computer chose: ", computer)
rounds = 0
user_wins = 0
computer_wins = 0
tie_count = 0
rocks = 0
papers = 0
scissors = 0
if player == "r" and computer == "r":
print("You & computer TIED!")
tie_count += 1
rounds += 1
rocks += 1
elif player == "p" and computer == "p":
print("You & computer TIED!")
tie_count += 1
rounds += 1
papers += 1
elif player == "s" and computer == "s":
print("You & computer TIED!")
tie_count += 1
rounds += 1
scissors += 1
elif player == "r": # rock
if computer == "p":
print("Paper BEATS rock! You LOST!")
computer_wins += 1
rounds += 1
rocks += 1
else:
print("Rock BEATS scissors! You WIN!")
user_wins += 1
rounds += 1
rocks += 1
elif player == "p":
if computer == "r":
print("Paper BEATS rock! You WIN!")
user_wins += 1
rounds += 1
papers += 1
else:
print("Scissors BEATS paper! You LOST!")
computer_wins += 1
rounds += 1
papers += 1
elif player == "s": # scissors
if computer == "r":
print("Rock BEATS scissors! You LOST!")
computer_wins += 1
rounds += 1
scissors += 1
else:
print("Scissors BEATS paper! You WIN!")
user_wins += 1
rounds += 1
scissors += 1
print("\nComputer Wins ", computer_wins)
print("User Wins ", user_wins)
print("# Draws: ", tie_count)
print("# Rocks Drawn: ", rocks)
print("# Paper Drawn: ", papers)
print("# Scissors Drawn: ", scissors)
def main():
while True:
player = get_user_input()
game(player)
main()
What you call game is only a round. So you have to put the while loop inside the game function.
import random
def get_user_input():
while True:
print("\nWhat do you choose to play? (r, p, s) or q to QUIT ")
player = input().lower()
if player == 'r':
print("You chose: ROCK")
elif player == 'p':
print("You chose: PAPER")
elif player == "s":
print(" You chose: SCISSORS")
elif player == "q":
pass
else:
continue
break
return player
def game():
rounds = 0
user_wins = 0
computer_wins = 0
tie_count = 0
rocks = 0
papers = 0
scissors = 0
while True:
player = get_user_input()
if player == "q":
break
possible_actions = ["r", "p", "s"]
computer = random.choice(possible_actions)
print("\nYou chose: ", player, "computer chose: ", computer)
if player == "r": # rock
if computer == "r":
print("You & computer TIED!")
tie_count += 1
elif computer == "p":
print("Paper BEATS rock! You LOST!")
computer_wins += 1
else:
print("Rock BEATS scissors! You WIN!")
user_wins += 1
rocks += 1
elif player == "p":
if computer == "p":
print("You & computer TIED!")
tie_count += 1
elif computer == "r":
print("Paper BEATS rock! You WIN!")
user_wins += 1
else:
print("Scissors BEATS paper! You LOST!")
computer_wins += 1
papers += 1
elif player == "s": # scissors
if computer == "s":
print("You & computer TIED!")
tie_count += 1
elif computer == "r":
print("Rock BEATS scissors! You LOST!")
computer_wins += 1
else:
print("Scissors BEATS paper! You WIN!")
user_wins += 1
scissors += 1
rounds += 1
print("\nComputer Wins ", computer_wins)
print("User Wins ", user_wins)
print("# Draws: ", tie_count)
print("# Rocks Drawn: ", rocks)
print("# Paper Drawn: ", papers)
print("# Scissors Drawn: ", scissors)
if __name__ == "__main__":
game()
In order to keep your current flow (where game only runs one round), you have to preserve the stats in-between rounds.
This can be done caching stats in a dictionary an returning as follows.
Code
import sys
import random
def get_user_input():
print("\nWhat do you choose to play? (r, p, s) or q to QUIT ")
player = input().lower()
if player == 'r':
print("You chose: ROCK")
return player
elif player == 'p':
print("You chose: PAPER")
return player
elif player == "s":
print(" You chose: SCISSORS")
return player
elif player == "q":
sys.exit(0)
else:
sys.exit(0)
def game(player, stats = None):
if stats is None:
# Initialize runtime stats
stats = {
'rounds' : 0,
'user_wins' : 0,
'computer_wins' : 0,
'tie_count' : 0,
'rocks' : 0,
'papers' : 0,
'scissors' : 0}
# Retrieve stat values
rounds = stats['rounds']
user_wins = stats['user_wins']
computer_wins = stats['computer_wins']
tie_count = stats['tie_count']
rocks = stats['rocks']
papers = stats['papers']
scissors = stats['scissors']
possible_actions = ["r", "p", "s"]
computer = random.choice(possible_actions)
print("\nYou chose: ", player, "computer chose: ", computer)
if player == "r" and computer == "r":
print("You & computer TIED!")
tie_count += 1
rounds += 1
rocks += 1
elif player == "p" and computer == "p":
print("You & computer TIED!")
tie_count += 1
rounds += 1
papers += 1
elif player == "s" and computer == "s":
print("You & computer TIED!")
tie_count += 1
rounds += 1
scissors += 1
elif player == "r": # rock
if computer == "p":
print("Paper BEATS rock! You LOST!")
computer_wins += 1
rounds += 1
rocks += 1
else:
print("Rock BEATS scissors! You WIN!")
user_wins += 1
rounds += 1
rocks += 1
elif player == "p":
if computer == "r":
print("Paper BEATS rock! You WIN!")
user_wins += 1
rounds += 1
papers += 1
else:
print("Scissors BEATS paper! You LOST!")
computer_wins += 1
rounds += 1
papers += 1
elif player == "s": # scissors
if computer == "r":
print("Rock BEATS scissors! You LOST!")
computer_wins += 1
rounds += 1
scissors += 1
else:
print("Scissors BEATS paper! You WIN!")
user_wins += 1
rounds += 1
scissors += 1
print("\nComputer Wins ", computer_wins)
print("User Wins ", user_wins)
print("# Draws: ", tie_count)
print("# Rocks Drawn: ", rocks)
print("# Paper Drawn: ", papers)
print("# Scissors Drawn: ", scissors)
# Cache stat values
stats['rounds'] = rounds
stats['user_wins'] = user_wins
stats['computer_wins'] = computer_wins
stats['tie_count'] = tie_count
stats['rocks'] = rocks
stats['papers'] = papers
stats['scissors'] = scissors
return stats
def main():
stats = None
while True:
player = get_user_input()
stats = game(player, stats)
main()
You have set the values to 0 within the function so every time the function will be called, the rounds will be set to 0. Try initializing the variable outside the function. That should fix it.

my rock paper scissors gives me nothing in output (python)

I am new to python and as a practice I'm trying to write a rock paper scissors with it.
I triple checked eth but i can't find the problem.
I'm using visual studio code console. the msvcrt is for "getch" and I'm not sure about about the random function syntax
problem: when you give it the input number, It doesn't do or write anything despite the program.
help me pleaaaaase.
import random
import msvcrt
##################################################
player_move = " "
system_move = " "
##################################################
def rand(system_move):
rn = random.randint(1, 3)
if rn == 1:
system_move = "Rock"
elif rn == 2:
system_move = "Paper"
elif rn == 3:
system_move = "Scissors"
else:
rand()
return system_move
##################################################
print("!!! Rock, Paper, Scissors !!!\n\n\n")
###################################################
def playermove(player_move):
print("What do you want to go with?\n1-Rock\n2-paper\n3-scissors\n")
temp = msvcrt.getch()
if temp == '1' or 1:
player_move = 'Rock'
elif temp == '2' or 2:
player_move = 'Paper'
elif temp == '3' or 3:
player_move = 'Scissors'
else:
print(f"invalid input {player_move}. Try again\n")
playermove()
return player_move
###################################################
pm = ' '
sm = ' '
rand(sm)
playermove(pm)
if pm== 'Scissors':
if sm == "Scissors":
print(f"System move: {sm}\nIt's a tie!\n")
elif sm == "Rock":
print(f"System move: {sm}\nSystem won!\n")
elif sm == "Paper":
print(f"System move: {sm}\nYou won!\n")
else:
print("Oops! Something went wrong.\n")
elif pm == "Paper":
if sm == "Scissors":
print(f"System move: {sm}\nSystem won!\n")
elif sm == "Rock":
print(f"System move: {sm}\nYou won!\n")
elif sm == "Paper":
print(f"System move: {sm}\nIt's a tie!\n")
else:
print("Oops! Something went wrong.\n")
elif pm == "Rock":
if sm == "Scissors":
print(f"System move: {sm}\nYou won!\n")
elif sm == "Rock":
print(f"System move: {sm}\nIt's a tie!\n")
elif sm == "Paper":
print(f"System move: {sm}\nSystem won!\n")
else:
print("Oops! Something went wrong.\n")
print("Press any key to exit...")
xyz = msvcrt.getch()
Well, the reason your code doesn't work is because you are not assigning the return value of your functions to any variable. To fix your code you need to do the following:
sm = rand(sm)
pm = playermove(pm)
In Python, passing an immutable object like string means that you cannot make any changes to it. As you're not using the passed value, your function's signature should actually look like this.
def rand()
def playermove()
After you do this, you'll see there are other things you need to fix in your code.
Try this code. Just replace snake, water, gun by rock, paper, scissors.
print(" \t\t\t Welecome to Snake , Water , Gun game\n\n")
import random
attempts= 1
your_point=0
computer_point=0
while (attempts<=10):
lst=["snake","water","gun"]
ran=random.choice(lst)
print("what do you choose snake, water or gun")
inp=input()
if inp==ran:
print("tie")
print(f"you choosed {inp} and computer guess is {ran}")
print("No body gets point\n")
elif inp=="snake" and ran=="water":
your_point=your_point+1
print(f"you choosed {inp} and computer guess is {ran}")
print("The snake drank water\n")
print("You won this round")
print("you get 1 point\n")
elif inp=="water" and ran=="snake":
computer_point = computer_point + 1
print(f"you choosed {inp} and computer guess is {ran}")
print("The snake drank water\n")
print("You Lost this round")
print("computer gets 1 point\n")
elif inp=="water" and ran=="gun":
print(f"you choosed {inp} and computer guess is {ran}")
your_point = your_point + 1
print("The gun sank in water\n")
print("You won this round")
print("you get 1 point\n")
elif inp == "gun" and ran == "water":
print(f"you choosed {inp} and computer guess is {ran}")
computer_point = computer_point + 1
print("The gun sank in water\n")
print("You Lost this round")
print("computer gets 1 point\n")
elif inp == "gun" and ran == "snake":
print(f"you choosed {inp} and computer guess is {ran}")
your_point = your_point + 1
print("The snake was shoot and he died\n")
print("You Won this round")
print("you get 1 point\n")
elif inp == "snake" and ran == "gun":
print(f"you choosed {inp} and computer guess is {ran}")
computer_point=computer_point+1
print("The snake was shoot and he died\n")
print("You Lost this round")
print("computer gets 1 point\n")
else:
print("invalid")
print(10 - attempts, "no. of guesses left")
attempts = attempts + 1
if attempts>10:
print("game over")
if computer_point > your_point:
print("Computer wins and you loose")
if computer_point < your_point:
print("you win and computer loose")
print(f"your point is {your_point} and computer point is {computer_point}")

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

How to execute multiple while loops?

I was wondering if someone could tell me how to have the computer choose a new choice after every round. I got the lower portion of the code to cover all choices but it turns out my code runs where the computer uses the same choice every time. Is there a way to set my code so the computer chooses something new from the list. Thanks!
import random
def computerChoice():
gameList = ["Rock", "Paper", "Scissors"]
computerChoice = random.choice(gameList)
print(computerChoice)
def userChoice(computerChoice):
userScore = 0
computerScore = 0
rounds = 0
print("Welcome to Rock, Paper, Scissors. You are playing against the computer on best out of three game, winner takes all! Have Fun!")
while userScore < 2 and computerScore < 2:
userAnswer = input("Please choose Rock, Paper, or Scissors: ")
if userAnswer == "Rock" and computerChoice != "Paper":
userScore += 1
rounds += 1
print("The Computer Loses and You Win the Round!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Paper" and computerChoice != "Scissors":
userScore += 1
rounds += 1
print("The Computer Loses and You Win the Round!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Scissors" and computerChoice != "Rock":
userScore += 1
rounds += 1
print("The Computer Loses and You Win the Round!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Rock" and computerChoice == "Paper":
computerScore += 1
rounds += 1
print("The Computer Wins and You Lose the Round!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Paper" and computerChoice == "Scissors":
computerScore += 1
rounds += 1
print("The Computer Wins and You Lose the Round!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Scissors" and computerChoice == "Rock":
computerScore += 1
rounds += 1
print("The Computer Wins and You Lose the Round!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Rock" and computerChoice == "Rock":
print("This round is a PUSH!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Scissors" and computerChoice == "Scissors":
print("This round is a PUSH!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Paper" and computerChoice == "Paper":
print("This round is a PUSH!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
else:
print("Whatever you just inputed doesn't work noodlehead, try again!")
continue
x = computerChoice()
print(userChoice(x))
Move this inside your while loop:
computerChoice = random.choice(gameList)
Currently you are saving a single choice, and then using it every time. Where as this would create a new choice each time:
while userScore < 2 and computerScore < 2:
userAnswer = input("Please choose Rock, Paper, or Scissors: ")
computerChoice = random.choice(gameList)
# Compare to see who won.
Note that gameList must be available inside that scope, so you will have to either pass it in as a function parameter or include it inside the function. That does change the nature of the function somewhat:
def game():
print("Welcome to Rock, Paper, Scissors. You are playing against the computer on best out of three game, winner takes all! Have Fun!")
userScore, computerScore, rounds = game_loop()
def game_loop(available_options: list=["Rock", "Paper", "Scissors"]):
computerScore = 0
userScore = 0
rounds = 0
while userScore < 2 and computerScore < 2:
userAnswer = input("Please choose Rock, Paper, or Scissors: ")
computerChoice = random.choice(available_options)
// compare and score (preferably in their own functions)
return userScore, computerScore, rounds
try this
import random
def computerChoice():
gameList = ["Rock", "Paper", "Scissors"]
return random.choice(gameList)
def userChoice(computerChoice):
userScore = 0
computerScore = 0
rounds = 0
print("Welcome to Rock, Paper, Scissors. You are playing against the computer on best out of three game, winner takes all! Have Fun!")
while userScore < 2 and computerScore < 2:
userAnswer = input("Please choose Rock, Paper, or Scissors: ")
#all your if statements and stuff
computerChoice = computerChoice()
print(userChoice(computerChoice()))

Categories