I'm currently pretty stuck on this rock, paper, scissors program and would greatly appreciate some help. I have looked through other posts concerning rock, paper, scissors programs but I'm still stuck.
The error I'm getting currently is When I ask the user to choose 'Rock', 'Paper' or 'Scissors' it will keep asking it a couple more times and then I get an error. Also, it seems to me that a good portion of the posts I look at involve concepts that I haven't used in class, so I'm not comfortable with them.
choices = [ 'Rock', 'Paper', 'Scissors' ]
# 1. Greetings & Rules
def showRules():
print("\n*** Rock-Paper-Scissors ***\n")
print("\nEach player chooses either Rock, Paper, or Scissors."
"\nThe winner is determined by the following rules:"
"\n Scissors cuts Paper -> Scissors wins"
"\n Paper covers Rock -> Paper wins"
"\n Rock smashes Scissors -> Rock wins\n")
# 2. Determine User Choice
def getUserChoice():
usrchoice = input("\nChoose from Rock, Paper or Scissors: ").lower()
if (usrchoice not in choices):
usrchoice = input("\nChoose again from Rock, Paper or Scissors: ").lower()
print('User chose:', usrchoice)
return usrchoice
# 3. Determine Computer choice
def getComputerChoice():
from random import randint
randnum = randint(1, 3)
cptrchoice = choices(randnum)
print('Computer chose:', cptrchoice)
return randnum
# 4. Determine Winner
def declareWinner(user, computer):
if usrchoice == cptrchoice:
print('TIE!!')
elif (usrchoice == 'Scissors' and cptrchoice == 'Rock'
or usrchoice == 'Rock' and cptrchoice == 'Paper'
or usrchoice == 'Paper' and cptrchoice == 'Scissors'):
print('You lose!! :(')
else:
print('You Win!! :)')
#5. Run program
def playGame():
showRules() # Display the title and game rules
user = getUserChoice() # Get user selection (Rock, Paper, or Scissors)
computer = getComputerChoice() # Make and display computer's selection
declareWinner(user, computer) # decide and display winner
You have few problems with the code:
First is you are converting user input to lowercase but your list items are not. So the check will fail.
choices = [ 'rock', 'paper', 'scissors' ]
Second thing is you are calling choice(randnum) which will throw an error as you have to use [] to retrieve element from list.
cptrchoice = choices[randnum]
Third is what happens if you enter invalid string. You only check with if but you need while loop
while (usrchoice not in choices):
usrchoice = getUserChoice() #input("\nChoose again from Rock, Paper or Scissors: ").lower()
Fourth is in declareWinner, your params are user and computer but then you are using usrchoice and cptrchoice in if conditions
def declareWinner(usrchoice, cptrchoice):
if usrchoice == cptrchoice:
Try this and give it a shot
here is what i did.
you play until you win. it uses the number scheme from chmod to determine wins and losses, and ties. it does not report losses or ties. i can't remember exactly how i figure this out. i was in the zone.
import random
print("Play until you win!")
print("Rock, Paper, or Scissors?")
class GameEngine:
def __init__(self, computer):
self.computer = computer
starter = GameEngine(random.choice([-4,-2,-1]))
class Player:
def __init__ (self, options):
self.options = options
play = Player({"rock":4,"paper":2,"scissors":1})
class ScoreBoard:
def __init__(self, score, loss):
self.score = score
self.loss = loss
while True:
match = ScoreBoard(play.options[input("Choose: ")]+starter.computer,[0,-1,-2,3]) #the dictionary key pair corresponding to the input of rock paper or scissors
if match.score in match.loss:
starter.computer = 0
else:
print("You win!")
break
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 11 months ago.
I'm trying to code a Rock, Paper, Scissors game. How do I prevent them from entering random words/letters and make them reinput their choices until they hit one of the viable choice in the Rock, Paper, Scissors game? For example: "Your input is not viable. Please try again: "
import random
def play():
user = input("Choose your secret weapon! 'Rock' or 'Paper' or 'Scissors': ")
computer = random.choice(['Rock', 'Paper', 'Scissors'])
if user == computer:
return ("It's a tie! You and computer have both chosen {}.").format(user)
if win(user, computer):
return("You've won! You chose {} and computer chose {}.").format(user, computer)
return("You've lost... You chose {} and computer chose {}.").format(user, computer)
def win(user, computer):
if(user == "Scissors" and computer == "Paper") or (user == "Paper" and computer == "Rock") or (user == "Rock" and computer == "Scissors"):
return True
return False
print(play())
You could use a while loop wich chekcks if it is a valid input something like
user_input = input("Choose your secret weapon! 'Rock' or 'Paper' or 'Scissors': ")
while user_input.lower() not in ['rock', 'paper', 'scissors']:
user_input = input("Your input is not viable. Please try again: ")
#Your code
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 for a programming homework assignment and I have run into a little snag. The program is suppose run by the user selecting 1 of 4 options, 1) rock, 2) paper, 3) scissors and 4) quit. Once the player selects an option the computers selection is displayed and the winner is announced and the program will ask if you would like to play another game. If y is select you go back to the main menu to choose another option, anything else will bring up the amount of games won, lost and how many games ended in a tie. If the player selects 4 the program should say "Exiting program..." and the game results should display.
Here are my issues:
Once you make the first selection, the winner is displayed and the program returns to main menu. If you make a second selection it will inform you of what the computer chose and then ask if you would like to play again. Y will take you back to the main menu, the computers selection will never change and no matter what you select the game will always end in the same result as the very first game. If you choose not to play again then the amount of games won, lost and tied will appear (this seems to be functioning correctly).
The quit option takes you back to the main menu instead of displaying the game results. I am not sure where to put that if statement.
Any help with these issues would be appreciated.
Thank you
#import module
import random
def main():
#create a variable to control the loop
play_again = 'y'
#create a counter for tied games, computer games and player games
tied_games = 0
computer_games = 0
player_games = 0
#display opening message
print("Let's play rock, paper scissors!")
computer_choice = process_computer_choice()
player_choice = process_player_choice()
winner = determine_winner(player_choice, computer_choice)
#setup while loop for playing multiple games
while play_again == 'y' or play_again == 'Y':
process_computer_choice()
process_player_choice()
#use a if else statement to print the computers choice
if computer_choice == 1:
print('computer chooses rock.')
elif computer_choice == 2:
print('computer chooses paper.')
else:
print('computer chooses scissors.')
#call the determine winner function
determine_winner(player_choice, computer_choice)
#check who won the game and add 1 to the correct counter
if winner == 'computer':
computer_games += 1
elif winner == 'player':
player_games += 1
else:
tied_games += 1
#ask the user if they would like to play again
play_again = input('would you like to play again? (enter y for yes): ')
#display number of games that were won by the computer, the player and that were tied
print()
print('there was', tied_games, 'tied games.')
print('the player won', player_games, 'games.')
print('The computer won', computer_games,'games.')
#define the process computer function
def process_computer_choice():
#setup computer to select random integer between 1 and 3
choice1 = random.randint(1, 3)
#return the computers choice
return choice1
#define the process player function
def process_player_choice():
#add input for players choice
print()
print(' MENU')
print('1) Rock!')
print('2) Paper!')
print('3) Scissors!')
print('4) Quit')
print()
player_choice = int(input('Please make a selection: '))
#add if statement for quit option
if player_choice == 4:
print('Exiting program....')
#validate if the user enters a correct selection
while player_choice != 1 and player_choice != 2 and player_choice != 3 and player_choice != 4:
#print a error message if the wrong selection is entered
print('Error! Please enter a correct selection.')
player_choice = int(input('Please make a selection: '))
#return the players choice
return player_choice
#define the determine winner function
def determine_winner(player_choice, computer_choice):
#setup if else statements for each of the 3 computer selections
if computer_choice == 1:
if player_choice == 2:
print('Paper wraps rock. You win!')
winner = 'player'
elif player_choice == 3:
print('Rock smashes scissors. The computer wins!')
winner = 'computer'
else:
print('The game is tied. Try again.')
winner = 'tied'
if computer_choice == 2:
if player_choice == 1:
print('Paper wraps rock. The computer wins!')
winner = 'computer'
elif player_choice == 3:
print('Scissors cut paper. You win!')
winner = 'player'
else:
print('The game is tied. Try again.')
winner = 'tied'
if computer_choice == 3:
if player_choice == 1:
print('Rock smashes scissors. You win!')
winner = 'player'
elif player_choice == 2:
print('Scissors cut paper. The computer wins!')
winner = 'computer'
else:
print('The game is tied. Try again.')
winner = 'tied'
return winner
main()
For issue 1, it's because you set the computer and player choices before your loop, and never update them. Change the beginning of your loop to:
while play_again == 'y' or play_again == 'Y':
computer_choice = process_computer_choice()
player_choice = process_player_choice()
You can also remove the lines of code before the loop that check the inputs and winner, as it's technically redundant for the first round.
For issue 2, just add the results after a 4 is chosen, like so:
if player_choice == 4:
print('Exiting program....')
print('there was', tied_games, 'tied games.')
print('the player won', player_games, 'games.')
print('The computer won', computer_games,'games.')
sys.exit() # be sure you add 'import sys' to the beginning of your file
Also, the line in your main loop determine_winner(player_choice, computer_choice) is indented so it will only be called if the computer chooses scissors, so you should unindent that :)
You aren't assigning to computer_choice or player_choice again, but using it's value.
while play_again == 'y' or play_again == 'Y':
process_computer_choice()
process_player_choice()
Should be
while play_again == 'y' or play_again == 'Y':
computer_choice = process_computer_choice()
player_choice = process_player_choice()
As for quitting just break in the quit choice. You have to return early from the process_player_choice and also do something in main.
So in process_player_choice:
if player_choice == 4:
print('Exiting program....')
return
and in main:
player_choice = process_player_choice()
if player_choice == 4:
return
winner = determine_winner(player_choice, computer_choice)
#setup while loop for playing multiple games
while play_again == 'y' or play_again == 'Y':
computer_choice = process_computer_choice()
player_choice = process_player_choice()
if player_choice == 4:
break
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).
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.