Rock, paper, scissors game. Writing a print statement that works - python

Here is my code:
from random import*
from myro import*
from math import*
def computerChoice():
computer = randint(0,2)
if (computer == 0):
choice = "rock"
elif(computer == 1):
choice = "paper"
else:
choice = "scissors"
return choice
def userGuess():
print " R = Rock"
print " P = Paper"
print " S = Scissors"
userChoice = raw_input("Enter R, P, or S: ")
return userChoice
def calculate(userChoice, choice):
userNameWins = 0
computerWins = 0
draws = 0
if(userChoice == "R" and choice == "paper"):
speak("scribbler wins")
computerWins = computerWins + 1
elif(userChoice== "R" and choice == "scissors"):
speak( "you win")
userNameWins = userNameWins + 1
elif(userChoice== "P" and choice == "rock"):
speak("you win")
userNameWins = userNameWins + 1
elif(userChoice== "P" and choice == "scissors"):
speak("scribbler wins")
computerWins = computerWins + 1
elif(userChoice == "S" and choice == "rock"):
speak("scribbler wins")
computerWins = computerWins + 1
elif(userChoice == "S" and choice == "paper"):
speak("you win")
userNameWins = userNameWins + 1
else:
speak("Draw")
draws = draws + 1
return userNameWins, computerWins, draws
def printResults(userNameWins, computerWins, draws)
# insert code for print statement
def main():
for x in range (5):
speak("Rock Papers Scissors ")
userChoice = userGuess()
choice = computerChoice()
calculate(userChoice,choice)
printResults (userNameWins, computerWins, draws)
I get an error when I try to define some variables and I don't know why.
I need a function that properly prints the results returned by calculate()

The part you're asking for is trivial. Since you didn't give us the desired output format, I'll guess at it, and hopefully you can fix it to match the way you want it to look:
def printResults(userNameWins, computerWins, draws)
print('user won {} times, computer won {} times, and players drew {} times'
.format(userNameWins, computerWins, draws))
However, your code isn't going to work, for at least two reasons.
First, you call this:
calculate(userChoice,choice)
… which returns the 3 values you want, but you never store them anywhere. In particular, you don't store them, or anything else, in variables named userNameWins, computerWins, and draws. So, this like will get a NameError:
printResults (userNameWins, computerWins, draws)
Second, you're looping 5 times over a function that, each time, returns a full set of values, but you're only calling printResults once, not 5 times. I'm not sure what you're intending here, but most likely, either you need to move printResults into the loop, or you need to add code that sums up the results across all the loops.

sorry about the wait but hopefully this solution is of help to you.
from random import randint
#from myro import *
choice = None
userChoice = None
userNameWins = 0
computerWins = 0
draws = 0
def computerChoice():
global choice
computer = randint(0,2)
if (computer == 0):
choice = "rock"
elif(computer == 1):
choice = "paper"
else:
choice = "scissors"
print "Scribbler selected " + choice
return choice
def userGuess():
global userChoice
print " R = Rock"
print " P = Paper"
print " S = Scissors"
userChoice = raw_input("Enter R, P, or S: ")
return userChoice
def calculate(userChoice, choice):
global userNameWins
global computerWins
global draws
if(userChoice == "R" and choice == "paper"):
print("scribbler wins")
computerWins = computerWins + 1
elif(userChoice== "R" and choice == "scissors"):
print( "you win")
userNameWins = userNameWins + 1
elif(userChoice== "P" and choice == "rock"):
print("you win")
userNameWins = userNameWins + 1
elif(userChoice== "P" and choice == "scissors"):
print("scribbler wins")
computerWins = computerWins + 1
elif(userChoice == "S" and choice == "rock"):
print("scribbler wins")
computerWins = computerWins + 1
elif(userChoice == "S" and choice == "paper"):
print("you win")
userNameWins = userNameWins + 1
else:
print("Draw")
draws = draws + 1
def printResults():
print "You won " + str(userNameWins) + " times"
print "Scribbler won " + str(computerWins) + " times"
print "There were " + str(draws) + " draws"
if (userNameWins > computerWins):
print "You win overall"
elif (userNameWins < computerWins):
print "Scribbler wins overall"
else:
print "It was a dead heat"
def main():
global userChoice
global choice
for x in range (5):
print ("Rock Papers Scissors ")
userChoice = userGuess()
choice = computerChoice()
calculate(userChoice,choice)
printResults ()
main()
I didn't have myro installed so I used print instead to display the results. Before you weren't saving the variables for the results anywhere so I made a global variable so that it can store the variables. Also I completed the printResults function.

