Broken code, need help fixing - python

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

Related

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

Python Coding Rock,Paper,Scissors,Lizard and Spock [duplicate]

This question already has an answer here:
How can I concatenate str and int objects?
(1 answer)
Closed 6 years ago.
total_guess = 0
wins = 0
loss = 0
import random
characters = ["rock", "paper", "scissors", "lizard", "spock"]
computer = characters[random.randint(0,4)]
print(computer)
Subroutine- functions fine
def valid(text, flag):
error_message= ""
while True:
var = input(error_message + text)
if flag == "s":
if var.isalpha()==True:
break
else:
error_message = "This is not valid, "
elif flag =="i":
if var.isdigit()==True:
var = int(var)
break
else:
error_message = user_name + " this is not a number, "
elif flag == "g":
if var == "rock" or var == "paper" or var == "scissors" or var == "lizard" or var == "spock":
break
else:
error_message = user_name + " this is not valid! "
return(var)
user_name = valid("What is your name?", "s")
num_rounds = valid(user_name +" how many rounds do you want?", "i")
This code does not work either due to past changes initially worked, 'says can't convert 'int' object to str implicitly
while True:
player = valid(user_name + """ ,What do you want as your character:
Rock, paper, scissors, lizard or spock""", "g" )
while num_rounds > total_guess:
total_guess = total_guess + 1
if player == computer:
print("Draw!")
# --------------------------------------------
elif player == "Rock" or player == "rock":
if computer == "paper" or computer == "spock" :
loss = loss + 1
print("You lost ", computer, " beats ", player)
print( user_name + " you have won " + wins +" games")
if computer == "scissors" or computer == "lizard":
wins = wins + 1
print("You win", player, " beats ", computer)
# ---------------------------------------------
elif player == "Paper" or player == "paper":
if computer == "scissors" or computer == "lizard":
loss = loss + 1
print("You lost ", computer, " beats ", player)
if computer == "rock" or computer == "spock":
wins = wins + 1
print("You win", player, " beats ", computer)
# ---------------------------------------------
elif player == "Scissors" or player == "scissors":
if computer =="Spock" or computer == "rock":
loss = loss + 1
print("You lost ", computer, " beats ", player)
if computer =="paper" or computer == "lizard":
wins = wins + 1
print("You win", player, " beats ", computer)
# --------------------------------------------
elif player == "Lizard" or player =="lizard":
if computer =="scissors" or computer == "rock":
loss = loss + 1
print("You lost ", computer, " beats ", player)
if computer == "paper" or computer == "spock":
wins = wins + 1
print("You win", player, " beats ", computer)
# --------------------------------------------
elif player == "Spock" or player == "spock":
if computer == "lizard" or computer == "paper":
loss = loss + 1
print("You lost ", computer, " beats ", player)
if computer =="rock" or computer == "scissors":
wins = wins + 1
print("You win", player, " beats ", computer)
# -------------------------------------------
This block code to restart game does not work it's purpose is to have a try again feature
end_game = input("To exit enter N, to play again enter any key ")
if end_game == 'n' or end_game == 'N':
print("THANKS FOR PLAYING " + user_name + '!')
break
This could be shortened heavily but I don't feel like rewriting your entire program. This should work as expected.
total_guess = 0
wins = 0
loss = 0
import random
characters = ["rock", "paper", "scissors", "lizard", "spock"]
computer = characters[random.randint(0,4)]
print(computer)
def valid(text, flag):
error_message= ""
while True:
var = input(error_message + text)
if flag == "s":
if var.isalpha()==True:
break
else:
error_message = "This is not valid, "
elif flag =="i":
if var.isdigit()==True:
var = int(var)
break
else:
error_message = user_name + " this is not a number, "
elif flag == "g":
if var == "rock" or var == "paper" or var == "scissors" or var == "lizard" or var == "spock":
break
else:
error_message = user_name + " this is not valid! "
return(var)
user_name = valid("What is your name?", "s")
num_rounds = valid(user_name +" how many rounds do you want?", "i")
while True:
while num_rounds > total_guess:
player = valid(user_name + """ ,What do you want as your character:
Rock, paper, scissors, lizard or spock""", "g" )
total_guess = total_guess + 1
if player == computer:
print("Draw!")
# --------------------------------------------
elif player == "Rock" or player == "rock":
if computer == "paper" or computer == "spock" :
loss = loss + 1
print(' '.join(("You lost", computer, "beats", player)))
if computer == "scissors" or computer == "lizard":
wins = wins + 1
print(' '.join(("You win", player, "beats", computer)))
elif player == "Paper" or player == "paper":
if computer == "scissors" or computer == "lizard":
loss = loss + 1
print(' '.join(("You lost", computer, "beats", player)))
if computer == "rock" or computer == "spock":
wins = wins + 1
print(' '.join(("You win", player, "beats", computer)))
elif player == "Scissors" or player == "scissors":
if computer =="Spock" or computer == "rock":
loss = loss + 1
print(' '.join(("You lost", computer, " beats ", player)))
if computer =="paper" or computer == "lizard":
wins = wins + 1
print(' '.join(("You win", player, "beats", computer)))
elif player == "Lizard" or player =="lizard":
if computer =="scissors" or computer == "rock":
loss = loss + 1
print(' '.join(("You lost", computer, "beats", player)))
if computer == "paper" or computer == "spock":
wins = wins + 1
print(' '.join(("You win", player, "beats", computer)))
elif player == "Spock" or player == "spock":
if computer == "lizard" or computer == "paper":
loss = loss + 1
print(' '.join(("You lost", computer, "beats", player)))
if computer =="rock" or computer == "scissors":
wins = wins + 1
print(' '.join(("You win", player, "beats", computer)))
end_game = input("To exit enter N, to play again enter any key ")
if end_game == 'n' or end_game == 'N':
print("THANKS FOR PLAYING " + user_name + '!')
break
total_guess = 0

