I'm currently testing my skill by making a "rock paper scissors" game. I ran into a problem.
Some of the code: (I know it's kind of a lot for a problem, but look towards the end where most serval similar statements are and where # Win and # Lose also appear.)
import random
computerScore = 0
Score = 0
print("> Type \"help\" for help. <")
print("---")
print("Loading Rock Paper Scissors...")
while True:
guesses = [
"rock", "paper", "scissors"
]
guessesShortcuts = [
"r", "p", "s"
]
cmd = input("> ")
cmd = cmd.lower()
if cmd == "help":
print("Help - Opens this menu.\nQuit - Quits and stops the game.\nRPS - Starts a classic game of Rock Paper Scissors.")
if cmd == "rps" or cmd == "rock paper scissors":
Guess = str(input(f"Choose your weapon. {guesses[0].capitalize()}, {guesses[1].capitalize()}, or {guesses[2].capitalize()}? "))
Guess = Guess.lower()
computerGuess = random.choice(guesses)
if Guess == guesses[0] or Guess == guesses[1] or Guess == guesses[2]:
if Guess == computerGuess:
print("It's a tie!")
print(f"{Score} / {computerScore}")
# Win
if Guess == guesses[0] or Guess == guessesShortcuts[0] and computerGuess == guesses[2]:
print(f"{computerGuess.capitalize()}.")
print("You win!")
Score += 1
print(f"{Score} / {computerScore}")
if Guess == guesses[1] or Guess == guessesShortcuts[1] and computerGuess == guesses[0]:
print(f"{computerGuess.capitalize()}.")
print("You win!")
Score += 1
print(f"{Score} / {computerScore}")
if Guess == guesses[2] or Guess == guessesShortcuts[2] and computerGuess == guesses[1]:
print(f"{computerGuess.capitalize()}.")
print("You win!")
Score += 1
print(f"{Score} / {computerScore}")
# Lose
if Guess == guesses[2] or Guess == guessesShortcuts[2] and computerGuess == guesses[0]:
print(f"{computerGuess.capitalize()}.")
print("You win!")
Score += 1
print(f"{Score} / {computerScore}")
if Guess == guesses[0] or Guess == guessesShortcuts[0] and computerGuess == guesses[1]:
print(f"{computerGuess.capitalize()}.")
print("You win!")
Score += 1
print(f"{Score} / {computerScore}")
if Guess == guesses[1] or Guess == guessesShortcuts[1] and computerGuess == guesses[2]:
print(f"{computerGuess.capitalize()}.")
print("You win!")
Score += 1
print(f"{Score} / {computerScore}")
else:
print("Invalid response.")
In python, all if statements that are true will execute without regard to the previous if statements. What you want to do is have your first statement as an if statement, then the rest are elif statements.
Example:
if (condition):
(code)
elif (condition):
(code)
elif (condition):
(code)
...
or has a lower precedence than and. When you say condition1 or condition2 and condition3, that's treated as condition1 or (condition2 and condition3), and it's true if condition1 is true, even if the other conditions are false.
When you say
if Guess == guesses[0] or Guess == guessesShortcuts[0] and computerGuess == guesses[2]:
that's true if Guess == guesses[0], regardless of what computerGuess is.
Also, you don't have any handling for ties if the user enters a 1-letter input, and guess is a misleading name for these choices.
Welcome to Python and SO, your problem is already explained by above answers, just use if-elif-else and double-check your condition
I suggest you should merge 2 list into a dict. It will make you see it more clear:
rps = {"rock": ['rock', 'r'],
"paper": ['paper', 'p'],
"scissor": ['scissor', 's']}
About if statements, you should consider splitting condition into some sub if-elif-else statements, it makes your code clearer:
Guess = str(input(f"Choose your weapon: {list(rps.keys())}? "))
Guess = Guess.lower()
computerGuess = random.choice(list(rps.keys()))
# Rock
if Guess in rps['rock']:
print(f"Computer: {computerGuess}")
if computerScore is 'rock':
print("It's a tie!")
elif computerGuess is 'paper':
print("You lose!")
computerScore += 1
else:
print("You win!")
Score += 1
print(f"{Score} / {computerScore}")
# Paper
elif Guess in rps['paper']:
print(f"Computer: {computerGuess}")
if computerScore is 'paper':
print("It's a tie!")
elif computerGuess is 'scissor':
print("You lose!")
computerScore += 1
else:
print("You win!")
Score += 1
print(f"{Score} / {computerScore}")
# Scissor
elif Guess in rps['scissor']:
print(f"Computer: {computerGuess}")
if computerScore is 'scissor':
print("It's a tie!")
elif computerGuess is 'rock':
print("You lose!")
computerScore += 1
else:
print("You win!")
Score += 1
print(f"{Score} / {computerScore}")
else:
print("Invalid response.")
As #panwen suggested, you can reduce the if statement clutter by using a dict as a lookup table. Consider using the following to make it easier to find an outcome.
solutions = {
'rock': {'rock': 'tie', 'paper': 'loss', 'scissors': 'win'},
'paper': {'rock': 'win', 'paper': 'tie', 'scissors': 'loss'},
'scissors': {'rock': 'loss', 'paper': 'win', 'scissors': 'tie'},
}
For example,
guess_player = 'rock'
guess_computer = 'scissors'
result = solutions[guess_player][guess_computer]
print(f"It's a {result}. You picked {guess_player} "
f"and the computer picked {guess_computer}")
The while True need some variable in the form
run = True to make the program know when to end the guessing loop by reassigning it a false value at some point or exit like;
run = Tru
while run:
....
....
run = False
Related
I built this simple rock/paper/scissor game by watching some tutorials. Everything is working fine. The issue is that I want to implement something where if the user and the computer choose the same word, then it should say something like "draw."
I could go ahead and add a bunch of "if" and "else" statements, but I don't want that. Can you guys think of any other way to implement that with fewer lines of code?
#Simple rock, paper and scissor game
import random
user_wins = 0
computer_wins = 0
options = ["rock", "paper", "scissors"]
while True:
user_pick = input("Please choose Rock/Paper/Scissors Or Press Q to quit: ")
if user_pick.lower() == "q":
print("You quit.")
break
elif user_pick not in options:
print("Please enter a valid input.")
continue
random_number = random.randint(0, 2)
computer_pick = options[random_number]
print("The computer picked", computer_pick)
if computer_pick == "rock" and user_pick == "scissors":
print("You lost!")
computer_wins += 1
elif computer_pick == "paper" and user_pick == "rock":
print("You lost!")
computer_wins += 1
elif computer_pick == "scissors" and user_pick == "paper":
print("You lost!")
computer_wins += 1
else:
print('You win!')
user_wins += 1
You could use a dictionary to map which choices beat each other. This will enable to you make the conditional part of the code, which determines who wins, more concise. It is also more easily expanded to rock-paper-scissors variants with more options, without the need for many more conditional statements.
#Simple rock, paper and scissor game
import random
user_wins = 0
computer_wins = 0
options = ["rock", "paper", "scissors"]
beaten_by = {
"rock": "scissors",
"scissors": "paper",
"paper": "rock"
}
while True:
user_pick = input("Please choose Rock/Paper/Scissors Or Press Q to quit: ")
if user_pick.lower() == "q":
print("You quit.")
break
elif user_pick not in options:
print("Please enter a valid input.")
continue
random_number = random.randint(0, 2)
computer_pick = options[random_number]
print("The computer picked", computer_pick)
if user_pick == computer_pick:
print("Draw!")
elif user_pick == beaten_by[computer_pick]:
print("You lost!")
computer_wins += 1
else:
print("You win!")
user_wins += 1
I am creating a python code for rock, paper, scissors but I can't seem to keep track of the score of wins, losses, and ties. I think there is something wrong with my "count" which i called "win += 0", "lose += 0" and "tie += 0." Could someone please tell me what I should do to increase the score by 1 every time there is a win, lose or tie?
Here is my code below:
from random import randint
t = ["rock", "paper", "scissors"]
computer = t[randint(0,2)]
player = False
lose = 0
win = 0
for i in range(0,10):
print("1... 2... 3... go!")
while player == False:
player = input("rock, paper, scissors: ")
print("Computer: ", computer)
print("User: ", player)
if player == computer:
tie = 0
tie +=1
print("Tie!")
elif player == "rock":
if computer == "paper":
lose +=0
print("You lose!")
else:
win +=0
print("You win!")
elif player == "paper":
if computer == "scissors":
lose = 0
lose +=0
print("You lose!")
else:
win +=0
print("You win!")
elif player == "scissors":
if computer == "rock":
lose +=0
print("You lose!")
else:
win +=0
print("You win!")
else:
print("That's not a valid play. Check your spelling!")
player = False
computer = t[randint(0,2)]
break
print("Final Tally")
print("************")
print("User Wins: ", win)
print("Computer Wins: ", lose)
print("Ties: ", tie)
if tie > win and tie > lose:
print("It's a tie!")
elif win > tie and win > lose:
print("You won!")
else:
print("The computer won!")
Here's the fixed version. I suggest you work on it some more :)
from random import choice
t = ["rock", "paper", "scissors"]
tie = 0
lose = 0
win = 0
for i in range(0, 10):
print("1... 2... 3... go!")
# you need to refresh these variables on every for iteration
computer = choice(t)
player = None
# if you're using while to make sure player inputs, that's the only thing that needs
# to be within the while loop
while not player:
player = input("rock, paper, scissors: ")
print("Computer: ", computer)
print("User: ", player)
# I would look for a way to simplify determining the winner
if player == computer:
# tie += 1 is the same as tie = tie + 1
tie +=1
print("Tie!")
elif player == "rock":
if computer == "paper":
lose += 1
print("You lose!")
else:
win += 1
print("You win!")
elif player == "paper":
if computer == "scissors":
lose += 1
print("You lose!")
else:
win += 1
print("You win!")
elif player == "scissors":
if computer == "rock":
lose += 1
print("You lose!")
else:
win += 1
print("You win!")
else:
print("That's not a valid play. Check your spelling!")
print("Final Tally")
print("************")
print("User Wins: ", win)
print("Computer Wins: ", lose)
print("Ties: ", tie)
if tie > win and tie > lose:
print("It's a tie!")
elif win > tie and win > lose:
print("You won!")
else:
print("The computer won!")
UPDATE: Apparently I have nothing to do. So ok, here's a straightforward way to simplify win conditioning.
win_condition_rock = player == 'rock' and computer == 'scissors'
win_condition_paper = player == 'paper' and computer == 'rock'
win_condition_scissors = player == 'scissors' and computer == 'paper'
if player == computer:
# tie += 1 is the same as tie = tie + 1
tie +=1
print("Tie!")
elif any([win_condition_paper, win_condition_scissors, win_condition_rock]):
win += 1
print('You win')
else:
lose += 1
print('You lose')
UPDATE 2: And here's a check for valid input
while player not in t:
player = input("rock, paper, scissors: ").lower()
if player not in t:
print('Invalid input')
It's my first time here and I'm kinda panicking. I have an assignment to code Rock, Paper, Scissors in Python. (I use Python 3.1) and for some reason the function is not running...?
Here's the code:
hscore = 0
cscore = 0
tries = 0
#computer choice
rock = ("rock")
paper = ("paper")
scissors = ("scissors")
rps = (rock, paper, scissors)
cchoice = random.choice(rps)
choice = input("\nWhat do you choose? <rock, paper, scissors>: ")
tries +=1
def humanfunction():
if choice == "rock":
if cchoice == scissors:
print("Human wins this round.")
hscore +=1
if choice == "scissors":
if cchoice == paper:
print("Human wins this round.")
hscore +=1
if choice == "paper":
if cchoice == rock:
print("Human wins this round.")
hscore +=1
if cchoice == choice:
print("Tie.")
def compfunction():
if cchoice == scissors:
if choice == "paper":
print("Computer wins this round.")
cscore +=1
if cchoice == rock:
if choice == "scissors":
print("Computer wins this round.")
cscore +=1
if cchoice == paper:
if choice == "rock":
print("Computer wins this rounud.")
cscore +=1
if cchoice == choice:
print("Tie.")
def choose():
tries = 0
while 0 == 0:
choice = input("\nWhat do you choose? <rock, paper, scissors>: ")
tries +=1
print("\nHuman choice: ", choice)
print("Computer choice: ", cchoice)
print("Finished game number", tries)
if tries == 10:
print("Limit reached!")
break
humanfunction()
compfunction()
choose()
I've been trying to solve this for days now and for some reason, when I run the code, it doesn't show up who won. Help would be appreciated <3
EDIT:
here's what i get when i run the code:
output
the program is actually supposed to show this:
output2
Here is my take on your code.
The main reason it wasn't running is that your cscore variable was being referenced before it was initialized, because you had setup cscore as a global variable, but didn't declare it as a global variable in your function.
You also needed to import the random library
Also instead of doing 4 if/then statements I combined them into 1 if/then statement
EDIT: cleaned up the code a little more
EDIT 2: no more globals, avoid globals if possible
import random
def get_human_choice():
valid_choice = False
while not valid_choice:
choice = input("\nWhat do you choose? <rock, paper, scissors>: ")
if choice == 'rock' or 'paper' or 'scissors':
valid_choice = True
return choice
def get_comp_choice():
rps = ('rock', 'paper', 'scissors')
comp_choice = random.choice(rps)
return comp_choice
def human_winner(comp_choice):
print("The computer chooses: %s" % comp_choice)
print("Human wins this round.")
def comp_winner(comp_choice):
print("The computer chooses: %s" % comp_choice)
print("Computer wins this round.")
def stats(attempts, human_score, comp_scored, tie_score):
print("Finished game number: %s" % attempts)
print('Human Score: %s' % human_score)
print('Computer Score: %s' % comp_scored)
print('Ties: %s' % tie_score)
def play_game(human_score, comp_score, tie_score):
choice = get_human_choice()
comp_choice = get_comp_choice()
if choice == 'rock':
if comp_choice == 'scissors':
human_winner(comp_choice)
human_score += 1
else:
comp_winner(comp_choice)
comp_score += 1
elif choice == 'scissors':
if comp_choice == 'paper':
human_winner(comp_choice)
human_score += 1
else:
comp_winner(comp_choice)
comp_score += 1
elif choice == 'paper':
if comp_choice == 'rock':
human_winner(comp_choice)
human_score += 1
else:
comp_winner(comp_choice)
comp_score += 1
elif choice == comp_choice:
print("Tie.")
tie_score += 1
return human_score, comp_score, tie_score
if __name__ == '__main__':
tries = 1
h_score, c_score, t_score = 0, 0, 0
while tries <= 10:
h_score, c_score, t_score = play_game(h_score, c_score, t_score)
if tries == 10:
print("\nLimit reached!\n")
stats(tries, h_score, c_score, t_score)
break
else:
tries += 1
Whenever it takes me several tries to beat the game, it always says the number_of_guesses is 1, which isn't true. What have I done wrong?
My code:
import random
print("Welcome to Rock, Paper, Scissors. \nYou will be going up against the computer, who will randomly",
"choose an object to duel you with!")
user_win = False
while not user_win:
user_guess = input("\nChoose either Rock, Paper or Scissors: ")
user_guess = user_guess.lower()
if user_guess != "rock" and user_guess != "paper" and user_guess != "scissors":
print("You didn't enter a valid guess. Try again, please.")
user_guess = input("\nChoose either Rock, Paper or Scissors: ")
user_guess = user_guess.lower()
computer_guess = random.randint(1,3)
if computer_guess == 1:
computer_guess = "rock"
elif computer_guess == 2:
computer_guess = "paper"
else:
computer_guess = "scissors"
print("Your guess:", user_guess.capitalize(), "\nComputer guess:", computer_guess.capitalize())
number_of_guesses = 1
if user_guess == computer_guess:
print("\nThe game is a tie. You guessed", user_guess, "and so did the computer.")
number_of_guesses += 1
user_win = False
elif (user_guess == "rock" and computer_guess == "scissors") or (user_guess == "paper" and computer_guess == "rock"):
print("\nCongratulations! You have beaten the computer by playing", user_guess.capitalize(), "while the computer played", computer_guess.capitalize())
user_win = True
number_of_guesses += 1
else:
print("\nDamn! The computer won by playing", computer_guess.capitalize(), "while you played", user_guess.capitalize())
user_win = False
number_of_guesses += 1
if number_of_guesses == 1:
print("\nYou won, and it only took you %d try!" % number_of_guesses)
else:
print("\nYou won, and it only took you %d tries!" % number_of_guesses)
input("\nPress enter to exit the program.")
I think that's formatted correctly. It's not easy to put code in here. Thank you!
You are always setting numbers of guesses equal to 1 inside your loop:
print("Your guess:", user_guess.capitalize(), "\nComputer guess:", computer_guess.capitalize())
number_of_guesses = 1 # setting here
Set the number_of_guesses outside the while loop
First of all in the while loop you always initialize number_of_guesses = 1 on every run. That is why this will always be 1 in each run.
Take this initialization before the while.
I am working on a rock paper scissors game. Everything seems to be working well except the win/loss/tie counter. I have looked at some of the other games people have posted on here and I still cannot get mine to work. I feel like I am soooooo close but I just can't get it! thanks for any help guys. this is my first time posting in here so I am sorry if I messed up the formatting.
I edited the code but still cannot get the program to recognize the counter without using global variables. at one point of my editing I managed to get it to count everything as a tie... i dont know how and I lost it somewhere along my editing. lol. -thanks again everyone!
here is what I get when I run the program:
Prepare to battle in a game of paper, rock, scissors!
Please input the correct number according
to the object you want to choose.
Select rock(1), paper(2), or scissors(3): 1
Computer chose PAPER .
You chose ROCK .
You lose!
Play again? Enter 'y' for yes or 'n' for no. y
Prepare to battle in a game of paper, rock, scissors!
Please input the correct number according
to the object you want to choose.
Select rock(1), paper(2), or scissors(3): 2
Computer chose PAPER .
You chose PAPER .
It's a tie!
Play again? Enter 'y' for yes or 'n' for no. y
Prepare to battle in a game of paper, rock, scissors!
Please input the correct number according
to the object you want to choose.
Select rock(1), paper(2), or scissors(3): 3
Computer chose SCISSORS .
You chose SCISSORS .
It's a tie!
Play again? Enter 'y' for yes or 'n' for no. n
Your total wins are 0 .
Your total losses are 0 .
Your total ties are 0 .
#import the library function "random" so that you can use it for computer
#choice
import random
#define main
def main():
#assign win, lose, and tie to zero for tallying
win = 0
lose = 0
tie = 0
#control loop with 'y' variable
play_again = 'y'
#start the game
while play_again == 'y':
#make a welcome message and give directions
print('Prepare to battle in a game of paper, rock, scissors!')
print('Please input the correct number according')
print('to the object you want to choose.')
#Get the player and computers choices and
#assign them to variables
computer_choice = get_computer_choice()
player_choice = get_player_choice()
#print choices
print('Computer chose', computer_choice, '.')
print('You chose', player_choice, '.')
#determine who won
winner_result(computer_choice, player_choice)
#ask the user if they want to play again
play_again = input("Play again? Enter 'y' for yes or 'n' for no. ")
#print results
print('Your total wins are', win, '.')
print('Your total losses are', lose, '.')
print('Your total ties are', tie, '.')
#define computer choice
def get_computer_choice():
#use imported random function from library
choice = random.randint(1,3)
#assign what the computer chose to rock, paper, or scissors
if choice == 1:
choice = 'ROCK'
elif choice == 2:
choice = 'PAPER'
else:
choice = 'SCISSORS'
#return value
return choice
#define player choice
def get_player_choice():
#assign input to variable by prompting user
choice = int(input("Select rock(1), paper(2), or scissors(3): "))
#Detect invalid entry
while choice != 1 and choice != 2 and choice != 3:
print('The valid numbers are rock(type in 1), paper(type in 2),')
print('or scissors(type in 3).')
choice = int(input('Enter a valid number please: '))
#assign what the player chose based on entry
if choice == 1:
choice = 'ROCK'
elif choice == 2:
choice = 'PAPER'
else:
choice = 'SCISSORS'
#return value
return choice
#determine the winner from the variables
def winner_result(computer_choice, player_choice):
#if its a tie, add 1 to tie variable and display message
if computer_choice == player_choice:
result = 'tie'
print("It's a tie!")
#if its a win, add to win tally and display message
elif computer_choice == 'SCISSORS' and player_choice == 'ROCK':
result = 'win'
print('ROCK crushes SCISSORS! You win!')
elif computer_choice == 'PAPER' and player_choice == 'SCISSORS':
result = 'win'
print('SCISSORS cut PAPER! You win!')
elif computer_choice == 'ROCK' and player_choice == 'PAPER':
result = 'win'
print('PAPER covers ROCK! You win!')
#if it does not match any of the win criteria then add 1 to lose and
#display lose message
else:
result = 'lose'
print('You lose!')
def result(winner_result,player_choice, computer_choice):
# accumulate the appropriate winner of game total
if result == 'win':
win += 1
elif result == 'lose':
lose += 1
else:
tie += 1
return result
main()
Your winner_result function returns before it increments the win counters. If you remove all the return statements from it, the counters should be updated. The return statements aren't needed anyway because the if/elif/else structure ensures that only one of the possible outcomes will be executed.
As Junuxx says in a comment, you also need to assign values to the winner_result variable properly, i.e. winner_result = 'win' instead of winner_result == 'win'. I'd also rename the winner_result variable or the function, because it's confusing to have both use the same name.
And the win/lose/tie variables are currently local, which means that main and winner_result will have their own copies of these variables, so main's values will always be zero. What you can do is make them global variables: Assign them to zero in the global scope (outside any function), and add the line global win, lose, tie inside the function winner_result.
Obviously been a few years since this question was answered but it came up while I was looking the same info. Here's my code if anyone is interested.
#! usr/bin/python3
import random
def game():
computer_count = 0
user_count = 0
while True:
base_choice = ['scissors', 'paper', 'rock']
computer_choice = random.choice(base_choice)
user_choice = input('(scissors, paper, rock) Type your choice: ').strip().lower()
print()
computer_wins = 'The computer wins!'
you_win = 'You win!'
print(f'You played {user_choice}, the computer played {computer_choice}')
if user_choice == 'scissors' and computer_choice == 'rock' or \
user_choice == 'paper' and computer_choice == 'scissors' or \
user_choice == 'rock' and computer_choice == 'paper':
print(computer_wins)
computer_count += 1
elif user_choice == 'rock' and computer_choice == 'scissors' or \
user_choice == 'scissors' and computer_choice == 'paper' or \
user_choice == 'paper' and computer_choice == 'rock':
print(you_win)
user_count += 1
else:
if user_choice == computer_choice:
print('Its a draw!')
computer_count += 1
user_count += 1
print(f'Computer: {computer_count} - You: {user_count}')
print()
game()
I was trying to do the same project, and I have found a solution that works well for me.
from random import randint
win_count = 0
lose_count = 0
tie_count = 0
# create a list of play options
t = ["Rock", "Paper", "Scissors"]
# assign a random play to the computer
computer = t[randint(0, 2)]
# set player to false
player = False
print()
print("To stop playing type stop at any time.")
print()
while player == False:
# set player to True
player = input("Rock, Paper or Scissors? ")
if player.lower() == "stop":
print()
print(
f"Thanks for playing! Your final record was {win_count}-{lose_count}-{tie_count}")
print()
break
if player.title() == computer:
print()
print("Tie!")
tie_count += 1
print()
elif player.title() == "Rock":
if computer == "Paper":
print()
print(f"You lose. {computer} covers {player.title()}.")
lose_count += 1
print()
else:
print()
print(f"You win! {player.title()} smashes {computer}.")
win_count += 1
print()
elif player.title() == "Paper":
if computer == "Scissors":
print()
print(f"You lose. {computer} cuts {player.title()}.")
lose_count += 1
print()
else:
print()
print(f"You win!, {player.title()} covers {computer}.")
win_count += 1
print()
elif player.title() == ("Scissors"):
if computer == "Rock":
print()
print(f"You lose. {computer} smashes {player.title()}.")
lose_count += 1
print()
else:
print()
print(f"You win! {player.title()} cuts {computer}.")
win_count += 1
print()
else:
print()
print("Sorry, we couldn't understand that.")
print()
# player was set to True, but we want it to be false to continue loop
print(f"Your record is {win_count}-{lose_count}-{tie_count}")
print()
player = False
computer = t[randint(0, 2)]
This works (kinda)
there are many issues with the code at the top of the page.
Firstly, Scoring doesn't work.
Secondly, nothing is indented meaning that nothing inside of the other def functions will work.
Thirdly, The other def functions are referred to in the first def main statement which causes Python to show an invalid syntax due to Python not knowing the other functions as they were referred to before they were introduced to python.