Related

My input sometimes takes multiple times for it to go in the if statements

I am attempting to make a basic rock, paper, scissors game. When I input either rock, paper, or scissors, I sometimes have to enter the same thing multiple times for it to continue to the if statements. See code below:
# Rock, Paper, Scissors
player_total = 0
computer_total = 0
def get_computer_hand():
choice = randint(1, 3)
if choice == 1:
return "scissors"
elif choice == 2:
return "paper"
else:
return "rock"
def ask_user():
global player_total
global computer_total
player = input("Enter your hand (stop to stop): ")
if player == "stop":
print("Computer had ", computer_total, "points, you had ", player_total, " points.")
exit(0)
computer = get_computer_hand()
if player == "rock":
if computer == "paper":
return "win"
elif computer == "scissors":
return "lose"
else:
return "tie"
elif player == "paper":
if computer == "paper":
return "tie"
elif computer == "scissors":
return "lose"
else:
return "win"
elif player == "scissors":
if computer == "scissors":
return "tie"
elif computer == "paper":
return "win"
else:
return "lose"
def count_winner():
global player_total
global computer_total
player_total = 0
computer_total = 0
while True:
outcome = ask_user()
if outcome == "win":
print("You won that one.")
player_total += 1
elif outcome == "lose":
print("Computer won that one.")
computer_total += 1
count_winner()
I expect it to work the first time and to continue as usual, but I can't seem to figure out why it just asks "Enter your hand (stop to stop): " instead sometimes when I enter either rock, paper, or scissors.
This is happening because there is a tie happening between the computer and the user. This could be fixed by adding the end with the code of
else outcome == "tie":
print("You have tied with the Computer!")
computer_total += 1
player_total += 1
This would add a point to both sides and if you don't want that just delete the last two lines of my code

How to create a Rock, Paper, Scissors program

