Rock paper scissors scoring problems [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Please can someone tell me how to do a basic scoring system to go into this code.
import random
print 'Welcome to Rock, paper, scissors!'
firstto=raw_input('How many points do you want to play before it ends? ')
playerscore=+0
compscore=+0
while True:
choice = raw_input ('Press R for rock, press P for paper or press S for scissors, CAPITALS!!! ')
opponent = random.choice(['rock', 'paper' ,'scissors' ])
print 'Computer has chosen', opponent
if choice == 'R' and opponent == "rock":
print 'Tie'
playerscore = playerscore+0
compscore = compscore+0
elif choice == 'P' and opponent == "paper":
print 'Tie'
playerscore = playerscore+0
compscore = compscore+0
elif choice == 'S' and opponent == "scissors":
print 'Tie'
playerscore = playerscore+0
compscore = compscore+0
elif choice == 'R' and opponent == "paper":
print 'CPU Wins'
playerscore = playerscore+0
compscore = compscore+1
elif choice == 'P' and opponent == "scissors":
print 'CPU Wins'
playerscore = playerscore+0
compscore = compscore+1
elif choice == 'S' and opponent == "rock":
print 'CPU Wins'
playerscore = playerscore+0
compscore = compscore+1
elif choice == 'P' and opponent == "rock":
print 'You Win'
playerscore = playerscore+1
compscore = compscore+0
elif choice == 'S' and opponent == "paper":
print 'You Win'
playerscore = playerscore+1
compscore = compscore+0
elif choice == 'R' and opponent == "scissors":
print 'You Win'
playerscore = playerscore+1
compscore = compscore+0
print 'Player score is',playerscore
print 'Computer score is',compscore
if playerscore == firstto:
'You won the game :)'
exit()
elif compscore == firstto:
'You lost the game :('
exit()

The problem lies with raw_input on line 3. raw_input always returns a string, whereas what you need is an int. If you change line 3 to:
firstto = int(raw_input('How many points do you want to play before it ends? '))
your code will work.
To sanitize user input (so that your code does not come crashing down when the user enters "hello" instead of 5), you can wrap the raw_input call into a try, except statement.
For instance:
valid_input = False # flag to keep track of whether the user's input is valid.
while not valid_input:
firstto_str = raw_input('How many points do you want to play before it ends? ')
try:
# try converting user input to integer
firstto = int(firstto_str)
valid_input = True
except ValueError:
# user input that cannot be coerced to an int -> raises ValueError.
print "Invalid input, please enter an integer."
As an aside, your code was stuck in an infinite loop because you were using the string provided by raw_input in comparisons with integers. This will always return False:
>>> "5" == 5
False

There are many ways to optimize this code, but your immediate problem is the raw_input and the entry of points. This returns a string, while you need an int. Wrap it with int() and you'll be fine. That is, until someone enters a something that cannot be parsed.
firstto = int(raw_input('How many points do you want to play before it ends? '))
EDIT: If you're interested, I've tried optimizing your code a bit (without going to extremes):
import random
what_beats_what = [('R', 'S'), ('S', 'P'), ('P', 'R')]
choices = {'R': 'Rock', 'P': 'Paper', 'S': 'Scissors'}
def outcome(player_a, player_b):
for scenario in what_beats_what:
if player_a == scenario[0] and player_b == scenario[1]:
return 'A'
elif player_b == scenario[0] and player_a == scenario[1]:
return 'B'
print 'Welcome to Rock, paper, scissors!'
score_to_win = 0
while True:
try:
score_to_win = int(raw_input('How many points do you want to play before it ends? '))
if score_to_win > 0:
break
except ValueError:
pass
print 'Try again, with a positive integer.'
human_score = 0
cpu_score = 0
while human_score < score_to_win and cpu_score < score_to_win:
human_choice = ''
while True:
human_choice = raw_input('Press R for rock, press P for paper or press S for scissors: ').upper()
if human_choice in choices:
break
else:
print 'Try again ...'
cpu_choice = random.choice(choices.keys())
print 'Computer has chosen: {0}'.format(choices[cpu_choice])
result = outcome(human_choice, cpu_choice)
if result == 'A':
print "Human wins!"
human_score += 1
elif result == 'B':
print "CPU wins!"
cpu_score += 1
else:
print 'It is a tie!'
print 'Human score is: {0}'.format(human_score)
print 'CPU score is: {0}'.format(cpu_score)
print 'You won the game :)' if human_score > cpu_score else 'You lost the game :('

Modify your first raw_input value. You are getting a string there.
For better result, validate the input as well :-)
while 1:
firstto=raw_input('How many points do you want to play before it ends? ')
if firstto.isdigit():
firstto = int(firstto)
break
else:
print "Invalid Input. Please try again"
This will accept only the strings with numbers. Even if some one gives input as "5.0", it will be neglected.
For better reading on raw_input, click here. To learn more about built-in string methods, read here.
PS: This is not related to the question. But a little suggestion. Your code could be made much simpler. If you are learning, keep this code as v0.1 and update it upon your progress.

