So, I'm making this game in python. The thing is, in scissors, paper and rock there can be different combinations like .. Rock and paper, Rock and scissors, and so on. So how would I make this without doing heaps of elif statements.
import random
random_choice = ["Scissors", "Paper", "Rock"][random.randint(0, 2)]
player_input = raw_input("What's your choice (Scissors, Paper, or Rock)")
if player_input not in ["Scissors", "Paper", "Rock"]:
print("Not valid choice")
raw_input()
exit()
if player_input == random_choice:
print("You both choose %s" % random_choice)
elif player_input == "Rock" and random_choice == "Scissors":
print("You picked Rock and the bot picked Scissors, you win!")
raw_input()
#And so on making heaps of elif's for all the combinations there can be.
So how do we make this game without having to do so many elif statements or type less code. Surely there has to be a better programming sequence for dealing with these types of things?
If you want to avoid the elif tree, you may use a set to store all the winning combinations:
import random
# random.choice is a convenient method
possible_choices = ["Scissors", "Paper", "Rock"]
random_choice = random.choice(possible_choices)
# set notation, valid since Python 2.7+ and 3.1+ (thanks Nick T)
winning = {("Scissors", "Paper"), ("Paper", "Rock"), ("Rock", "Scissors")}
player_input = raw_input("What's your choice (Scissors, Paper, or Rock)")
if player_input not in possible_choices:
print("Not valid choice.")
raw_input()
if player_input == random_choice:
print("You both choose %s" % random_choice)
elif (player_input, random_choice) in winning:
print("You picked %s and the bot picked %s, you win!" % (player_input, random_choice))
else:
print("You picked %s and the bot picked %s, you lose!" % (player_input, random_choice))
raw_input()
How about doing a map of possible results:
a_beats_b = {('Scissors', 'Paper'): True,
('Scissors', 'Rock'): False,
...
(Note that keys must be tuples). And then do a lookup with like this:
player_wins = a_beats_b[(player_input, random_choice)]
You'll need to handle the case of the same choices (as you already do).
Related
import random
allx = ["rock", "Rock", "paper", "Paper", "Scissors", "scissors"]
rock = ["rock", "Rock"]
paper = ["paper", "Paper"]
scissors = ["Scissors", "scissors"]
robot = ["ROCK!", "PAPER!", "SCISSORS!"]
while True:
print("Let's play rock paper scissors!")
hand = input("Choose one: ")
if hand not in allx:
print("Something went wrong!")
continue
if hand in rock:
print("You choose rock... Let's see what the computer chooses!")
break
elif hand in paper:
print("You choose paper... Let's see what the computer chooses!")
break
elif hand in scissors:
print("You choose scissors... Let's see what the computer chooses!")
break
choice = random.choice(robot)
print("The robot chose " + choice)
now with this, I want to see what the robot chooses from the list, comparing that to the user's choice, and seeing if they won or not. I asked a question similar to this, but it didn't have what I needed.
I have some tips to make your code shorter and easier to read
First tip: you can use the string_name.upper() or string_example.lower() to avoid creating the list with every item in lower and upper, just normalize the input of the user.
Second tip: The robot dont need another list, you cant personalize the same string of the first list adding the exclamation mark and using string.upper() again.
Thirth: You dont need to write the print sencente for every choice, you can use the .format() method of the strings
import random
options = ["rock", "paper", "scissors"]
while True:
print("Let's play rock paper scissors!")
human_chose = input("Choose one: ").lower()
if human_chose in options:
print("You choose {}... Let's see what the computer chooses!".format(human_chose))
break
else:
print("Something went wrong!")
robot_chose = random.choice(options)
print("The robot chose: {}".format(robot_chose.upper() + '!'))
Now, for compare the human_chose with the robot_chose, you can use if conditions on this way:
if human_chose == robot_chose:
# the == symbols compare bot variables searching for equality
print('You win!')
else:
print('You lose')
Sorry if i over explain, i am procrastinating, and sorry for my bad english too
Correction:
if human_choice == 'paper':
if robot_choice == 'rock':
print('you win')
elif robot_chice == 'scissors':
print('you loss')
else:
print('tie')
elif human_choice == 'rock':
if robot_choice == 'scissors':
print('you win')
elif robot_chice == 'paper':
print('you loss')
else:
print('tie')
elif human_choice == 'scissors':
if robot_choice == 'paper':
print('you win')
elif robot_chice == 'rock':
print('you loss')
else:
print('tie')
# or you can do something like:
who_wins = {
'paper': 'rock',
'scissors': 'paper',
'rock': 'scissors'
}
if who_wins[human_choice] == robot_chice:
print('you win')
elif human_choice == robot_chice:
print('tie')
else:
print('you loss')
If the logic is bad you can correct it, probably the long ifs sentences will be easier to understand for you.
Hello i'm doing some personal python learning and i have a practice problem i'm trying to figure out. The main goal is to play paper rock scissors with the computer. Your supposed to input "paper" "rock" or "Scissors" as a user answer and the computer will randomly generate a number from 1-3 that corresponds to a particular choice. I can get the program to work fine if the user inputs a number from 1-3 but that's not what the question asks. I feel like i've tried everything like assigning each name to the corresponding number, creating an if then statement that then reassigns the choice to the numerical value but it always just gets stuck after the input prompt and doesn't move forward with the code. I know the issue lies most likely in the line 6 because thats the last spot it executes.. not sure how to fix it. Also if anyone can give me some pointers on how this could look a little cleaner or if this is roughly what is should look like in terms of efficiency and cleanliness. Keep in mind i have not learned anything too advanced like dictionaries lists ect. Problem should be solved using basic stuff for now. Thank you!
import random
def main():
global user_answer
print('lets play paper rock scissors')
number = comp_answer()
user_answer = int(input('What do you choose?')) <--- # i know the change would be
while number = comp_answer(): # here.... maybe str(input(' '))
tie(number) # then define the choices? tried
paper_rock_scissors(number) # that and failed not sure if i'm
# doing it wrong.
def comp_answer():
number = random.randint(1,4)
return number
def tie(number):
print("its a tie!")
print ("tie breaker")
user_answer = input('What do you choose?')
def paper_rock_scissors(number):
if number == 3 and user_answer == 1:
print("computer: scissors")
print("you: ",user_answer )
print("you won!")
print("rocks smashes scissors")
elif number == 3 and user_answer == 2:
print("computer: scissors")
print("you: ",user_answer )
print("Game over")
print("scissors cuts paper")
elif number == 1 and user_answer == 3:
print("computer: rock")
print("you: ",user_answer )
print("Game over")
print("rocks smashes scissors")
elif number == 2 and user_answer == 3:
print("computer: paper")
print("you: ",user_answer )
print("you won!")
print("scissors cuts paper")
elif number == 1 and user_answer == 2:
print("computer: rock")
print("you: ",user_answer )
print("you won!")
print("paper covers rock")
elif user_answer == 1 and number == 2:
print("computer: paper")
print("you: ",user_answer )
print("Game over")
print("paper covers rock")
main()
In the while loop condition you don't compare the user's choice to the program's.
def main():
global user_answer
print('lets play paper rock scissors')
number = comp_answer()
user_answer = int(input('What do you choose?'))
while user_answer == number:
tie(number)
number = comp_answer()
paper_rock_scissors(number)
Fix this by comparing user_answer and number instead. You also need to specify that user_answer is global in tie. The fact that comp_answer is recomputed in the while condition will make it so that number has the incorrect value when passed to rock_paper_scissors. Those Three changes should fix the issue.
As for cleanliness, global variables are generally bad practice. You could change this by changing tie(number) to user_answer = tie(number) and adding user_answer as an argument to rock_paper_scissors. The tie function also doesn't use it's argument so it could easily be removed.
The problem in your program lies in
"while number = comp_answer():"
It should be a "==" for comparison. "=" is used for assignment and what we need here is an equal to evaluation.
Also,
while number == comp_answer():
doesn't really equate to a tie. It just checks whether the stored value number is equal to the output from comp_answer(). You might wanna equate "user_input" with "number" to check for the same.
P.S. the comp_answer() should be called again in tie function
Try this:
I've put the print statements to a new function that makes the program a big easier to read and shorter.
import random
def main():
global user_answer
print('lets play paper rock scissors')
number = comp_answer()
user_answer = int(input('What do you choose?'))
while number == user_answer:
tie()
paper_rock_scissors(number)
def comp_answer():
number = random.randint(1,4)
return number
def tie():
global number
print("its a tie!")
print ("tie breaker")
number = comp_answer()
user_answer = input('What do you choose?')
def print_ans(computer, user, explanation, win):
print("computer: ", computer)
print("you: ", user)
print(explanation)
if win:
print("you won!")
else:
print("Game over")
def paper_rock_scissors(number):
if number == 3:
if user_answer == 1:
print_ans("scissors", "rock", "rocks smashes scissors", win=True)
else:
print_ans("scissors", "paper", "scissors cut paper", win=False)
elif number == 1:
if user_answer == 3:
print_ans("rock", "scissors", "rocks smashes scissors", win=False)
else:
print_ans("rock", "paper", "paper covers rock", win=True)
else:
if user_answer == 1:
print_ans("paper", "rock", "paper covers rock", win=False)
else:
print_ans("paper", "scissors", "scissors cut paper", win=True)
main()
If you want the user to input string instead of integers, the code will look somewhat like this (mind you I will be using dictionaries as it makes things easier and I think it is important for everyone to know about them, so read up a bit on them):
import random
num_mappings = {"rock":1 , "paper":2 , "scissors":3}
def main():
global user_answer
print('lets play paper rock scissors')
number = comp_answer()
user = input('What do you choose?')
user_answer = num_mappings[user]
while number == user_answer:
tie()
paper_rock_scissors(number)
def comp_answer():
number = random.randint(1,4)
return number
def tie():
global number
print("its a tie!")
print ("tie breaker")
number = comp_answer()
user = input('What do you choose?')
user_answer = num_mappings[user]
def print_ans(computer, user, explanation, win):
print("computer: ", computer)
print("you: ", user)
print(explanation)
if win:
print("you won!")
else:
print("Game over")
def paper_rock_scissors(number):
if number == 3:
if user_answer == 1:
print_ans("scissors", "rock", "rocks smashes scissors", win=True)
else:
print_ans("scissors", "paper", "scissors cut paper", win=False)
elif number == 1:
if user_answer == 3:
print_ans("rock", "scissors", "rocks smashes scissors", win=False)
else:
print_ans("rock", "paper", "paper covers rock", win=True)
else:
if user_answer == 1:
print_ans("paper", "rock", "paper covers rock", win=False)
else:
print_ans("paper", "scissors", "scissors cut paper", win=True)
main()
However, keep in mind, your code will fail if the user types anything other than "rock", "paper" or "scissors". I suggest you look into exception handling to get a good grasp and improve on those aspects.
I am new to python and I am writing a program to play Rock, Paper, Scissor. When I start to do the if else statements to compare outputs from user and the computer, my program just completely skips the if-else statements. Not sure what's going on with it.
user = input("Please enter Rock, Paper, Scissor: ")
while user not in ("Rock", "Paper", "Scissor"):
print("Try again")
user = input("Please enter Rock, Paper, Scissor: ")
if user == "Rock":
print("Your Choice is Rock")
elif user == "Scissor":
print("Your Choice is Scissor")
elif user == "Paper":
print("Your Choice is Paper")
import random
AI=["Rock", "Paper", "Scissor"]
b=random.randint(0,2)
print("The computer choice is " + AI[b])
if user == b:
print("Tie")
elif user == "Rock":
if b == "Scissor":
print("Rock Beats Scissor")
It goes through all of the code expect the last if-else statement. It just finishes the program after the computer chooses what to use.
Your issue is in the last if, you are comparing a string with a integer user == b remember that the user choice is a string but b is a random number between 0 and 2.
if user == AI[b]: # you need to compare the value with the string selection of the "AI"
print("Tie")
elif user == "Rock":
if AI[b] == "Scissor":
print("Rock Beats Scissor")
else:
# I don't remember what are the rules to win or lose LOL, but I guess there are more
# maybe you need more conditions
print("other choice...")
I'm trying to make a simple Rock, Paper, Scissors game in python 3.4 and it works to a certain degree but some time i get an output of "You Won Rock crushes Rock" even though i thought i have stop this from happening and only allowed certain outcomes of the code with my elif and if statements. So can anyone tell me why isn't this working sometimes. :)
import random
count = 0
OPTIONS = ['rock', 'paper', 'scissors']
# then check if the user lose's, wins ties
def computer():
return random.choice(OPTIONS)
print("\n"+"-=-"*11)
print("Welcome to ROCK, PAPER, SCISSORS")
print(" GAME")
print(" It's you Vs. the computer!")
print("-=-"*11)
while True:
user = input("What do you choose Rock, Paper, Scissors: ").lower()
if user in OPTIONS:
# Possible user time a user can succeeds rock beats sicissor, sicissors cuts paper, paper covers rock
if user == computer():
print("tie")
elif user == 'rock' and computer() == 'scissors':
print("\nYou Won! {} crushes {}".format(user.title(), computer().title()))
elif user == 'scissors' and computer() =='rock':
print("\nComputer Won! {} crushes {}".format(computer().title(), user.title() ))
elif user == 'scissors' and computer() == 'paper':
print("\nYou Won! {} cuts {}".format(user.title(), computer().title()))
elif user == 'paper' and computer() == 'scissors':
print("\nComputer Won! {} cuts {}".format(computer().title(), user.title()))
elif user == 'paper' and computer() == 'rock':
print("\nYou Won! {} covers {}".format(user.title(), computer().title()))
elif user == 'rock' and computer() == 'paper':
print("\nComputer Won! {} covers {}".format(computer().title(), user.title()))
else:
print("\nMake sure you choose ethier Rock, Paper or Scissors")
enter code here
elif user == 'rock' and computer() == 'scissors':
print("\nYou Won! {} crushes {}".format(user.title(), computer().title()))
Every time you call computer(), it generates a completely new value, independent of any previous calls. For example, in the code above it's entirely possible that the first computer() call returns "scissors", and the second one returns "rock".
Call computer() only once in the loop, and store the result. Then use that value for the rest of your code.
while True:
user = input("What do you choose Rock, Paper, Scissors: ").lower()
if user in OPTIONS:
computer_move = computer()
# Possible user time a user can succeeds rock beats sicissor, sicissors cuts paper, paper covers rock
if user == computer_move:
print("tie")
elif user == 'rock' and computer_move == 'scissors':
print("\nYou Won! {} crushes {}".format(user.title(), computer_move.title()))
#etc
Your computer() function calls a random number. So every time you call computer() in you code you are choosing 'at random' a completely new number. Because there are only three answers, you may actually end up with the right answer quite often.
Think of calling the function as rolling a die (with 3 sides, whoa). So now your program looks like this:
def RollDice():
return random.choice(OPTIONS)
#...
while True:
user = input("What do you choose Rock, Paper, Scissors: ").lower()
if user in OPTIONS:
# Possible user time a user can succeeds rock beats scissor, scissors cuts paper, paper covers rock
if user == RollDice:
print("tie")
elif user == 'rock' and RollDice == 'scissors':
print("\nYou Won! {} crushes {}".format(user.title(), RollDice.title()))
elif user == 'scissors' and RollDice =='rock':
print("\nComputer Won! {} crushes {}".format(RollDice.title(), user.title() ))
#...
Now you see what the problem is.What you really want is to save the value of 'one' random choice at the very beginning of your if statement:
if user in OPTIONS:
computerChoice = computer()
if user == computerChoice:
print("tie")
elif user == 'rock' and computerChoice == 'scissors':
print("\nYou Won! {} crushes {}".format(user.title(), computerChoice.title()))
elif user == 'scissors' and computerChoice =='rock':
print("\nComputer Won! {} crushes {}".format(computerChoice.title(), user.title() ))
#....
That way you have one constant choice saved in a variable to call on.
P.S. It would also be better to use raw_input instead of input so that the program will automatically change the users input into a string.
Disclaimer, the answer has been given, this is merely to peak the interest in generalizing the game.
To make any type of Rock-Paper-Scissor game you can realize that it is in fact a round-robin table of wins.
For instance if you do this:
P-R-S..P-R-S
you can see that the previous letter always wins on the next letter.
Using this approach it becomes easy to create custom rock-paper-scissor games using look-around tables:
import random
from collections import OrderedDict
# Important to retain order of "kill"
OPTIONS = OrderedDict([('P', 'Paper'),
('R', 'Rock'),
('S', 'Scissors')])
# N_KILLS determines how many letters in front it is killing
N_KILLS = 1
OPTIONS = OrderedDict([('P', 'Princess'),
('J', 'Knight'),
('W', 'Wizard'),
('D', 'Dragon'),
('K', 'King')])
N_KILLS = 2
# Create lookup table
LOOKUP = OPTIONS.keys()
# Number of items
N_ITEMS = len(LOOKUP)
# Options to choose from
STR_OPTIONS = ' ,'.join( OPTIONS.values() )
def computer():
return random.randint(0,N_ITEMS-1)
print("\n"+"-=-"*11)
print("Welcome to "+STR_OPTIONS)
print(" GAME")
print(" It's you vs. the computer!")
print("-=-"*11)
while True:
# Convert user option to integer
uidx = computer()
if uidx >= 0:
# Get computer index
cidx = computer()
d = cidx - uidx
# Correct for wrap-arounds
if d > N_KILLS:
d = d - N_ITEMS
elif d < -N_KILLS:
d = d + N_ITEMS
print(' You choose: '+OPTIONS[LOOKUP[uidx]] + ' computer chooses: '+OPTIONS[LOOKUP[cidx]])
if d == 0:
print(' Tie ...')
elif d > 0 and d <= N_KILLS:
print(' You WIN ...')
elif d < 0 and -d <= N_KILLS:
print(' You LOOSE ...')
else:
# This will only occur if N_KILLS*2+1<N_ITEMS
print(' Tie ...')
Not only is the code easier to read (in my opinion), but it becomes extremely easy to implement several new games. For instance check this amazing game out: http://www.umop.com/rps101.htm
You almost had it correct, as has been mentioned, for each game, the call to computer() should only be made once. It would also make sense to display the two player's choices. Also as you are working in title case, it would make sense to convert everything to use that to avoid needing to call .title() so many times.
import random
OPTIONS = ['Rock', 'Paper', 'Scissors']
# then check if the user lose's, wins ties
def computer():
return random.choice(OPTIONS)
print("\n"+"-=-"*11)
print("Welcome to ROCK, PAPER, SCISSORS")
print(" GAME")
print(" It's you Vs. the computer!")
print("-=-"*11)
while True:
user_choice = input("\nWhat do you choose Rock, Paper, Scissors: ").title()
computer_choice = computer()
print("User: {} Computer: {}".format(user_choice, computer_choice))
if user_choice in OPTIONS:
# Possible user_choice time a user_choice can succeeds rock beats sicissor, sicissors cuts paper, paper covers rock
if user_choice == computer_choice:
print("tie")
elif user_choice == 'Rock' and computer_choice == 'Scissors':
print("You Won! {} crushes {}".format(user_choice, computer_choice))
elif user_choice == 'Scissors' and computer_choice == 'Rock':
print("Computer Won! {} crushes {}".format(computer_choice, user_choice ))
elif user_choice == 'Scissors' and computer_choice == 'Paper':
print("You Won! {} cuts {}".format(user_choice, computer_choice))
elif user_choice == 'Paper' and computer_choice == 'Scissors':
print("Computer Won! {} cuts {}".format(computer_choice, user_choice))
elif user_choice == 'Paper' and computer_choice == 'Rock':
print("You Won! {} covers {}".format(user_choice, computer_choice))
elif user_choice == 'Rock' and computer_choice == 'Paper':
print("Computer Won! {} covers {}".format(computer_choice, user_choice))
else:
print("Make sure you choose either Rock, Paper or Scissors")
So a game would look like:
-=--=--=--=--=--=--=--=--=--=--=-
Welcome to ROCK, PAPER, SCISSORS
GAME
It's you Vs. the computer!
-=--=--=--=--=--=--=--=--=--=--=-
What do you choose Rock, Paper, Scissors: rock
User: Rock Computer: Scissors
You Won! Rock crushes Scissors
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.