I'm very new to python and am taking an online class. I'm not very familiar with many functions in python so if you could keep it somewhat basic for me to keep track of, I would really appreciate it. I am trying to make a program that runs Rock, Paper, Scissors with a user but the num_games is not being accepted in the "for i in range". Also, I have run it and found that Scissors can beat Rock (THIS IS ANARCHY!). Can anyone assist me? Thanks in advance!
import random
def comp_turn():
comp_move = random.randint(1,3)
if comp_move == 1:
return "Rock!"
elif comp_move == 2:
return "Paper!"
else:
return "Scissors!"
def main():
num_games = int(input("Enter how many games you would like to play: "))
print "You are going to play " + str(num_games) + " games! Here we go!"
num_wins = 0
for i in range(num_games):
user_move = input("Choose either Rock, Paper or Scissors and enter it: ")
cpu_turn = comp_turn()
print "The computer went with: " + cpu_turn
if user_move == 'Rock' and cpu_turn == 'Scissors':
print "You won! Nice job!"
num_wins +=1
elif user_move == 'Paper' and cpu_turn == 'Rock':
print "You won! Nice job!"
num_wins +=1
elif user_move == 'Scissors' and cpu_turn == 'Paper':
print "You won! Nice job!"
num_wins +=1
elif user_move == cpu_turn:
print "Oh! You tied"
else:
print "Whoops! You lost!"
return num_wins
print main()
This should be what you want:
import random
def comp_turn():
return random.choice(['Rock','Paper','Scissors'])
def main():
num_games = int(input("Enter how many games you would like to play: "))
print("You are going to play " + str(num_games) + " games! Here we go!")
num_wins = 0
for i in range(num_games):
user_move = input("Choose either Rock, Paper or Scissors and enter it: ")
cpu_turn = comp_turn()
print("The computer went with: " + cpu_turn)
if user_move == 'Rock' and cpu_turn == 'Scissors': print("You won! Nice job!"); num_wins +=1
elif user_move == 'Paper' and cpu_turn == 'Rock': print("You won! Nice job!"); num_wins +=1
elif user_move == 'Scissors' and cpu_turn == 'Paper': print("You won! Nice job!"); num_wins +=1
elif user_move == cpu_turn: print("Oh! You tied")
else: print("Whoops! You lost!");
return num_wins
print(main())
Or even Better:
import random
def comp_turn():
return random.choice(['Rock','Paper','Scissors'])
def main():
num_games = int(input("Enter how many games you would like to play: "))
print("You are going to play " + str(num_games) + " games! Here we go!")
num_wins = 0
winning=[('Rock','Scissors'),('Paper','Rock'),('Scissors','Paper')]
for i in range(num_games):
user_move = input("Choose either Rock, Paper or Scissors and enter it: ")
cpu_turn = comp_turn()
print("The computer went with: " + cpu_turn)
if (user_move,cpu_turn) in winning:
print('You won!')
num_wins+=1
elif user_move == cpu_turn:
print('Same')
else:
print('You lost!')
return num_wins
print(main())
And another option that's also good:
import random
def comp_turn():
return random.choice(['Rock','Paper','Scissors'])
def main():
num_games = int(input("Enter how many games you would like to play: "))
print("You are going to play " + str(num_games) + " games! Here we go!")
num_wins = 0
d={}.fromkeys([('Rock','Scissors'),('Paper','Rock'),('Scissors','Paper')],'You Won')
for i in range(num_games):
user_move = input("Choose either Rock, Paper or Scissors and enter it: ")
cpu_turn = comp_turn()
print("The computer went with: " + cpu_turn)
if not user_move == cpu_turn:
print(d.get((user_move,cpu_turn),'You lost!'))
else:
print('Same')
return num_wins
print(main())
Here's what you want:
import random
outcome = random.choice(['Rock', 'Paper', 'Scissors'])
print(outcome)
Have you tried removing the '!' in the comp_turn function? It seems like cpu_turn variable will contain either 'Rock!', 'Scissors!' or 'Paper!' while your if-else condition is looking for either 'Rock', 'Scissors' or 'Paper' without the '!'. So, no matter what the player or cpu chooses, it will go into 'else' in the 'for' loop and the player loses.
This is the edited code:
import random
def comp_turn():
comp_move = random.randint(1,3)
if comp_move == 1: return "Rock"
elif comp_move == 2: return "Paper"
else: return "Scissors"
def main():
num_games = int(input("Enter how many games you would like to play: "))
print("You are going to play " + str(num_games) + " games! Here we go!")
num_wins = 0
for i in range(num_games):
user_move = input("Choose either Rock, Paper or Scissors and enter it: ")
cpu_turn = comp_turn()
print("The computer went with: " + cpu_turn)
if user_move == 'Rock' and cpu_turn == 'Scissors':
print("You won! Nice job!")
num_wins +=1
elif user_move == 'Paper' and cpu_turn == 'Rock':
print("You won! Nice job!")
num_wins +=1
elif user_move == 'Scissors' and cpu_turn == 'Paper':
print("You won! Nice job!")
num_wins +=1
elif user_move == cpu_turn:
print("Oh! You tied")
else: print("Whoops! You lost!")
return num_wins
print(main())
Do note that the player's input is case sensitive too. Hope this helps!

Input not read correctly, rock paper scissors lizard spock

