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
Related
I am writing a simple game of rock, paper and scissors, where the user competes with a computer. There are 5 tries.
The problems I ran into are :
If I enter something apart from three options, it should return "Invalid Entry". Instead, the program stops
The program never prints "You won the game" or "You lost the game", it finishes after 5 attempts
Other feedback would also be appreciated
import random
def game():
win_count = 0
loose_count = 0
tries = 0
while tries < 5:
chosen = input("Make your choice: ")
if chosen == "scissors" or chosen == "Scissors":
element = "scissors"
elif chosen == "paper" or chosen == "Paper":
element = "paper"
elif chosen == "rock" or chosen == "Rock":
element = "rock"
else:
return "Invalid Entry"
computer_choices = ["scissors", "paper", "rock"]
computer_choice = random.choice(computer_choices)
if element == "scissors" and computer_choice == "paper":
print("Computer chose paper, you chose scissors, you win !")
win_count += 1
tries += 1
elif element == "paper" and computer_choice == "scissors":
print("Computer chose scissors, you chose paper, you loose !")
loose_count += 1
tries += 1
elif element == "paper" and computer_choice == "rock":
print("Computer chose rock, you chose paper, you win !")
win_count += 1
tries += 1
elif element == "rock" and computer_choice == "paper":
print("Computer chose paper, you chose rock, you loose !")
loose_count += 1
tries += 1
else:
print("Whoops, that's a draw, try again")
tries+=1
print("Your Wins: "+ str(win_count))
print("Computer Wins: "+str(loose_count))
if win_count > loose_count:
return "Congrats, you won the game!"
else:
return "Sorry, you lost"
game()
return statement does not print anything but they return the value from a function and as soon as a return statement executes the function ends up executing that's why whenever the user inputs something invalid the program stop.
Also not use the if statement from if chosen = paper or chosen = Paper instead use .lower() to lower the string.
I have made some changes to your code.
Try this code
import random
def game():
win_count = 0
loose_count = 0
tries = 0
while tries < 5:
element = input("Make your choice: ").lower()
computer_choices = ["scissors", "paper", "rock"]
if element not in computer_choices:
print("Invalid choice")
continue
computer_choice = random.choice(computer_choices)
if element == "scissors" and computer_choice == "paper":
print("Computer chose paper, you chose scissors, you win !")
win_count += 1
tries += 1
elif element == "paper" and computer_choice == "scissors":
print("Computer chose scissors, you chose paper, you loose !")
loose_count += 1
tries += 1
elif element == "paper" and computer_choice == "rock":
print("Computer chose rock, you chose paper, you win !")
win_count += 1
tries += 1
elif element == "rock" and computer_choice == "paper":
print("Computer chose paper, you chose rock, you loose !")
loose_count += 1
tries += 1
else:
print("Whoops, that's a draw, try again")
tries+=1
print("Your Wins: "+ str(win_count))
print("Computer Wins: "+str(loose_count))
if win_count > loose_count:
print("Congrats, you won the game!")
else:
print("Sorry, you lost")
game()
This question already has answers here:
Prompt the user to input something else if the first input is invalid [duplicate]
(2 answers)
Closed 2 years ago.
I have tried to create the program to play "Rock, Paper, Scissors, Lizard & Spock", as I had done to create the simple game of "Rock, paper, Scissors", however I cannot with the prompts they asked me:
In addition, it should also improve the way the game interacts with the player: the number of rounds to play, which must be an odd number, will be requested from the user until a valid number is entered. Define a new function to make that request.
Could you help me please? this is the code i used:
import random
gestures = ['rock', 'paper', 'scissors', 'lizard', 'spock']
n_rounds = 0
cpu_score = 0
player_score = 0
import random
gestures = ['rock', 'paper', 'scissors', 'lizard', 'spock']
n_rounds = 0
cpu_score = 0
player_score = 0
def rounds_to_win(gestures):
rounds_to_win = print("How many rounds you want to play? Introduce an odd number")
while rounds_to_win %2 == 0:
if rounds_to_win % 2 > 0:
print("This isn't a valid option. Introduce an odd numbe")
elif rounds_to_win %2 < 0:
print("You chose", rounds_to_win)
def cpu_choice (gestures):
return random.choice(gestures)
def player_choice(gestures):
player_choice = input("Stone, paper, scissors, lizard or spock?. Please, type your choice.")
while player_choice not in gestures:
player_choice = input("That's not an option. Stone, paper, scissors, lizard or spock?")
if player_choice == "stone":
print("You choose stone")
elif player_choice == "paper":
print("You choose paper")
elif player_choice == "scissors":
print("You choose scissor")
elif player_choice == "lizard":
print("You choose lizard")
elif player_choice == "spock":
print("You choose Spock")
return str(player_choice)
def choice(gestures):
print("You chose:", player_choice)
print("CPU chose:", cpu_choice)
if player_choice == "stone" and cpu_choice == "stone":
print("Stone vs stone. It's a tie")
cpu_score += 0
player_score += 0
n_rounds += 1
elif player_choice == "paper" and cpu_choice == "paper":
print("Paper vs paper. It's a tie")
cpu_choice += 0
player_score += 0
n_rounds += 1
elif player_choice == "scissors" and cpu_choice == "scissors":
print("Scissors vs scissors. It's a tie")
cpu_score += 0
player_score += 0
n_rounds += 1
elif player_choice == "stone" and cpu_choice == "paper":
print("Stone vs paper. You loose")
cpu_score += 0
player_score += 2
n_rounds += 1
elif player_choice == "stone" and cpu_choice == "scissors":
print("Stone vs scissors. You win")
cpu_choice += 1
player_score += 0
n_rounds += 1
elif player_choice == "paper" and cpu_choice == "stone":
print("Paper vs stone. You win")
cpu_score += 0
player_score += 2
n_rounds += 1
elif player_choice == "paper" and cpu_choice == "scissors":
print("Paper vs Scissors. You loose")
cpu_choice += 1
player_score += 0
n_rounds += 1
elif player_choice == "scissors" and cpu_choice == "paper":
print("Scissors vs paper. You win")
cpu_score += 0
player_score += 2
n_rounds += 1
elif player_choice == "scissors" and cpu_choice == "stone":
print("Scissors vs stone. You loose")
cpu_choice += 1
player_score += 0
n_rounds += 1
def winner():
print((player_score) - (cpu_score))
while n_rounds < 5:
rounds_to_win(gestures)
player_choice(gestures)
cpu_choices = cpu_choice(gestures)
winner()
if player_score > cpu_score:
print("You won")
else:
print("CPU won")
I presume this is what you were trying to make:
import random
gestures = ['rock', 'paper', 'scissors', 'lizard', 'spock']
def rounds_to_win(gestures):
while True:
rounds_to_win = input("How many rounds you want to play? Introduce an odd number")
if int(rounds_to_win) %2 != 0:
break
else:
print('please input odd number')
return int(rounds_to_win)
def cpu_choice(gestures):
return random.choice(gestures)
def player_choice(gestures):
while True:
players_choice = input("Stone, paper, scissors, lizard or spock?. Please, type your choice.")
if players_choice not in gestures:
print('input not valid')
else:
break
return players_choice
def main_loop(gestures):
player_score=0
cpu_score=0
rounds_played=0
for i in range(rounds_to_win(gestures)):
rounds_played+=1
if player_choice(gestures) == cpu_choice(gestures):
print('you win')
player_score+=1
else:
print('you lose')
cpu_score+=1
print(f'Player score {player_score}\nCPU Score {cpu_score}\nRounds Played {rounds_played}')
main_loop(gestures)
I am trying to create a little Rock paper scissors game as I am a beginner but I am having issues with my if and elif statements.
import random
player_score = 0
computer_score = 0
options = ['rock', 'paper', 'scissors']
def player_choice():
input('Rock, Paper or Scissors? ')
return player_choice
def computer_choice():
print(random.choice(options))
return computer_choice
ps = print('player score: ', player_score)
cs = print('computer_score: ',computer_score)
while player_score or computer_score < 10:
player_choice()
computer_choice()
if player_choice == 'rock' and computer_choice == 'rock':
print('Tie')
elif player_choice == 'rock' and computer_choice == 'paper':
print('Computer wins')
computer_score = computer_score + 1
print(ps)
print(cs)
elif player_choice == 'rock' and computer_choice == 'scissors':
print('You win')
player_score = player_score + 1
print(ps)
print(cs)
It seems as though the entire if/ elif block is ignored and nothing prints or is incremented. No error pops up, it is just simply ignored.
There are a couple of problems with your code, and I am going to try and address all of them.
The first one has to do with the naming of your variables. You name your functions computer_choice and player_choice, and then check if they equal "rock" or other strings. This is only going to return False because computer_choice is a function, not a string. I would recommend changing the names of your functions to get_computer_choice() and get_player_choice()
Secondly, ps = print('player score: ', player_score). I don't know what you are trying to do there. ps will be None, because print() doesn't return anything.
Third, your functions return themselves.
def my_func():
return my_func
Will return a function. What you want to do for both of your choice functions is this:
def get_player_choice():
player_choice = input('Rock, Paper or Scissors? ')
return player_choice
def get_computer_choice():
computer_choice = random.choice(options) # Set computer_choice to computers choice
print(computer_choice)
return computer_choice
Fourth, under your while loop, you are calling the functions, but aren't doing anything with the returns. Change
while player_score or computer_score < 10:
player_choice()
computer_choice()
to
while player_score or computer_score < 10:
player_choice = get_player_choice()
computer_choice = get_computer_choice()
Finally, the if ... else statements need to be indented under the while loop, otherwise they never get executed.
Please check the 13th line of your code. I couldn't understand what ps = print(...) means.
There were several issues with your code.
def player_choice():
input('Rock, Paper or Scissors? ')
return player_choice
player_choice is not initialised. Input takes the user input, but the result is not stored anywhere.
def get_player_choice():
choice = input("Rock, Paper or Scissors? ")
return choice
Same procedure for computer_choice.
Then there is:
ps = print('player score: ', player_score)
cs = print('computer_score: ',computer_score)
I assume you tried to construct a string containing the scores. I suggest
def print_score():
print('player score: ', player_score)
print('computer_score: ',computer_score)
instead. You can then call the function whenever you want to see the score.
And finally, the indent was not right for the if-else statements. It should have been in the while loop. Now it just asks the user for input and generates a choice for the computer in an endless loop.
Here are all changes I suggested combined:
import random
player_score = 0
computer_score = 0
options = ['rock', 'paper', 'scissors']
def get_player_choice():
player_choice= input('Rock, Paper or Scissors? ')
return player_choice
def get_computer_choice():
computer_choice = random.choice(options)
print(computer_choice)
return computer_choice
def print_score():
print('player score: ', player_score)
print('computer_score: ',computer_score)
while player_score < 10 and computer_score < 10:
player_choice = get_player_choice()
computer_choice = get_computer_choice()
if player_choice == 'rock' and computer_choice == 'rock':
print('Tie')
elif player_choice == 'rock' and computer_choice == 'paper':
print('Computer wins')
computer_score = computer_score + 1
print_score()
elif player_choice == 'rock' and computer_choice == 'scissors':
print('You win')
player_score = player_score + 1
print_score()
A few notes:
1. I changed the name of your functions to avoid a later error when calling them.
2. As suggested in another answers you must pass a variable to store the result from the functions.
3. It was missing indentation
4. Some of your conditions were not right. Such as the while condition: if ((player_score<10) or (computer_score < 10)), even if someone reaches the score of 10, the game will keep going. We don't want that, so it must be the and condition.
Here is the solution:
import random
player_score = 0
computer_score = 0
options = ['rock', 'paper', 'scissors']
def choice_player():
result_player = str((input('rock, paper or scissors? ')))
return (result_player)
def choice_computer():
result_computer = random.choice(options)
return (result_computer)
#---------------------------------------------
ps = print('player score: ', player_score)
cs = print('computer_score: ',computer_score)
while ((player_score<10) and (computer_score < 10)):
player_choice = choice_player()
computer_choice = choice_computer()
if ((player_choice == 'rock') and (computer_choice == 'rock')):
print('Tie')
elif ((player_choice == 'rock') and (computer_choice == 'paper')):
print('Computer wins')
computer_score = computer_score + 1
print('player score: ', player_score)
print('computer_score: ',computer_score)
elif ((player_choice == 'rock') and (computer_choice == 'scissors')):
print('You win')
player_score = player_score + 1
print('player score: ', player_score)
print('computer_score: ',computer_score)
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')
import random
name = input("What is your name?")
print ("Welcome to Rock Paper Scissors", name, "!")
def computerThrow():
throwOptions = ["rock","paper","scissors"]
randomChoice = random.randint(0,2)
return throwOptions [randomChoice]
def playerThrow():
player = input("rock, paper, scissors?")
return player
def compareThrows(player, computer):
if player == computer:
return("tie")
elif player == "rock":
if computer == "scissors":
return("win")
else:
return("lose")
elif player == "scissors":
if computer == "paper":
return("win")
else:
return("lose")
elif player == "paper":
if computer == "rock":
return("win")
else:
return("lose")
else:
return("invalid")
def printMatchOutcome(result, player, computer):
if result == "win":
print(player, "beats", computer, " — You win!")
if result == "lose":
print (computer,"beats",player, "- You lose!")
if result == "tie":
print("tie match!")
if result == "invalid":
print ("invalid...try again")
def oneRound():
player = playerThrow()
print("You threw:",player)
computer = computerThrow()
print("Computer threw:",computer)
compare = compareThrows(player, computer)
printMatchOutcome(compare, player, computer)
#define counter variable
gamesPlayed = 0
playerWins = 0
computerWins = 0
userWantsToPlay = True
while userWantsToPlay:
oneRound()
response = input("Do you want to play again? (yes / no)")
if response == 'yes':
userWantsToPlay = True
else:
userWantsToPlay = False
print("Thanks for playing!")
def score(result):
oneRound()
if result == "win":
return playerWins + 1
elif result == "lose":
return computerWins + 1
I am trying to add a score counter to my game so that once userWantsToPlay = False it will display the number of games played, and the score for the computer and the player. I have started it as a function but I am not sure if that is even right? How would I go about this?