If user inputs letter output should be word - python

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]

Related

Repeating a while loop Python

so i am trying to make this rock paper scissors game, i want to make a while loop that terminates when user input is "quit" but it doesnt seem to work, it either fails to repeat or continues indefinitly, any idea why?
import random #this module is used to select randomly one of the three values, rock paper or scissors
words = ["rock", "paper", "scissors"]
badwords = ["fuck","shit","bitch", "cunt", "fuck off", "piss off", "nigger","motherfucker"]
def check_word_input(word, word_list, bad_word_list=None):
"""
this function compares the word, in this case user input against a wordlist to see if input is correct, by checking if
words is present in a wordlist. if not, user is notified that his input is not valid.
optionally checks the word against a list of bad words and gives feedback
arguments:
word -- word you want to check
word_list -- list of words you want your word to compare against
keyword arguments:
bad_word_list -- list of words that give custom feedback to the user. (default None)
"""
if word in word_list:
return word
elif bad_word_list and word in bad_word_list:
print("How dare you?!")
else:
print("invalid input, (check for typos)")
def game():
computer_wins = 0
player_wins = 0
feedback = input("Welcome to my rock, paper scissors game, type 'rock', 'paper' or 'scissors': ")
checked_feedback = " "
while checked_feedback != "quit":
checked_feedback = check_word_input(feedback, words, badwords)
computer = random.choice(["rock","paper","scissors"])
if checked_feedback == computer:
print("its a tie!")
if (checked_feedback == 'rock' and computer == 'scissors') or (checked_feedback == 'paper' and computer == 'rock') or (checked_feedback == 'scissors' and computer == 'paper'):
player_wins += 1
print("you won!, your current score is now %d" %player_wins)
else:
computer_wins += 1
print("you lost!, opponents current score is now %d" %computer_wins)
print("type 'quit' to quit")
checked_feedback = check_word_input(feedback, words, badwords)
break
print("computer score: ", computer_wins)
print("player score: ", player_wins)
you need to change
print("type 'quit' to quit")
to
feedback = input("type 'quit' to quit")
Also I would change
feedback = input("Welcome to my rock, paper scissors game, type 'rock', 'paper' or 'scissors': ")
to
print("Welcome to my rock, paper scissors game")
then at the first line of the loop should have
feedback = input("Rock, paper or scissors")

Unable to get if function to run based on outputs

absolute beginner here and it's driving me insane already. Basically, the following is a back and forth game with the PC - if you both pick steal you both loose, if you pick deal and PC picks steal you lose so on and so forth. I have got the code to a point where it can out put the results base on what I put in and what the PC randomly selects however I cannot get the if statement to detect the results and work out if you win or lose.
selection = 'Steal Deal or Quit'
human = input('Steal, Deal or Quit [s|d|q]?:')
print(" ")
if human == 'steal':
print('You chose: ' + selection.split(" ")[0])
if human == 's':
print('You chose: ' + selection.split(" ")[0])
if human == 'deal':
print('You chose: ' + selection.split(" ")[1])
if human == 'd':
print('You chose: ' + selection.split(" ")[1])
if human == 'quit':
print('You chose: ' + selection.split(" ")[3])
if human == 'q':
print('You chose: ' + selection.split(" ")[3])
#Computer input
sd = ["Steal", "Deal"]
computer = print('Comp chose: ' + random.choice(sd))
if human == sd:
print('Draw!')
# human is a STRING !!!
human = input(...)
# sd is a LIST !!!
sd = ["Steal", "Deal"]
if human == sd:
print('Draw!')
You are comparing very different things. There's no way the comparison will return a True result.
You are likely to want to compare the computer's choise with human's instead. You should store the computer's choice in a variable before using it for printing, and compare this variable to human afterwards.
computer_choice = random.choice(sd)
print('Comp chose: ' + computer_choice)
if human == computer_choice:
print('Draw!')
Also, the value of human remains whatever was typed by the user. Your program should change its value to "Steal", "Deal" accordingly before comparison.