as my homework (using codeskulptor.org) I put together a simple Rock-Paper-Scissors-Lizard-Spock 'game' in Python, where hard coded player's guesses were running the programme. Translation from name to number and other way round, random computer choice and printing... everything worked fine.
Then I tried to introduce input so that player gets to type their guess. However, the console prints only the log about wrong input but doesn't launch the rest of the programme if the input is actually correct... Tried various modifications, but I'm stuck... am I missing something obvious? Thanks!
import simplegui
import random
def get_guess(guess):
if guess == "rock":
return 0
elif guess == "Spock":
return 1
elif guess == "paper":
return 2
elif guess == "lizard":
return 3
elif guess == "scissors":
return 4
else:
print "Error guess_to_number:", guess, "is not a rpsls-element"
return
def number_to_name(number):
if number == 0:
return "rock"
elif number == 1:
return "Spock"
elif number == 2:
return "paper"
elif number == 3:
return "lizard"
elif number == 4:
return "scissors"
else:
print "Error number_to_name:", number, "is not in [0, 4]"
return
def rpsls(guess):
print
print "Player chooses", guess
player_number = get_guess(guess)
computer_number = random.randrange(5)
computer_choice = number_to_name(computer_number)
print "Computer chooses", computer_choice
diff_mod = (player_number - computer_number) % 5
if diff_mod == 0:
print "Player and computer tie!"
elif diff_mod == 1 or diff_mod == 2:
print "Player wins!"
else:
print "Computer wins!"
frame = simplegui.create_frame("GUI-based RPSLS", 200, 200)
frame.add_input("Enter guess for RPSLS", get_guess, 200)
frame.start()

Rock Paper Scissors Lizard and Spock. WIns Counter not working

I am stuck on trying to get it to display the number of wins for both the computer and player. I tried using while statements but they never seemed to work so I have if statements that don't allow me to go past 1. Need help understanding what needs to be changed on lines 57, 58, 66 and 69.
selection = {"0" : "Rock", "1" : "Paper", "2" : "Scissors", "3" : "Lizard", "4" : "Spock"}
def RPSLS():
Player = random.randrange(5)
Computer = random.randrange(5)
print "\n"
def Selection(Player):
if Player == 0:
Player = selection["0"]
elif Player == 1:
Player = selection["1"]
elif Player == 2:
Player = selection["2"]
elif Player == 3:
Player = selection["3"]
else:
Player = selection["4"]
print "Player chooses", Player
return Player
Selection(Player)
def Selection(Computer):
if Computer == 0:
Computer = selection["0"]
elif Computer == 1:
Computer = selection["1"]
elif Computer == 2:
Computer = selection["2"]
elif Computer == 3:
Computer = selection["3"]
else:
Computer = selection["4"]
print "Computer chooses", Computer
return Computer
Selection(Computer)
def Wins():
Difference = (Player - Computer) % 5
Playerwins =+ 0
Computerwins =+ 0
if Difference == 0:
print "Player and Computer tie!"
elif Difference <= 2:
Playerwins =+ 1
print "Player Wins!"
else:
Computerwins =+ 1
print "Computer Wins!"
print "\n"
print "Player Wins:", Playerwins
print "Computer Wins:", Computerwins
return Wins
Wins()
Loop = 0
while Loop != 10:
RPSLS()
Loop += 1
raw_input("\n\nPress the enter key to exit.")
There are a lot of issues with your code in terms of scope, syntax, naming conventions, etc. I recommend reading a tutorial on Python best practices. However, without doing a complete rewrite, here are minimum number of changes I needed to make to get your code to work.
import random
selection = {0 : "Rock", 1 : "Paper", 2 : "Scissors", 3 : "Lizard", 4 : "Spock"}
Playerwins = 0
Computerwins = 0
def RPSLS():
global Playerwins, Computerwins
Player = random.randrange(5)
Computer = random.randrange(5)
print "Player chooses", selection[Player]
print "Computer chooses", selection[Computer]
Difference = (Player - Computer) % 5
if Difference == 0:
print "Player and Computer tie!"
elif Difference <= 2:
Playerwins += 1
print "Player Wins!"
else:
Computerwins += 1
print "Computer Wins!"
print "Player Wins:", Playerwins
print "Computer Wins:", Computerwins
print "\n"
Loop = 0
while Loop != 10:
RPSLS()
Loop += 1
raw_input("\n\nPress the enter key to exit.")
Also, I don't think your Rock-Paper-Scissors-Lizard-Spock rules are correct by the usual rules. According to your rules Spock beats Lizard. Check out this solution.

