Unable to get if function to run based on outputs - python

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.

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]

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.

getting Python 3.9 to recognize parameters and act accordingly (Interactive storytelling)

I'll try to keep it short and sweet.
I'm writing an interactive story that changes based on the "roll" of a d20 dice. I've managed to figure out getting started, but I've hit a point where I don't think Python is actually listening to the parameters I'm giving it, because it kind of just does whatever.
Essentially, here's what's supposed to happen:
Player agrees that they want to play the game -> Player Rolls dice -> Game uses the randomly rolled number to determine which start that the player will have.
What's currently happening is, all goes well until it's supposed to spit out the start that the player has. It doesn't seem to actually decide based on my parameters. For example, you're supposed to have the "human" start if the player rolls 5 or less, and an "elf" start for anything between 6 and 18. Here's what happened yesterday:
venv\Scripts\python.exe C:/Users/drago/PycharmProjects/D20/venv/main.py
Hello! Would you like to go on an adventure? y/n >> y
Great! Roll the dice.
Press R to roll the D20.
You rolled a 15!
You start as a human.
As a human, you don't have any special characteristics except your ability to learn.
The related code is below:
def NewGame():
inp = input("Hello! Would you like to go on an adventure? y/n >> ")
if inp == "y" or inp == "yes":
print("Great! Roll the dice.")
input("Press R to roll the D20.")
print("You rolled a " + str(RollD20()) + "!")
PostGen()
else:
input("Okay, bye! Press any key to exit.")
sys.exit()
def PostGen():
if RollD20() <= 5:
print("You start as a human.")
PostStartHum()
elif RollD20() >= 6:
print("You start as an elf.")
PostStartElf()
elif RollD20() >= 19:
print("You lucked out, and can start as a demigod!")
PostStartDemi()
def RollD20():
n = random.randint(1, 20)
return n
def PostStartHum():
print("As a human, you don't have any special characteristics except your ability to learn.")
def PostStartElf():
print("As an elf, you have a high intelligence and a deep respect for tradition.")
def PostStartDemi():
print("As a demigod, you are the hand of the gods themselves; raw power incarnated in a human form...")
print("However, even mighty decendants of gods have a weakness. Be careful."
Thanks for all your help.
Turn your PostGen function into the following:
def PostGen(rollValue):
if rollValue <= 5:
print("You start as a human.")
PostStartHum()
elif rollValue >= 6:
print("You start as an elf.")
PostStartElf()
elif rollValue >= 19:
print("You lucked out, and can start as a demigod!")
PostStartDemi()
Change your NewGame function to the following:
def NewGame():
inp = input("Hello! Would you like to go on an adventure? y/n >> ")
if inp == "y" or inp == "yes":
print("Great! Roll the dice.")
input("Press R to roll the D20.")
rollValue = RollD20()
print("You rolled a " + str(rollValue) + "!")
PostGen(rollValue)
else:
input("Okay, bye! Press any key to exit.")
sys.exit()
You are generating a new random number every time you call RollD20(). You need to store the value somewhere and reuse it for the game session.
Each time you call RollD20, you get a new random number. So if you want to use the same random number in multiple ifs, you need to tuck that value into another variable.
def NewGame():
inp = input("Hello! Would you like to go on an adventure? y/n >> ")
if inp == "y" or inp == "yes":
print("Great! Roll the dice.")
input("Press R to roll the D20.")
result = RollD20()
print("You rolled a " + str(result) + "!")
PostGen(result)
else:
input("Okay, bye! Press any key to exit.")
sys.exit()
And from there you change PostGen() to accept the result:
def PostGen(result):
if result <= 5:
print("You start as a human.")
PostStartHum()
elif result >= 6:
print("You start as an elf.")
PostStartElf()
elif result >= 19:
print("You lucked out, and can start as a demigod!")
PostStartDemi()

Python - properly returning value for rock, paper, scissors

I am trying to write a Python script where the user can select a choice for 'r', 'p', or 's' and the script will generate the outcome of the Rock, Paper, Scissors game based on the returned value. This is what I have so far:
from random import choice
import sys
# Input name
meetname = input("Nice to meet you! What's your name? \n")
print(' \n')
# Game instructions
rpsthink = 'Well, ' + meetname + ", how about we play a game of Rock, Paper, Scissors?"
print(rpsthink)
print('\n')
#Ask user for choice of rock, paper, scissors
try:
user_move = str(input("Enter 'r' for rock, 'p' for paper, or 's' for scissors. The system will randomly select a choice, and the result of the game will be displayed to you. You can enter 'Q' to quit the game at any time. \n"))
except ValueError:
print("Please make sure your input is 'r', 'p', 's', or 'Q'!")
sys.exit()
print('\n')
if user_move =='Q':
print('Sorry to see you go - hope you had fun playing!')
sys.exit()
# Generate a random computer choice
def computer_rps() -> str:
#Computer will randomly select from rock, paper, scissors:
computermove: str = choice(['r','p','s'])
return computermove
def gameresult(user_move, computermove):
# Return value based on comparison of user and computer moves
# User wins
if (user_move == 'r' and computermove == 's') or (user_move == 'p' and computermove == 'r') or (user_move == 's' and computermove =='p'):
return 1
# User loses
if (user_move == 'r' and computermove == 'p') or (user_move == 's' and computermove == 'r') or (user_move == 'p' and computermove == 's'):
return -1
# Tie game
if user_move == computermove:
return 0
#Notification of game result based on returned function value
if int(gameresult(user_move, computermove)) == -1:
print("The computer made a choice of ", computermove)
print("Looks like the computer won this time...don't let that deter you - let's have another round for a shot at victory!")
if int(gameresult(user_move, computermove)) == 1:
print("The computer made a choice of ", computermove)
print('Looks like you won! Excellent choice! But how many times can you make the winning decision...?')
if int(gameresult(user_move, computermove)) == 0:
print("The computer made a choice of ", computermove)
print("Looks like it's a tie game - how about another round to settle the score?")
sys.exit()
However, I get an error of the name 'computermove' not being defined for the line if int(gameresult(user_move, computermove)) == -1. Do I need to set computermove as a global variable so that the comparison of user and computer moves can be properly done?
computermove is undefined because it's not available in the scope you're accessing it and you haven't created it anywhere else. You need to create a variable that receives the value returned by the function that generates the computer move.
computermove = computer_rps() # Add this line here and it should do it
#Notification of game result based on returned function value
if int(gameresult(user_move, computermove)) == -1:
print("The computer made a choice of ", computermove)
print("Looks like the computer won this time...don't let that deter you - let's have another round for a shot at victory!")
if int(gameresult(user_move, computermove)) == 1:
print("The computer made a choice of ", computermove)
print('Looks like you won! Excellent choice! But how many times can you make the winning decision...?')
if int(gameresult(user_move, computermove)) == 0:
print("The computer made a choice of ", computermove)
print("Looks like it's a tie game - how about another round to settle the score?")
sys.exit()
The error is pretty explicative. It's telling you that the variable computermove is not defined on the line where you are trying to use it.
You need to define said variable to the return value of the function computer_rps before calling the gameresult function.
Such as:
computermove = computer_rps()
if int(gameresult(user_move, computermove...

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