How to use a function for a computer's choice [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
I am at the final steps of creating a rock, paper, scissors game for class. In our brief we must include a function for the computer's choice.
I created the function but some errors have come up where it says that 'choices' has been undefined. I am new to using functions so I am not entirely sure why these errors have come up as I thought I already defined choices.
This is the piece of code which has the error:
def aiChoice():
choices = ['r', 'p', 's']
com_choice = random.choice(choices)
# the possible choices
return choices
return com_choice
for i in range(games):
print(f"Match {i+1}, trust your instinct")
while True:
user_play = input("Select r, p, or s: ")
# asks user to play rock, paper or scissors
if user_play in choices: **error here that says undefined name 'choices'**
# checks user input
break
# if valid, breaks the loop
print("Please enter only r, p, or s")
# otherwise asks again
com_choice = random.choice(choices) **same error here for 'choices'**
# assigns the computer choice
print(com_choice)
# prints a random item from the list as the computer's choice
if user_play == com_choice:
print('Draw!')
draw = draw + 1
# if the user plays the same move as the computer, one point goes to draw
You need choices outside of the aiChoice() function.
See:
import random
win = 0
loss = 0
draw = 0
# the possible choices
choices = ['r', 'p', 's']
def aiChoice():
com_choice = random.choice(choices)
return com_choice
while True:
name = input("Enter your name: ")
# asks user for name
if name.isalpha():
break
else:
print("Please enter characters A-Z only")
# makes sure user only enters letters
# taken from Stack Overflow
# asks user how many games they want to play
while True:
games = int(input(name + ', enter in number of plays between 1 and 7: '))
if games <= 7:
break
else:
print('1 to 7 only.')
# makes sure user input doesn't exceed seven plays
for i in range(games):
print(f"Match {i+1}, trust your instinct")
while True:
user_play = input("Select r, p, or s: ")
# asks user to play rock, paper or scissors
if user_play in choices:
# checks user input
break
# if valid, breaks the loop
print("Please enter only r, p, or s")
# otherwise asks again
com_choice = random.choice(choices)
# assigns the computer choice
print(com_choice)
# prints a random item from the list as the computer's choice
if user_play == com_choice:
print('Draw!')
draw = draw + 1
# if the user plays the same move as the computer, one point goes to draw
elif user_play == 'r' and com_choice == 'p':
print('Paper beats rock.')
print('AI wins!')
loss = loss + 1
# if the user plays rock and computer plays paper, says that the computer won and puts a point in the loss category
elif user_play == 'r' and com_choice == 's':
print('Rock beats scissors.')
print(name + ' wins!')
win = win + 1
# if the user plays rock and computer plays scissors, says that the person won and puts a point in the win category
elif user_play == 'p' and com_choice == 'r':
print('Paper beats rock.')
print(name + ' wins!')
win = win + 1
# if the user plays paper and computer plays rock, says that the person won and puts a point in the win category
elif user_play == 'p' and com_choice == 's':
print('Scissors beats paper.')
print('AI wins!')
loss = loss + 1
# if the user playspaper and scissors plays paper, says that the computer won and puts a point in the loss category
elif user_play == 's' and com_choice == 'r':
print('Rock beats scissors.')
print('AI wins!')
loss = loss + 1
# if the user plays scissors and computer plays rock, says that the computer won and puts a point in the loss category
elif user_play == 's' and com_choice == 'p':
print('Scissors beats paper.')
print(name + ' wins!')
win = win + 1
# if the user plays scissors and computer plays paper, says that the person won and puts a point in the win category
print(name + "'s final score:")
print('Wins: ' + str(win))
print('Loss: ' + str(loss))
print('Draws: ' + str(draw))
# prints the final score after all games are finished.
At the moment you're also not calling the aiChoice() function.
Do this instead:
import random
win = 0
loss = 0
draw = 0
# the possible choices
choices = ['r', 'p', 's']
def aiChoice():
com_choice = random.choice(choices)
return com_choice
while True:
name = input("Enter your name: ")
# asks user for name
if name.isalpha():
break
else:
print("Please enter characters A-Z only")
# makes sure user only enters letters
# taken from Stack Overflow
# asks user how many games they want to play
while True:
games = int(input(name + ', enter in number of plays between 1 and 7: '))
if games <= 7:
break
else:
print('1 to 7 only.')
# makes sure user input doesn't exceed seven plays
for i in range(games):
print(f"Match {i+1}, trust your instinct")
while True:
user_play = input("Select r, p, or s: ")
# asks user to play rock, paper or scissors
if user_play in choices:
# checks user input
break
# if valid, breaks the loop
print("Please enter only r, p, or s")
# otherwise asks again
com_choice = aiChoice()
# assigns the computer choice
print(com_choice)
# prints a random item from the list as the computer's choice
if user_play == com_choice:
print('Draw!')
draw = draw + 1
# if the user plays the same move as the computer, one point goes to draw
elif user_play == 'r' and com_choice == 'p':
print('Paper beats rock.')
print('AI wins!')
loss = loss + 1
# if the user plays rock and computer plays paper, says that the computer won and puts a point in the loss category
elif user_play == 'r' and com_choice == 's':
print('Rock beats scissors.')
print(name + ' wins!')
win = win + 1
# if the user plays rock and computer plays scissors, says that the person won and puts a point in the win category
elif user_play == 'p' and com_choice == 'r':
print('Paper beats rock.')
print(name + ' wins!')
win = win + 1
# if the user plays paper and computer plays rock, says that the person won and puts a point in the win category
elif user_play == 'p' and com_choice == 's':
print('Scissors beats paper.')
print('AI wins!')
loss = loss + 1
# if the user playspaper and scissors plays paper, says that the computer won and puts a point in the loss category
elif user_play == 's' and com_choice == 'r':
print('Rock beats scissors.')
print('AI wins!')
loss = loss + 1
# if the user plays scissors and computer plays rock, says that the computer won and puts a point in the loss category
elif user_play == 's' and com_choice == 'p':
print('Scissors beats paper.')
print(name + ' wins!')
win = win + 1
# if the user plays scissors and computer plays paper, says that the person won and puts a point in the win category
print(name + "'s final score:")
print('Wins: ' + str(win))
print('Loss: ' + str(loss))
print('Draws: ' + str(draw))
# prints the final score after all games are finished.

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

Rock paper scissors scoring problems [closed]

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.

Categories