Broken code, need help fixing

This code runs through properly once and then brings the error
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
paper
NameError: name 'paper' is not defined
I need the code to be able to run a game of rock, paper, lizard, spock to run 10 times showing a tally of the scores (as it goes and) at the end of the 10 (or the number of chosen) games.
Here is the code:
import random
numberofgames = raw_input("How many games do you want to play? ")
print "Please choose rock , paper , scissors , lizard, or spock (in lower case please)"
choice = raw_input("What do you choose? ")
player_choice = str(choice)
def name_to_number(name):
if name == "rock":
name = 0
return name
elif name == "spock":
name = 1
return name
elif name == "paper":
name = 2
return name
elif name == "lizard":
name = 3
return name
elif name == "scissors":
name = 4
return name
def number_to_name(number):
if number == 0:
number = "rock"
return number
elif number == 1:
number = "spock"
return number
elif number == 2:
number = "paper"
return number
elif number == 3:
number = "lizard"
return number
elif number == 4:
number = "scissors"
return number
try:
computer_choice = random.randrange(5)
player_number = name_to_number(player_choice)
print "Player choice is: " + player_choice
print "Computer choice is: " + number_to_name(computer_choice)
difference = (int(player_number) - computer_choice) % 5
draws = 0
playerwins = 0
computerwins = 0
if difference in [1, 2]:
print "Player wins!"
playerwins = playerwins + 1
elif difference == 0:
print "Player and computer tie!"
draws = draws + 1
else:
print "Computer wins!"
computerwins = computerwins + 1
print "Wins: " + str(playerwins) + "\n" + "Draws: " + str(draws) + "\n" + "Losses " + str(computerwins)
while playerwins + draws + computerwins <= numberofgames:
name_to_number()
except TypeError:
print "Sorry, please read the directions and type rock, paper, scissors, spock, or lizard in lowercase."
The code you posted raises TypeError: name_to_number() takes exactly 1 argument (0 given) because you call your name_to_number function without an argument.
Btw, here's a simpler version of that function:
name_to_number_dict = dict(rock=0, spock=1, paper=2,lizard=3,scissors=4)
def name_to_number(name):
if name not in name_to_number_dict:
raise ValueError("illegal name")
return name_to_number_dict[name]
Edit:
In fact you don't need such a function at all. A simpler approach might be the following:
import random
data = "rock", "spock", "paper", "lizard", "scissors"
def playgames():
tally = dict(win=0, draw=0, loss=0)
numberofgames = raw_input("How many games do you want to play? ")
numberofgames = int(numberofgames)
for _ in range(numberofgames):
outcome = playgame()
tally[outcome] += 1
print """
Wins: {win}
Draws: {draw}
Losses: {loss}
""".format(**tally)
def playgame():
choice = ""
while (choice not in data):
choice = raw_input("Enter choice (choose rock , paper , scissors , lizard, or spock):")
choice = choice.lower()
print "Player choice is:{}".format(choice)
player_number = data.index(choice)
computer_number = random.randrange(5)
print "Computer choice is: {}".format(data[computer_number])
difference = (player_number - computer_number) % 5
if difference in [1, 2]:
print "Player wins!"
outcome = "win"
elif difference == 0:
print "Player and computer tie!"
outcome = "draw"
else:
print "Computer wins!"
outcome = "win"
return outcome
playgames()

Categories