How to execute multiple while loops?

I was wondering if someone could tell me how to have the computer choose a new choice after every round. I got the lower portion of the code to cover all choices but it turns out my code runs where the computer uses the same choice every time. Is there a way to set my code so the computer chooses something new from the list. Thanks!
import random
def computerChoice():
gameList = ["Rock", "Paper", "Scissors"]
computerChoice = random.choice(gameList)
print(computerChoice)
def userChoice(computerChoice):
userScore = 0
computerScore = 0
rounds = 0
print("Welcome to Rock, Paper, Scissors. You are playing against the computer on best out of three game, winner takes all! Have Fun!")
while userScore < 2 and computerScore < 2:
userAnswer = input("Please choose Rock, Paper, or Scissors: ")
if userAnswer == "Rock" and computerChoice != "Paper":
userScore += 1
rounds += 1
print("The Computer Loses and You Win the Round!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Paper" and computerChoice != "Scissors":
userScore += 1
rounds += 1
print("The Computer Loses and You Win the Round!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Scissors" and computerChoice != "Rock":
userScore += 1
rounds += 1
print("The Computer Loses and You Win the Round!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Rock" and computerChoice == "Paper":
computerScore += 1
rounds += 1
print("The Computer Wins and You Lose the Round!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Paper" and computerChoice == "Scissors":
computerScore += 1
rounds += 1
print("The Computer Wins and You Lose the Round!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Scissors" and computerChoice == "Rock":
computerScore += 1
rounds += 1
print("The Computer Wins and You Lose the Round!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Rock" and computerChoice == "Rock":
print("This round is a PUSH!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Scissors" and computerChoice == "Scissors":
print("This round is a PUSH!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
elif userAnswer == "Paper" and computerChoice == "Paper":
print("This round is a PUSH!")
print("You have a score of " + str(userScore) + " and the computer has a score of " + str(computerScore))
continue
else:
print("Whatever you just inputed doesn't work noodlehead, try again!")
continue
x = computerChoice()
print(userChoice(x))
Move this inside your while loop:
computerChoice = random.choice(gameList)
Currently you are saving a single choice, and then using it every time. Where as this would create a new choice each time:
while userScore < 2 and computerScore < 2:
userAnswer = input("Please choose Rock, Paper, or Scissors: ")
computerChoice = random.choice(gameList)
# Compare to see who won.
Note that gameList must be available inside that scope, so you will have to either pass it in as a function parameter or include it inside the function. That does change the nature of the function somewhat:
def game():
print("Welcome to Rock, Paper, Scissors. You are playing against the computer on best out of three game, winner takes all! Have Fun!")
userScore, computerScore, rounds = game_loop()
def game_loop(available_options: list=["Rock", "Paper", "Scissors"]):
computerScore = 0
userScore = 0
rounds = 0
while userScore < 2 and computerScore < 2:
userAnswer = input("Please choose Rock, Paper, or Scissors: ")
computerChoice = random.choice(available_options)
// compare and score (preferably in their own functions)
return userScore, computerScore, rounds
try this
import random
def computerChoice():
gameList = ["Rock", "Paper", "Scissors"]
return random.choice(gameList)
def userChoice(computerChoice):
userScore = 0
computerScore = 0
rounds = 0
print("Welcome to Rock, Paper, Scissors. You are playing against the computer on best out of three game, winner takes all! Have Fun!")
while userScore < 2 and computerScore < 2:
userAnswer = input("Please choose Rock, Paper, or Scissors: ")
#all your if statements and stuff
computerChoice = computerChoice()
print(userChoice(computerChoice()))

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.

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

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.

Categories