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.
Related
The Python program generates rock, paper, scissors game. The game works; however, I am having trouble keeping up with the score. I use the count method to calculate the amount times the user wins, cpu wins, # of rocks/paper/scissors that have been used.
I looked at other similar questions similar to mine. I am stuck because I am using functions. I want to keep the function format for practice.
I tried setting the counter to equal to 0's as globals. That gave a lot of traceback errors.
I tried changing the while loop within the game() function, but that produced an infinite loop. I kept the while loop within the main() function.
What is the best way to approach this? I want to be able to keep scores and for the count to update until the user quits the program.
Thank you!
import sys
import random
def get_user_input():
print("\nWhat do you choose to play? (r, p, s) or q to QUIT ")
player = input().lower()
if player == 'r':
print("You chose: ROCK")
return player
elif player == 'p':
print("You chose: PAPER")
return player
elif player == "s":
print(" You chose: SCISSORS")
return player
elif player == "q":
sys.exit(0)
else:
sys.exit(0)
def game(player):
possible_actions = ["r", "p", "s"]
computer = random.choice(possible_actions)
print("\nYou chose: ", player, "computer chose: ", computer)
rounds = 0
user_wins = 0
computer_wins = 0
tie_count = 0
rocks = 0
papers = 0
scissors = 0
if player == "r" and computer == "r":
print("You & computer TIED!")
tie_count += 1
rounds += 1
rocks += 1
elif player == "p" and computer == "p":
print("You & computer TIED!")
tie_count += 1
rounds += 1
papers += 1
elif player == "s" and computer == "s":
print("You & computer TIED!")
tie_count += 1
rounds += 1
scissors += 1
elif player == "r": # rock
if computer == "p":
print("Paper BEATS rock! You LOST!")
computer_wins += 1
rounds += 1
rocks += 1
else:
print("Rock BEATS scissors! You WIN!")
user_wins += 1
rounds += 1
rocks += 1
elif player == "p":
if computer == "r":
print("Paper BEATS rock! You WIN!")
user_wins += 1
rounds += 1
papers += 1
else:
print("Scissors BEATS paper! You LOST!")
computer_wins += 1
rounds += 1
papers += 1
elif player == "s": # scissors
if computer == "r":
print("Rock BEATS scissors! You LOST!")
computer_wins += 1
rounds += 1
scissors += 1
else:
print("Scissors BEATS paper! You WIN!")
user_wins += 1
rounds += 1
scissors += 1
print("\nComputer Wins ", computer_wins)
print("User Wins ", user_wins)
print("# Draws: ", tie_count)
print("# Rocks Drawn: ", rocks)
print("# Paper Drawn: ", papers)
print("# Scissors Drawn: ", scissors)
def main():
while True:
player = get_user_input()
game(player)
main()
What you call game is only a round. So you have to put the while loop inside the game function.
import random
def get_user_input():
while True:
print("\nWhat do you choose to play? (r, p, s) or q to QUIT ")
player = input().lower()
if player == 'r':
print("You chose: ROCK")
elif player == 'p':
print("You chose: PAPER")
elif player == "s":
print(" You chose: SCISSORS")
elif player == "q":
pass
else:
continue
break
return player
def game():
rounds = 0
user_wins = 0
computer_wins = 0
tie_count = 0
rocks = 0
papers = 0
scissors = 0
while True:
player = get_user_input()
if player == "q":
break
possible_actions = ["r", "p", "s"]
computer = random.choice(possible_actions)
print("\nYou chose: ", player, "computer chose: ", computer)
if player == "r": # rock
if computer == "r":
print("You & computer TIED!")
tie_count += 1
elif computer == "p":
print("Paper BEATS rock! You LOST!")
computer_wins += 1
else:
print("Rock BEATS scissors! You WIN!")
user_wins += 1
rocks += 1
elif player == "p":
if computer == "p":
print("You & computer TIED!")
tie_count += 1
elif computer == "r":
print("Paper BEATS rock! You WIN!")
user_wins += 1
else:
print("Scissors BEATS paper! You LOST!")
computer_wins += 1
papers += 1
elif player == "s": # scissors
if computer == "s":
print("You & computer TIED!")
tie_count += 1
elif computer == "r":
print("Rock BEATS scissors! You LOST!")
computer_wins += 1
else:
print("Scissors BEATS paper! You WIN!")
user_wins += 1
scissors += 1
rounds += 1
print("\nComputer Wins ", computer_wins)
print("User Wins ", user_wins)
print("# Draws: ", tie_count)
print("# Rocks Drawn: ", rocks)
print("# Paper Drawn: ", papers)
print("# Scissors Drawn: ", scissors)
if __name__ == "__main__":
game()
In order to keep your current flow (where game only runs one round), you have to preserve the stats in-between rounds.
This can be done caching stats in a dictionary an returning as follows.
Code
import sys
import random
def get_user_input():
print("\nWhat do you choose to play? (r, p, s) or q to QUIT ")
player = input().lower()
if player == 'r':
print("You chose: ROCK")
return player
elif player == 'p':
print("You chose: PAPER")
return player
elif player == "s":
print(" You chose: SCISSORS")
return player
elif player == "q":
sys.exit(0)
else:
sys.exit(0)
def game(player, stats = None):
if stats is None:
# Initialize runtime stats
stats = {
'rounds' : 0,
'user_wins' : 0,
'computer_wins' : 0,
'tie_count' : 0,
'rocks' : 0,
'papers' : 0,
'scissors' : 0}
# Retrieve stat values
rounds = stats['rounds']
user_wins = stats['user_wins']
computer_wins = stats['computer_wins']
tie_count = stats['tie_count']
rocks = stats['rocks']
papers = stats['papers']
scissors = stats['scissors']
possible_actions = ["r", "p", "s"]
computer = random.choice(possible_actions)
print("\nYou chose: ", player, "computer chose: ", computer)
if player == "r" and computer == "r":
print("You & computer TIED!")
tie_count += 1
rounds += 1
rocks += 1
elif player == "p" and computer == "p":
print("You & computer TIED!")
tie_count += 1
rounds += 1
papers += 1
elif player == "s" and computer == "s":
print("You & computer TIED!")
tie_count += 1
rounds += 1
scissors += 1
elif player == "r": # rock
if computer == "p":
print("Paper BEATS rock! You LOST!")
computer_wins += 1
rounds += 1
rocks += 1
else:
print("Rock BEATS scissors! You WIN!")
user_wins += 1
rounds += 1
rocks += 1
elif player == "p":
if computer == "r":
print("Paper BEATS rock! You WIN!")
user_wins += 1
rounds += 1
papers += 1
else:
print("Scissors BEATS paper! You LOST!")
computer_wins += 1
rounds += 1
papers += 1
elif player == "s": # scissors
if computer == "r":
print("Rock BEATS scissors! You LOST!")
computer_wins += 1
rounds += 1
scissors += 1
else:
print("Scissors BEATS paper! You WIN!")
user_wins += 1
rounds += 1
scissors += 1
print("\nComputer Wins ", computer_wins)
print("User Wins ", user_wins)
print("# Draws: ", tie_count)
print("# Rocks Drawn: ", rocks)
print("# Paper Drawn: ", papers)
print("# Scissors Drawn: ", scissors)
# Cache stat values
stats['rounds'] = rounds
stats['user_wins'] = user_wins
stats['computer_wins'] = computer_wins
stats['tie_count'] = tie_count
stats['rocks'] = rocks
stats['papers'] = papers
stats['scissors'] = scissors
return stats
def main():
stats = None
while True:
player = get_user_input()
stats = game(player, stats)
main()
You have set the values to 0 within the function so every time the function will be called, the rounds will be set to 0. Try initializing the variable outside the function. That should fix it.
def player_choice():
while True:
roundsplayed = int(input("Choose how many rounds you want to play from 1 to 5! "))
if roundsplayed < 1 or roundsplayed > 5:
print ("Please enter a valid number from 1 to 5! ")
continue
return player_choice
else:
print ("Lets play " + roundsplayed + "rounds! ")
roundsplayed = player_choice()
print ("Let's go go go!")
options = ("r", "p", "s", "l", "sp")
from random import randint
computer = options[randint(0,4)]
for i in range(roundsplayed):
wins = 0
loses = 0
draws = 0
player = input("""Choose your hand!
Rock (r)
Paper (p)
Scissor (s)
Lizard (l)
Spock (s)
Your Choice: """)
# if player chooses rock
if player == "r" and computer == "r":
print ("You tied!")
elif player == "r" and computer == "s":
print ("You crushed them! You Win!")
wins += 1
print ("Wins: {} Draws: {} Loses: {}".format(wins, draws, loses))
elif player == "r" and computer == "p":
print ("You got covered! You lose!")
loses += 1
print ("Wins: {} Draws: {} Loses: {}".format(wins, draws, loses))
elif player == "r" and computer == "l":
print ("You crushed them! You Win!")
wins += 1
print ("Wins: {} Draws: {} Loses: {}".format(wins, draws, loses))
elif player == "r" and computer == "sp":
print ("You got vaporized! You lose!")
loses += 1
print ("Wins: {} Draws: {} Loses: {}".format(wins, draws, loses))
So I have this line of code
for i in range(roundsplayed):
wins = 0
loses = 0
draws = 0
player = input("""Choose your hand!
Rock (r)
Paper (p)
Scissor (s)
Lizard (l)
Spock (s)
Your Choice: """)
# if player chooses rock
if player == "r" and computer == "r":
print ("You tied!")
elif player == "r" and computer == "s":
print ("You crushed them! You Win!")
wins += 1
print ("Wins: {} Draws: {} Loses: {}".format(wins, draws, loses))
elif player == "r" and computer == "p":
print ("You got covered! You lose!")
loses += 1
print ("Wins: {} Draws: {} Loses: {}".format(wins, draws, loses))
elif player == "r" and computer == "l":
print ("You crushed them! You Win!")
wins += 1
print ("Wins: {} Draws: {} Loses: {}".format(wins, draws, loses))
elif player == "r" and computer == "sp":
print ("You got vaporized! You lose!")
loses += 1
print ("Wins: {} Draws: {} Loses: {}".format(wins, draws, loses))
And want to make it repeat the number of times I want it to loop by entering a certain variable or input. I put the 'roundsplayed' variable there in the idea that the code would accept a variable entered by the user.
Obviously this doesn't work because the code doesn't define it as an interger.
Also for:
wins = 0
loses = 0
draws = 0
I want it to tally up when the rounds restart to the start of the loop, but obviously have a problem with that as whenever it chooses to restart the loop, the tally is reset to 0, most likely from by obvious mistake.
I hope somebody can help me out, this is all that needs to be fixed for my coding as a python learner, so that I can move on to my next project.
To convert a string to an integer,
int("stringhere")
If you don't want variables reset every time you loop, take them out of the loop.
In order to use the variables in the loop without reset it them, declare them above of the loop (outside the loop).
wins = 0
loses = 0
draws = 0
for i in range(roundsplayed):
player = input("""Choose your hand!
Rock (r)
Paper (p)
Scissor (s)
Lizard (l)
Spock (s)
Your Choice: """)
If you wanna cast a string you got from the console to an int, you can use the Int() function.
var number = int("1")
https://docs.python.org/2/library/functions.html
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()
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()
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.