This is the code that I wrote for a very basic rock paper scissors game.
However when I run the code. It doesn't always print the outcome of the game, ie. You win!, You lose or tie. I am not quite sure why this is the case. HELP!![1]
`
start_game = input('Type start to start game:').lower()
import random
def play():
user = input("'rock' , 'paper', 'scissors' ").lower()
if user == 'quit':
print("Game ended :(")
exit()
computer = random.choice(['rock', 'paper','scissors'])
print(computer)
if user == computer:
return 'tie'
elif not user == is_win(user, computer):
return 'You win!'
else:
return 'You lost!'
def is_win(player,opponent):
if (player == 'rock'and opponent == 'scissors') or (player == 'scissors'and opponent == 'paper') or \
(player=='paper' and opponent == 'rock'):
return True
print(play())
while True:
if start_game != 'start':
start_game = input('Sorry i dont understand please try again:')
else:
print(play())
output:
Type start to start game:srt
Sorry i dont understand please try again:start
'rock' , 'paper', 'scissors' rock
paper
`
The logic to decide the winner is slightly wrong. The object user just contains the user's choice. The function is_win should return a boolean. You do return True when the user wins, but when he loses, you're recalling the original calling function.
start_game = input('Type start to start game:').lower()
import random
def play():
user = input("'rock' , 'paper', 'scissors' ").lower()
if user == 'quit':
print("Game ended :(")
exit()
computer = random.choice(['rock', 'paper','scissors'])
print(computer)
if user == computer:
return 'tie'
elif is_win(user, computer):
return 'You win!'
else:
return 'You lost!'
def is_win(player,opponent):
if (player == 'rock'and opponent == 'scissors') or (player == 'scissors'and opponent == 'paper') or \
(player=='paper' and opponent == 'rock'):
return True
return False
while True:
if start_game != 'start':
start_game = input('Sorry i dont understand please try again:')
else:
print(play())
Try making the above changes and see if it works for you.
You are using is_win() function before defining it!
define the function before play function!
consider this
start_game = input('Type start to start game:').lower()
import random
def is_win(player,opponent):
if (player == 'rock'and opponent == 'scissors') or (player == 'scissors'and opponent == 'paper') or \
(player=='paper' and opponent == 'rock'):
return True
print(play())
def play():
user = input("'rock' , 'paper', 'scissors' ").lower()
if user == 'quit':
print("Game ended :(")
exit()
computer = random.choice(['rock', 'paper','scissors'])
print(computer)
if user == computer:
return 'tie'
elif not user == is_win(user, computer):
return 'You win!'
else:
return 'You lost!'
while True:
if start_game != 'start':
start_game = input('Sorry i dont understand please try again:')
else:
print(play())
what is that print(play()) for? You are running another round of the game inside an unfinished round. I think you should return False instead of that and also change the 'elif' condition:
start_game = input('Type start to start game:').lower()
import random
def play():
user = input("'rock' , 'paper', 'scissors' ").lower()
if user == 'quit':
print("Game ended :(")
exit()
computer = random.choice(['rock', 'paper','scissors'])
print(computer)
if user == computer:
return 'tie'
elif is_win(user, computer):
return 'You win!'
else:
return 'You lost!'
def is_win(player,opponent):
if (player == 'rock'and opponent == 'scissors') or (player == 'scissors'and opponent == 'paper') or \
(player=='paper' and opponent == 'rock'):
return True
return False
while True:
if start_game != 'start':
start_game = input('Sorry i dont understand please try again:')
else:
print(play())
Related
I made the game rock, paper or scissors. I want to implement a game counter, but I can't figure out how to make it work. It is stopped at 1. I want to play more games and the counter to show me the numbers of played games.
import random
stop = False
while (not stop):
games_count = 0
you = input('Player 1: Please type your choice: rock, paper or scissors: ')
oponent = ['rock', 'paper', 'scissors']
choice = random.choice(oponent)
games_count += 1
print('the oponent choice is: ', choice)
if choice == you:
print('DRAW GAME')
elif choice == 'rock' and you == 'paper':
print('YOU LOST')
elif choice == 'rock' and you == 'scissors':
print('YOU WON')
elif choice == 'paper' and you == 'rock':
print('YOU WON')
elif choice == 'paper' and you == 'scissors':
print('YOU LOST')
elif choice == 'scissors' and you == 'rock':
print('YOU LOST')
elif choice == 'scissors' and you == 'paper':
print('YOU WON')
else:
print('Wrong answer, please type rock, paper or scissors in your next attempt!')
answer = input('Do you want to start a new game? (y for yes, any for no): ')
if answer == 'y':
print('New game will start')
print('jocuri terminate: ',games_count)
elif answer == 'no':
stop = True
print('GAME OVER')
else:
print('Wrong answer, please type Yes or No in your next attempt!')
stop = True
Your counter is reinitialized to 0 at each iteration because it is inside your loop.
while not stop:
games_count = 0
...
Instead, initialize it outside the loop.
games_count = 0
while not stop:
...
As a sidenote, you might want to look to other implementations of rock-paper-scissor that do not rely on a big list of if-statement.
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?
I am creating a Rock, Paper, Scissors game. The game has a main menu which I need to be able to return to from each sub menu. I've tried a few different method I could think of as well as looked here and elsewhere online to determine a method of solving my problem.
I want the user to be able to select an option from the main menu, go to the selected sub menu, then be prompted with an option to return to the main menu. For example, Select the rules sub menu, then return to the main menu. Or, select to play a round of Rock, Paper, Scissors, then select to play again or return back to the main menu.
# random integer
from random import randint
# list for weapon
WEAPON = ["Rock", "Paper", "Scissors"]
# module to run the program
#def main():
# menu()
def main():
menuSelect = ""
print("\tRock, Paper, Scissors!")
# main menu
print("\n\t\tMain Menu")
print("\t1. See the rules")
print("\t2. Play against the computer")
print("\t3. Play a two player game")
print("\t4. Quit")
menuSelect = int(input("\nPlease select one of the four options "))
while menuSelect < 1 or menuSelect > 4:
print("The selection provided is invalid.")
menuSelect = int(input("\nPlease select one of the four options "))
if menuSelect == 1:
rules()
elif menuSelect == 2:
onePlayer()
elif menuSelect == 3:
twoPlayer()
elif menuSelect == 4:
endGame()
# display the rules to the user
def rules():
print("\n\t\tRules")
print("\tThe game is simple:")
print("\tPaper Covers Rock")
print("\tRock Smashes Scissors")
print("\tScissors Cut Paper")
print("")
# one player mode
def onePlayer():
again = ""
player = False
print("\n\tPlayer VS Computer")
while player == False:
player = input("\nSelect your weapon: Rock, Paper, or Scissors\n")
player = player.lower()
computer = WEAPON[randint(0,2)]
computer = computer.lower()
if player == computer:
print(player," vs ",computer)
print("It's a tie!\n")
elif player == "rock":
if computer == "paper":
print(player," vs ",computer)
print("Paper covers rock! You lose!\n")
else:
print("Rock smashes",computer,". You win!\n")
elif player == "paper":
if computer == "scissors":
print(player," vs ",computer)
print("Scissors cut paper! You lose!\n")
else:
print("Paper covers",computer,". You win!\n")
elif player == "scissors":
if computer == "rock":
print(player," vs ",computer)
print("Rock smashes scissors! You lose!\n")
else:
print("Scissors cut",computer,". You win!\n")
else:
print("invalid input")
again = input("Would you like to play again? Yes or no\n")
again = again.lower()
if again == "yes" or "y":
player = False
elif again == "no" or "n":
main()
# two player mode
def twoPlayer():
fight = False
player1 = ""
player2 = ""
print("\n\tPlayer VS Player")
while fight == False:
player1 = input("\nSelect your weapon: Rock, Paper, or Scissors\n")
player1 = player1.lower()
player2 = input("\nSelect your weapon: Rock, Paper, or Scissors\n")
player2 = player2.lower()
if player1 == player2:
print(player1," vs ",player2)
print("It's a tie!\n")
elif player1 == "rock":
if player2 == "paper":
print(player1," vs ",player2)
print("Paper covers rock! Player 2 wins!\n")
else:
print("Rock smashes",player2,". Player 1 wins!\n")
elif player1 == "paper":
if player2 == "scissors":
print(player1," vs ",player2)
print("Scissors cut paper! Player 2 wins!\n")
else:
print("Paper covers",player2,". Player 1 wins!\n")
elif player1 == "scissors":
if player2 == "rock":
print(player1," vs ",player2)
print("Rock smashes scissors! Player 2 wins!\n")
else:
print("Scissors cut",player2,". Player 1 wins!\n")
else:
print("invalid input")
again = input("Would you like to play again? Yes or no\n")
again = again.lower()
if again == "yes" or "y":
player = False
elif again == "no" or "n":
main()
def endGame():
print("Thank you for playing!")
main()
Currently my only test is within the onePlayer() module. The idea behind my code is to ask the user if they want to continue playing. If they don't want to continue playing, then I want the program to bring them back to the main menu.
You are using player variable for two works, instead of that you can use another variable to just check the condition and another to take user input.
Also you can check the condition like : if again in ["yes","y"]
def main():
menuSelect = ""
print("\tRock, Paper, Scissors!")
# main menu
print("\n\t\tMain Menu")
print("\t1. See the rules")
print("\t2. Play against the computer")
print("\t3. Play a two player game")
print("\t4. Quit")
menuSelect = int(input("\nPlease select one of the four options "))
while menuSelect < 1 or menuSelect > 4:
print("The selection provided is invalid.")
menuSelect = int(input("\nPlease select one of the four options "))
if menuSelect == 1:
rules()
elif menuSelect == 2:
onePlayer()
elif menuSelect == 3:
twoPlayer()
elif menuSelect == 4:
endGame()
# display the rules to the user
def rules():
print("\n\t\tRules")
print("\tThe game is simple:")
print("\tPaper Covers Rock")
print("\tRock Smashes Scissors")
print("\tScissors Cut Paper")
print("")
# one player mode
def onePlayer():
again = ""
player = False
print("\n\tPlayer VS Computer")
while player == False:
player = input("\nSelect your weapon: Rock, Paper, or Scissors\n")
player = player.lower()
#computer = WEAPON[randint(0,2)]
#temporary
computer = "paper"
computer = computer.lower()
if player == computer:
print(player," vs ",computer)
print("It's a tie!\n")
elif player == "rock":
if computer == "paper":
print(player," vs ",computer)
print("Paper covers rock! You lose!\n")
else:
print("Rock smashes",computer,". You win!\n")
elif player == "paper":
if computer == "scissors":
print(player," vs ",computer)
print("Scissors cut paper! You lose!\n")
else:
print("Paper covers",computer,". You win!\n")
elif player == "scissors":
if computer == "rock":
print(player," vs ",computer)
print("Rock smashes scissors! You lose!\n")
else:
print("Scissors cut",computer,". You win!\n")
else:
print("invalid input")
again = input("Would you like to play again? Yes or no\n")
again = again.lower()
if again=="yes" or again=="y":
player = False
else:
player = True
main()
main()
Do a try and except command. If they say no your code should be quit(). If they say yes put a continue command and it will restart the whole thing.
put your main method in a while (True): loop, and if option 4 is called, use break like this:
elif menuSelect == 4:
break
add an indent to
again = input("Would you like to play again? Yes or no\n")
again = again.lower()
if again == "yes" or "y":
player = False
else:
main()
and rather than calling main() just set player = True also, your Weapon array has not been defined. easy fix, just add WEAPON = ["rock", "paper", "scissors"] to the beginning of your onePlayer(): method. I can see another problem, change
if again == "yes" or "y":
to
if again == "yes" or again == "y":
one last thing, don't forget your imports! (put it at the top of your code.)
from random import randint
BTW, the break statement just tells python to leave whatever for loop or while loop it's in.
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"
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.