Python Rock Paper Scissors game ( Loop for certain condition ) - python

I made a simple Rock Paper Scissors program, and I need to add a certain condition to this program.. I have to Let the
user play continuously until either the user or the computer wins more than two times in a row.I tried to find the answer in and out but unfortunately couldn't find it..
First off I tried
gameOver = False
playerScore = 0
computerScore = 0
and added
while not gameOver:
main()
if playerScore == 2 :
gameOver = True
and also added playerScore += 1 to the if statements..
But wouldn't work ...
any advise would help and much appreciated in advance.. cheers!
And here is my code..
import random
import sys
def main():
player = input("Enter your choice in number (rock 1 / paper 2 / scissors 0) :")
if (player == 0):
player = "scissors"
elif (player == 1):
player = "rock"
elif (player == 2):
player = "paper"
else:
print("Invalid Input Quitting...")
sys.exit(0)
computer = random.randint(0,2)
if (computer == 0):
computer = "scissors"
elif (computer == 1):
computer = "rock"
elif (computer == 2):
computer = "paper"
if (player == computer):
print("Player is ",player, "Computer is ",computer," You Draw!")
elif (player == "rock"):
if (computer == "paper"):
print("Player is ",player, "Computer is ",computer," You Lost!")
else:
print("Player is ",player, "Computer is ",computer," You Win!")
elif (player == "paper"):
if (computer == "rock"):
print("Player is ",player, "Computer is ",computer," You Win!")
else:
print("Player is ",player, "Computer is ",computer," You Lost!")
elif (player == "scissors"):
if (computer == "rock"):
print("Player is ",player, "Computer is ",computer," You Lost!")
else:
print("Player is ",player, "Computer is ",computer," You Win!")

If you have your main() function return a value corresponding to who won, you could do:
gameOver = False
playerScore = 0
computerScore = 0
while not gameOver:
player_wins = main()
if player_wins == True:
playerScore += 1
computerScore = 0
if player_wins == False:
playerScore = 0
computerScore += 1
if player_wins == None:
# Draw, do nothing to the scores
pass
if playerScore == 2 or computerScore == 2:
print("Game over")
print(" playerScore:", playerScore)
print(" computerScore:", computerScore)
gameOver = True
Note that I had it return True if the player won, False if the computer won, and None if it was a draw.

I think you are asking only a schema:
(this is no true code)
Program starts:
gameover = False
lastWinner = ""
Loop until gameover == True
ask for player answer
make the random choice of the computer
winner = "asigned winner"
if lastWinner == winner:
gameover = True
Print something cool about who is the winner
else:
lastWinner = winner

You may be getting an error when attempting to modify the globals, but from your example it's not entirely clear.
If you try to modify playerScore or computerScore in your main() method, it'll yell at you unless you have a statement like:
global computerScore
before you modify it.
Also, avoid repeating yourself in your code. I was able to trim much of your code out by using the following:
computerWins = False
print "Player is %s; Computer is %s" % (computer, player)
if (player == computer):
print "Draw"
return 0
elif (player == "rock"):
computerWins = computer == "paper"
elif (player == "paper"):
computerWins = computer == "scissors"
elif (player == "scissors"):
computerWins = computer == "rock"
if computerWins:
global computerScore
computerScore = computerScore + 1
print "Computer wins"
else:
global playerScore
playerScore = playerScore + 1
print "You win"

Related

Rock, paper, scissors game in Python - some clarification needed

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()

How can I store a number while using multiple if statements?

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')

Why my code ends even though i add a way to restart it

Hello this is me again asking for a question about my code I am creating a Rock, Paper, Scissor i add
main() and def main(): and indent the code but when i run the code this happens
C:\Users\Timothy\Documents>python text.py
C:\Users\Timothy\Documents>
this is my code
def main():
import random
print("1=Rock, 2=Paper, 3=Scissor")
player = int(input("Please Put your choice"))
ai = random.randint(1,3)
###if and else statement for ai to print the random integer to string
if (ai == 3):
print("AI: Scissor")
elif (ai == 2):
print("AI: Paper")
elif (ai == 1):
print("AI: Rock")
####if and statement for the ai and player
if (player == ai):
print("It is a tie")
if (player == 1 and ai == 2):
print("AI won")
if (player == 1 and ai == 3):
print("You Won!!")
if (player == 2 and ai == 1):
print("You won")
if (player == 2 and ai == 3):
print("AI won")
if (player == 3 and ai == 1):
print("AI won")
if (player == 3 and ai == 2):
print("You won")
main()
Yup it is indented too much
def main():
import random
print("1=Rock, 2=Paper, 3=Scissor")
player = int(input("Please Put your choice"))
ai = random.randint(1,3)
###if and else statement for ai to print the random integer to string
if (ai == 3):
print("AI: Scissor")
elif (ai == 2):
print("AI: Paper")
elif (ai == 1):
print("AI: Rock")
####if and statement for the ai and player
if (player == ai):
print("It is a tie")
if (player == 1 and ai == 2):
print("AI won")
if (player == 1 and ai == 3):
print("You Won!!")
if (player == 2 and ai == 1):
print("You won")
if (player == 2 and ai == 3):
print("AI won")
if (player == 3 and ai == 1):
print("AI won")
if (player == 3 and ai == 2):
print("You won")
main() # this way if will run if this condition is met player == 3 and ai == 2
main() # this will surely run in the end calling itself
Here is a way to loop the program using while True so that the game can be played more than once.
def main():
import random
print("1=Rock, 2=Paper, 3=Scissor")
player = int(input("Please Put your choice"))
ai = random.randint(1,3)
###if and else statement for ai to print the random integer to string
if (ai == 3):
print("AI: Scissor")
elif (ai == 2):
print("AI: Paper")
elif (ai == 1):
print("AI: Rock")
####if and statement for the ai and player
if (player == ai):
print("It is a tie")
if (player == 1 and ai == 2):
print("AI won")
if (player == 1 and ai == 3):
print("You Won!!")
if (player == 2 and ai == 1):
print("You won")
if (player == 2 and ai == 3):
print("AI won")
if (player == 3 and ai == 1):
print("AI won")
if (player == 3 and ai == 2):
print("You won")
while True:
main()
restart = input("Again? Y/N: ").upper()
if restart == "Y":
main()
if restart == "N":
break

Python Function not running?

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

How to add score counter to python rock paper scissors

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?

Categories

Resources