Related

If user inputs letter output should be word

Basically, my game runs off 3 words - Steal, Deal or Quit however I want the option that if the user inputs say the letter 's' it should = Steal as the output (The player is versing a PC and the results of the game are based on the 2 values.
human = input('Steal, Deal or Quit [s|d|q]?:')
print(" ")
print('You chose: ' + human)
#Computer input
sd = ["Steal", "Deal"]
computer_choice = random.choice(sd)
print('Comp chose: ' + computer_choice)
print(" ")
if human == computer_choice:
print('Draw! Split pot -50 each')
elif human == 'Steal' and computer_choice == 'Deal':
print('You win! You gain 100.')
elif human == 'Deal' and computer_choice == 'Steal':
print('You loose! Comp gain 100.')
elif human == 'Steal' and computer_choice == 'Steal':
print('Too Greedy! You get nothing')
You should use a dictionary to map the human letter input to the words Steal or Deal
First add the dictionary at the top:
human_input_map = {
's': 'Steal'
'd': 'Deal'
}
Then after taking the user input you can convert their input into the full word for comparing with computer_choice.
human = input('Steal, Deal or Quit [s|d|q]?:')
human = human_input_map[human]

Break command doesn't stop loop [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
The Break Command Doesnt work and when i try to run it, it gets stuck like it cant compile because its stuck in a loop
My code isn't running at all, I have reviewed my code but it doesn't seem to work. Everything is fine for me.
import random
# print("Winning Rules of the Rock paper scissor game as follows: \n"
# + "Rock vs paper->paper wins \n"
# + "Rock vs scissor->Rock wins \n"
# + "paper vs scissor->scissor wins \n")
while True:
def main():
print("Enter choice \n 1. Rock \n 2. paper \n 3. scissor \n")
try :
choice_name = (input("User turn: "))
if choice_name == 1:
choice_name = 'Rock'
if choice_name == 2:
choice_name = 'paper'
if choice_name == 3:
choice_name = 'scissor'
else:
choice_name = None
input("Atleast Enter a Valid Number like BRUHHHHHHHHH: ")
except ValueError:
print ("Try again")
main()
print("user choice is: " + choice_name)
print("\nNow its computer turn.......")
Computer_Choice = random.randint(1, 3)
while Computer_Choice == choice_name:
Computer_Choice = random.randint(1, 3)
if Computer_Choice == 1:
Computer_Choice_name = 'Rock'
elif Computer_Choice == 2:
Computer_Choice_name = 'paper'
else:
Computer_Choice_name = 'scissor'
print("Computer choice is: " + Computer_Choice_name)
print(choice_name + " V/s " + Computer_Choice_name)
if((choice_name == 1 and Computer_Choice == 2) or
(choice_name == 2 and Computer_Choice == 1)):
print("paper wins => ", end="")
result = "paper"
elif((choice_name == 1 and Computer_Choice == 3) or
(choice_name == 3 and Computer_Choice == 1)):
print("Rock wins =>", end="")
result = "Rock"
else:
print("scissor wins =>", end="")
result = "scissor"
if result == choice_name:
print("<== User wins ==>")
else:
print("<== Computer wins ==>")
print("Do you want to play again? (Y/N)")
ans = input()
if ans == 'n' or ans == 'N':
break
print("\nThanks for playing")
You are defining a function inside of a while loop. Currently the loop always evaluates to False.
What you want is:
def main():
while True:
# ...
Then you need to actually call main. At the end of the file:
if __name__ == '__main__':
main()

I am working on a rock, paper, scissors program using functions and it is always returning else cases

I am looking for some input on a rock, paper, scissors program that I am making where the statements in the main() and determineWinner that use playerChoice always terminate in the else: case. Each trial will output the player chooses scissors and that the game is tied. I am not sure where I went wrong here as I've printed the input to confirm it is correct before sending to it to the other functions. I cannot figure what pare of the above to function is causing the problem, if anyone could point me in the right direction here I would be grateful.
Here is the code I have so far:
import random
# define main function
def main():
# initialize playAgain to start game, set stats to 0
playAgain = 'y'
numberTied = 0
numberPlayerWon = 0
numberComputerWon = 0
print("Let's play a game of rock, paper, scissors.")
# loop back to play again if user confirms
while playAgain == 'y' or playAgain == 'Y':
computerChoice = processComputerChoice()
playerChoice = processPlayerChoice()
# display computer choice
if computerChoice == 1:
print('The computer chooses rock.')
elif computerChoice == 2:
print('The computer chooses paper.')
else:
print('The computer chooses scissors.')
# display player choice
if playerChoice == 1:
print('You choose rock.')
elif playerChoice == 2:
print('You choose paper.')
else:
print ('You choose scissors.')
# assign who won to result and add total wins/ties to accumulator
result = determineWinner(playerChoice, computerChoice)
if result == 'computer':
numberComputerWon += 1
elif result == 'player':
numberPlayerWon += 1
else:
numberTied += 1
# ask player if they would like to play again
print('')
print
playAgain = input('Do you want to play again? (Enter y or Y to start another game)')
print('')
else:
# print accumulated wins and ties for computer and player
print('There were', numberTied, 'tie games played.')
print('The computer won', numberComputerWon, 'game(s).')
print('The player won', numberPlayerWon, 'game(s).')
print('')
# define computer choice function
def processComputerChoice():
# randomly select an option for the computer to play
randomNumber = random.randint(1,3)
print(randomNumber)
return randomNumber
# define player choice function
def processPlayerChoice():
choice = int(input(('What is your choice? Enter 1 for rock, 2 for paper, or 3 for scissors. ')))
print (choice)
# throw error if player makes invalid choice
while choice != 1 and choice != 2 and choice != 3:
print('ERROR: please input a valid choice of 1, 2, or 3')
choice = int(input('Please enter a correct choice: '))
return choice
# definition for the function to determine the winner
def determineWinner(playerChoice, computerChoice):
# determine player choice and compare to computer choice to determine the winner
if computerChoice == 1:
if playerChoice == 2:
print('Paper covers rock. You are victorious!')
winner = 'player'
elif playerChoice == 3:
print('Rock bashes scissors. The computer is victorious!')
winner = 'computer'
else:
print('The game is tied. Try again 1')
winner = 'tied'
if computerChoice == 2:
if playerChoice == 1:
print('Paper covers rock. The computer is victorious!')
winner = 'computer'
elif playerChoice == 3:
print('Scissors slice paper. You are victorious!')
winner = 'player'
else:
print('The game is tied. Try again 2')
winner = 'tied'
if computerChoice == 3:
if playerChoice == 1:
print('Rock bashes scissors. You are victorious!')
winner = 'player'
elif playerChoice == 2:
print('Scissors slice paper. The computer is victorious!')
winner = 'computer'
else:
print('The game is tied. Try again 3')
winner = 'tied'
return winner
main()
input("Press Enter to continue")
The return statement of your function processPlayerChoice has incorrect indentation. It should be out of while loop (unindent it one level)
At the moment, if player enters correct choice your function will return None.
If user enters incorrect choice, it will enter the while loop and will return whatever the second input from user is.
def processPlayerChoice():
choice = int(input(('What is your choice? Enter 1 for rock, 2 for paper, or 3 for scissors. ')))
print (choice)
# throw error if player makes invalid choice
while choice != 1 and choice != 2 and choice != 3:
print('ERROR: please input a valid choice of 1, 2, or 3')
choice = int(input('Please enter a correct choice: '))
return choice
Make sure to align your return statements with the function body. Currently in both processPlayerChoice and determineWinner they are aligned with the conditional loops, and thus will not be reached every time.

how to use an if else statement in another while loop

I am new to coding. I want to try writing a simple rock paper scissors game. But I can't figure out how to end the game.
In the end of this program if the user input is wrong I want to go to the end variable again. I tried with the commented lines but its not working.
player1 = input("What is player 1's name ? ")
player2 = input("What is player 2's name ? ")
player1 = player1.title()
player2 = player2.title()
while True:
print(player1 + " What do you choose ? rock / paper / scissors : ")
a = input()
print(player2 + " What do you choose ? rock / paper / scissors : ")
b = input()
if a == "rock" and b == "scissors" :
print(player1, "won !!!")
elif a == "scissors" and b == "rock":
print(player2, "won !!!")
elif a == "paper" and b == "rock":
print(player1, "won !!!")
elif a == "rock" and b == "paper":
print(player2, "won !!!")
elif a == "scissors" and b == "paper":
print(player1, "won !!!")
elif a == "paper" and b == "scissors":
print(player2, "won !!!")
elif a == b:
print("Its a tie :-(")
elif a or b != "rock" or "paper" or "scissors":
print("Wrong input, Try again")
end = input("Do you want to play again ? yes/no ") == "yes"
if input == "yes":
continue
else:
print('''
GAME OVER''')
break
# elif input != "yes" or "no":
# print("Wrong input, Try again. yes or no ?")
I expect it to end game if the input is "no" and restart the game if input is "yes" if the input is not correct I want the prompt to appear again.
Your code has a few issues which need some addressing, and a few places where it can be streamlined. I have made a few changes to your program as well as added a few comments explaining the changes.
player1 = input("What is player 1's name ? ").title() #This uses chaining to streamline code
player2 = input("What is player 2's name ? ").title() #Same as above
while True:
a = input(player1 + " What do you choose ? rock / paper / scissors : ") #no need to use a separate print statement
b = input(player2 + " What do you choose ? rock / paper / scissors : ")
valid_entries = ["rock", "paper", "scissors"] #To check for valid inputs
if (a not in valid_entries) or (b not in valid_entries):
print("Wrong input, try again")
continue
a_number = valid_entries.index(a) #Converting it to numbers for easier comparison
b_number = valid_entries.index(b)
if(a_number == b_number):
print("Its a tie :-(")
else:
a_wins = ((a_number > b_number or (b_number == 2 and a_number == 0)) and not (a_number == 2 and b_number == 0)) #uses some number comparisons to see who wins instead of multiple if/elif checks
if(a_wins):
print(player1, "won !!!")
else:
print(player2, "won !!!")
end = input("Do you want to play again ? yes/no ")
while (end !="yes") and (end != "no"):
print("invalid input, try again")
end = input("Do you want to play again ? yes/no ")
if end == "yes":
continue
else:
print("GAME OVER")
break
These changes also make the check by using another while loop to see if the input to restart the game was valid or not
*Note that I have not tested these changes and some edits may need to be be made
Just check the value of end
if end is True:
continue
else:
break
Since, you have set the value of end as a boolean by comparing the input() to "yes", it will say whether the user wants to end the game?
Also, you are not initializing the input variable, and the last elif condition will always be true as mentioned in the comment.
Well you can simplify your code using a list and then simplify your if tests. You can check the order of the options and based on it make a decision. You can also make the tests standard to minimize the number of if statements. This my suggestion to improve your code. I hope it helps:
# get playe names
player1 = input("What is player 1's name ? ")
player2 = input("What is player 2's name ? ")
player1 = player1.title()
player2 = player2.title()
# init vars
options = ["rock", "paper", "scissors"]
players = [player1, player2]
# start game
while True:
a = input(player1 + " What do you choose ? rock / paper / scissors : ")
b = input(player2 + " What do you choose ? rock / paper / scissors : ")
# check if inputs are correct
while (a not in options or b not in options):
print("Wrong input, Try again")
a = input(player1 + " What do you choose ? rock / paper / scissors : ")
b = input(player2 + " What do you choose ? rock / paper / scissors : ")
# check who won
if abs(options.index(a) - options.index(b)) == 1:
print(players[1*int(options.index(a) > options.index(b))], "won !!!")
elif abs(options.index(b) - options.index(a)) > 1:
print(players[1*int(options.index(a) > options.index(b))], "won !!!")
elif a == b:
print("Its a tie :-(")
# continue or drop game
end = input("Do you want to play again ? yes/no ")
if end == "yes":
continue
else:
print('''
GAME OVER''')
break

A local or global name can not be found error [duplicate]

This question already has answers here:
Python NameError from contents of a variable
(2 answers)
Closed 8 years ago.
I'm trying to make a simple rock paper scissors game, and I get an error with in the line, guess = input. It says I need to define the function or variable before I use it in this way and I am unsure of how I can do that. This is using Python/JES programming
#import random module
import random
#main function
def main():
#intro message
print("Let's play 'Rock, Paper, Scissors'!")
#call the user's guess function
number = user_guess()
#call the computer's number function
num = computer_number()
#call the results function
results(num, number)
#computer_number function
def computer_number():
#get a random number in the range of 1 through 3
num = random.randrange(1,4)
#if/elif statement
if num == 1:
print("Computer chooses rock")
elif num == 2:
print("Computer chooses paper")
elif num == 3:
print("Computer chooses scissors")
#return the number
return num
#user_guess function
def user_guess():
guess = input ("Choose 'rock', 'paper', or 'scissors' by typing that word. ")
#while guess == 'paper' or guess == 'rock' or guess == 'scissors':
if is_valid_guess(guess):
#if/elif statement
#assign 1 to rock
if guess == 'rock':
number = 1
#assign 2 to paper
elif guess == 'paper':
number = 2
#assign 3 to scissors
elif guess == 'scissors':
number = 3
return number
else:
print('That response is invalid.')
return user_guess()
def is_valid_guess(guess):
if guess == 'rock' or guess == 'paper' or guess == 'scissors':
status = True
else:
status = False
return status
def restart():
answer = input("Would you like to play again? Enter 'y' for yes or \
'n' for no: ")
#if/elif statement
if answer == 'y':
main()
elif answer == 'n':
print("Goodbye!")
else:
print("Please enter only 'y' or 'n'!")
#call restart
restart()
#results function
def results(num, number):
#find the difference in the two numbers
difference = num - number
#if/elif statement
if difference == 0:
print("TIE!")
#call restart
restart()
elif difference % 3 == 1:
print("I'm sorry! You lost :(")
#call restart
restart()
elif difference % 3 == 2:
print("Congratulations! You won :)")
#call restart
restart()
main()
Using raw_input instead of input seems to solve the problem.
guess = raw_input ("Choose 'rock', 'paper', or 'scissors' by typing that word. ")
and also in
answer = raw_input("Would you like to play again? Enter 'y' for yes or 'n' for no: ")
I'm using Python 2.7.x

Categories