Whenever I say "no" to the "would you like to attempt the puzzle?" thing, nothing comes up. I even just put a print ("test") after all of that code once and it didn't execute the test.
puzzle1 = raw_input ("The cave has a small golden inscription on the door with a dial for imputting numbers. A puzzle! Would you like to attempt the puzzle?")
#Puzzle 1
if path1 == "2":
while breakhold2 == 0:
if path1 == "2":
if puzzle1.lower in ["Yes", "Ye", "Y", "y", "ye", "yes"]:
print ("You press the button on the door. A small dial turns quickly and picks a random number between 1 and 50. Now you must guess the number being told to go 'higher' or 'lower'. You have only 5 tries to guess the random number.")
if path1 == "2":
while breakhold2 == 0:
if path1 == "2":
if puzzle1.lower in ["Yes", "Ye", "Y", "y", "ye", "yes"]:
from random import randrange
puzzle1number = randrange(1,51)
puzzle1number2 = raw_input ("What is the first guess? You have 5 tries left.")
if int(puzzle1number2) == puzzle1number:
print ("You did it first try! Lucky you!")
if int(puzzle1number2) > puzzle1number:
print ("Lower!")
if int(puzzle1number2) < puzzle1number:
print ("Higher!")
if int(puzzle1number2) == puzzle1number:
breakhold2 += 1
break
else:
puzzle1number3 = raw_input ("What is the second guess? You have 4 tries left.")
if int(puzzle1number3) == puzzle1number:
print ("You did it second try! Great guessing!")
if int(puzzle1number3) < puzzle1number:
print ("Higher!")
if int(puzzle1number3) > puzzle1number:
print ("Lower!")
if int(puzzle1number2) == puzzle1number or int(puzzle1number3) == puzzle1number:
breakhold2 += 1
break
else:
puzzle1number4 = raw_input ("What is the third guess? You have 3 tries left.")
if int(puzzle1number4) == puzzle1number:
print ("You did it third try! Great guessing!")
if int(puzzle1number4) < puzzle1number:
print ("Higher!")
if int(puzzle1number4) > puzzle1number:
print ("Lower!")
if int(puzzle1number4) == puzzle1number or int(puzzle1number4) == puzzle1number:
breakhold2 += 1
break
else:
puzzle1number5 = raw_input ("What is the fourth guess? You have 2 tries left.")
if int(puzzle1number5) == puzzle1number:
print ("You did it fourth try! That came kind of close.")
if int(puzzle1number5) < puzzle1number:
print ("Higher!")
if int(puzzle1number5) > puzzle1number:
print ("Lower!")
if int(puzzle1number5) == puzzle1number or int(puzzle1number5) == puzzle1number:
breakhold2 += 1
break
else:
puzzle1number6 = raw_input ("What is the fifth and final guess? This is your last try!")
if int(puzzle1number6) == puzzle1number:
print ("Finally! Got it on the last go!")
else:
print ("Blast! The small dial clicks and becomes unmovable. Whatever treasure was in there is now locked inside. I wonder why that was a lock?")
breakhold2 += 1
break
if path1 == "2":
while breakhold2 == "0":
if puzzle1.lower in ["No", "no", "n", "N"]:
print ("You decide not to attempt the puzzle.")
breakhold2 += 1
break
puzzle1.lower in ['yes', 'no', 'whatever', ...] will always be False.
Use instead puzzle1.lower() in [....].
Check:
answer = 'Yes'
print(answer.lower)
print(answer.lower in ['yes', 'y'])
versus:
answer = 'Yes'
print(answer.lower())
print(answer.lower() in ['yes', 'y'])
Related
I am trying to make a little guessing game, here's the code
secret_w = "giraffe"
guess= ""
guess_remain = 3
guess_c = 0
guess_limit = 2
outofguesses = False
while guess != secret_w and not(outofguesses):
guess = input("I'm thinking of an animal, try and guess it! ")
guess_c += 1
if guess != secret_w:
print("Incorrect, try again")
guess_remain -= 1
print("You've guessed", guess_c, "times and have", guess_remain, "guesses left!")
if guess_c == 1:
print("Hint 1: It's tall!")
if guess_c == 2:
print("Hint 2: It has spots and a long neck")
if guess_c > guess_limit:
outofguesses = True
if outofguesses:
print("You're out of guesses, better luck next time!")
if guess == secret_w:
print("Well done")
print("You got it on attempt number", guess_c )
If I run it, it works fine, if I guess it wrong 3 times, it ends which is perfect, but if I guess it right the first time, it still says "hint 1: it's tall" which clearly I don't want to happen, and same goes if i guess it correctly on guess 2, it gives me hint 2.
I've tried making true and false statements but nothing seems to work?
Ignore my spaghetti code, I know I have to practice making it shorter and so on.
Use the .lower() method on the input to make sure it is in lowercase so it matches your secret word by using it this way:
guess = input("I'm thinking of an animal, try and guess it! : ").lower()
Notice the .lower() in the end, it automatically makes the user input all lowercase.
Secondly you need to have the if statements nested correctly like so:
if guess != secret_w:
print("Incorrect, try again")
guess_remain -= 1
print("You've guessed", guess_c, "times and have", guess_remain, "guesses left!")
if guess_c == 1 and guess != secret_w:
print("Hint 1: It's tall!")
if guess_c == 2 and guess != secret_w:
print("Hint 2: It has spots and a long neck")
if guess_c > guess_limit:
outofguesses = True
Also we check if it is not the secret word on every try. This works for your solution.
So for clarity, the whole working code would look like this:
secret_w = "giraffe"
guess= ""
guess_remain = 3
guess_c = 0
guess_limit = 2
outofguesses = False
while guess != secret_w and not(outofguesses):
guess = input("I'm thinking of an animal, try and guess it! : ").lower()
guess_c += 1
if guess != secret_w:
print("Incorrect, try again")
guess_remain -= 1
print("You've guessed", guess_c, "times and have", guess_remain, "guesses left!")
if guess_c == 1 and guess != secret_w:
print("Hint 1: It's tall!")
if guess_c == 2 and guess != secret_w:
print("Hint 2: It has spots and a long neck")
if guess_c > guess_limit:
outofguesses = True
if outofguesses:
print("You're out of guesses, better luck next time!")
if guess == secret_w:
print("Well done")
print("You got it on attempt number", guess_c )
Because you increase guess_c by 1 every time the user enters a guess means that even if they get it right it is still being called because guess_c is still being increased.
If you want to stop this you can check if it is correct before you run the conditions for the checks. Also if you want the program to stop after you get it right, add a break to stop the loop.
secret_w = "giraffe"
guess= ""
guess_remain = 3
guess_c = 0
guess_limit = 2
outofguesses = False
while guess != secret_w and not(outofguesses):
guess = input("I'm thinking of an animal, try and guess it! ")
guess_c += 1
if outofguesses:
print("You're out of guesses, better luck next time!")
if guess == secret_w:
print("Well done")
print("You got it on attempt number", guess_c )
break
if guess != secret_w:
print("Incorrect, try again")
guess_remain -= 1
print("You've guessed", guess_c, "times and have", guess_remain, "guesses left!")
if guess_c == 1:
print("Hint 1: It's tall!")
if guess_c == 2:
print("Hint 2: It has spots and a long neck")
if guess_c > guess_limit:
outofguesses = True
And instead of adding a variable you can just break the loop using break which will end a loop.
while True:
break
It must be on nested If condition so that it will not show when you guess right answer. Always compare strings as case-insensitive and break a while loop when condition satisfied. Here is your modified code
secret_w = "giraffe"
guess= ""
guess_remain = 3
guess_c = 0
guess_limit = 2
outofguesses = False
while guess != secret_w and not(outofguesses):
guess = input("I'm thinking of an animal, try and guess it! ")
guess_c += 1
if guess.lower() != secret_w.lower():
print("Incorrect, try again")
guess_remain -= 1
print("You've guessed", guess_c, "times and have", guess_remain, "guesses left!")
if guess_c == 1:
print("Hint 1: It's tall!")
if guess_c == 2:
print("Hint 2: It has spots and a long neck")
if outofguesses:
print("You're out of guesses, better luck next time!")
else:
print("Well done")
print("You got it on attempt number", guess_c )
break
if guess_c > guess_limit:
outofguesses = True
def random():
x_val = randint(1,100)
limit = []
limit2 = len(limit)
while True:
try:
roll = int(raw_input("Please pick a number: "))
except ValueError:
print "Please input numbers only"
continue
if limit2 <= 5:
if roll > 100 or roll < 1:
print "Exceed Limited Guess"
continue
elif roll < x_val:
limit.append(1)
sleep(1)
print "Your guess is lower!"
continue
elif roll > x_val:
limit.append(1)
sleep(1)
print "Your guess is higher!"
continue
elif roll == x_val:
print limit2
return "You guessed correct! You win!"
break
else:
print "Incorrect Input"
continue
elif limit2 > 5:
return "You guessed over 5 times. You lose, sucker..."
break
elif limit2 == 4:
print "Last guess!"
continue
print "Welcome to my world! You will have to pick a correct number from 1 to 100!
If you can do it within 5 times you win! Otherwise you suck!"
while True:
try:
start = raw_input("Start Rolling? Yes or No: ").lower()
except ValueError:
print "Answer Yes or no"
continue
if start == "y" or start == "yes" or start == "ye":
user2 = random()
print user2
elif start == "n" or start == "no" or start == "noo":
print "Ready when you are"
continue
else:
print "Answer Yes or No"
continue
Hi, I am working on a guessing game from 1-100 that I built from ground up by myself and doing research, my original code is not even close to this.
Now, I am stuck on the last part I cannot use the list to limit the input in while loop. I want to stop the game after 5 guesses. However every time it always keep going and once it win it printed out "0" for limit2 variable.
Thank you
The main problem with your code is that you never update the "counter" of the attempted tries made by the user. You initialize it at the beginning (through limit2 = len(limit)), but you never update that value, therefore causing an endless loop.
You simply need to perform the check on len(limit) instead of on limit2.
Working solution can be found below. I took the liberty of commenting limit2 (as it is not needed anymore), improving the indentation, adding two imports, replacing sleep with time.sleep, and fixing the number of checks to perform (if you are aiming at 5 maximum tries, len(limit) needs to be less than 5).
from random import randint
import time
def random():
x_val = randint(1,100)
limit = []
# limit2 = len(limit)
while True:
try:
roll = int(raw_input("Please pick a number: "))
except ValueError:
print "Please input numbers only"
continue
if len(limit) < 5:
if roll > 100 or roll < 1:
print "Exceed Limited Guess"
continue
elif roll < x_val:
limit.append(1)
time.sleep(1)
print "Your guess is lower!"
continue
elif roll > x_val:
limit.append(1)
time.sleep(1)
print "Your guess is higher!"
continue
elif roll == x_val:
print len(limit)
return "You guessed correct! You win!"
break
else:
print "Incorrect Input"
continue
elif len(limit) >= 5:
return "You guessed over 5 times. You lose, sucker..."
break
print "Welcome to my world! You will have to pick a correct number from 1 to 100! If you can do it within 5 times you win! Otherwise you suck!"
while True:
try:
start = raw_input("Start Rolling? Yes or No: ").lower()
except ValueError:
print "Answer Yes or no"
continue
if start == "y" or start == "yes" or start == "ye":
user2 = random()
print user2
elif start == "n" or start == "no" or start == "noo":
print "Ready when you are"
continue
else:
print "Answer Yes or No"
continue
Worthy of note is that -- among several other things that should be fixed in your code -- you should avoid calling a function random, since it is already a name used by a very common module.
import random
def start():
print "\t\t***-- Please enter Y for Yes and N for No --***"
answer = raw_input("\t\t Would you like to play a Guessing Game?: ")
if answer == "Y"
or answer == "y":
game()
elif answer == "N"
or answer == "n":
end()
def end():
print("\t\t\t **Goodbye** ")
raw_input("\t\t\t**Press ENTER to Exit**")
def game():
print "\t\t\t Welcome to Williams Guessing Game"
user_name = raw_input("\n\t\t Please enter your name: ")
print "\n", user_name, "I am thinking of a number between 1 and 20"
print "You have 5 attempts at getting it right"
attempt = 0
number = random.randint(1, 20)
while attempt < 5:
guess = input("\t\nPlease enter a number: ")
attempt = attempt + 1
answer = attempt
if guess < number:
print "\nSorry", user_name, "your guess was too low"
print "You have ", 5 - attempt, " attempts left\n"
elif guess > number:
print "\nSorry ", user_name, " your guess was too high"
print "You have ", 5 - attempt, " attempts left\n"
elif guess == number:
print "\n\t\t Yay, you selected my lucky number. Congratulations"
print "\t\t\tYou guessed it in", attempt, "number of attempts!\n"
answer = raw_input("\n\t\t\t\tTry again? Y/N?: ")
if answer == "Y"
or answer == "y":
game()
elif answer == "N"
or answer == "n":
end()
start()
If you want the computer to guess your number, you could use a function like this:
import random
my_number = int(raw_input("Please enter a number between 1 and 20: "))
guesses = []
def make_guess():
guess = random.randint(1, 20)
while guess in guesses:
guess = random.randint(1, 20)
guesses.append(guess)
return guess
while True:
guess = make_guess()
print(guess)
if guess == my_number:
print("The computer wins!")
break
else:
print(guesses)
It's just a quick-and-dirty example, but I hope it gives you the idea. This way, the computer gets unlimited guesses, but you could easily change the while loop to limit its number of guesses.
Whenever an output should result in a change of shield, the program just says 'You have 5 shields' followed by 'You Win'. I think I might have made a mistake when passing over the variables from one function to the next. Thank you in advance for the help!
def main():
while TakeTurn(word,shield) == False:
if shield == 1:
word1 = "shield"
else:
word1 = "shields"
print ("You have", shield, word1,)
if shield < 1:
print ("Sorry! You ran out of shields! You lose!")
else:
print ("You win")
#This function is the actual 'game' and will deterine what happens to the character
def TakeTurn(word1,shield1):
time.sleep(1.5)
#This means that when the user reaches 0 shields, they lose.
if shield1 < 1:
return True
#Whatever the user inputs will not actually affect the outcome
print ("You have reached", word1 ,"junction.\nDo you want to turn left (L), turn right (R) or go straight ahead(S)?")
turning = input()
#This is a simple instruction that means that the first time you come to a junction, it will say 'a junction' but the second time it will say 'another junction'
word1 = "another"
#This 'if' statement means that the program will only continue if the user has inputed the letters 'L', 'R' or 'S'
elif turning not in ["L","R","S","l","r","s"] :
time.sleep (0.7)
print ("Sorry, I didn't understand that")
TakeTurn()
else:
choice = randint (1,10)
#This is just going to display a random message which will affect the outcome
time.sleep (1)
if choice == 1:
print ("You have found the exit!")
return True
elif choice == 2:
print ("You have found a shield!")
time.sleep(1)
shield1 = shield1 +1
return False
elif choice == 3:
print ("You have found two shields!")
time.sleep(1)
shield1 = shield1 +2
return False
elif choice == 4:
print ("You have found three shields!")
time.sleep(1)
shield1 = shield1 +3
return False
elif choice == 5:
print ("A fairy has jumped into your pants!")
time.sleep(2)
print ("You lose two shields")
time.sleep(1)
shield1 = shield1 -2
return False
elif choice == 6:
treasurechest(shield1)
return False
elif choice == 7:
print ("You have tripped over a log!")
time.sleep(2)
print ("You lose a shield")
time.sleep(1)
shield1 = shield1 -1
return False
elif choice == 8:
print ("An angry teenager is staring at you in the eye.")
time.sleep(2.5)
print ("He uses laziness...")
time.sleep(1.5)
print ("It's super effective!")
time.sleep(1)
print ("You lose three shields")
time.sleep(1)
shield1 = shield1 -3
return False
elif choice == 9:
print ("You have encountered an ogre...")
time.sleep(1.5)
print ("He bashes you over the head with a steel bar")
time.sleep(2)
print ("You lose two shields")
time.sleep(1)
shield1 = shield1 -2
return False
else:
print ("A goblin aproaches and says the following:")
time.sleep(2)
goblin(shield1)
return False
You should refactor main and TakeTurn to make shield and word explicit arguments and return values. This prevents relying on scope for access to variables, without having to use global (which is usually a bad sign):
def main(shield, word):
while True:
shield, word, finished = TakeTurn(shield, word)
if finished:
break
word1 = "shield" if shield == 1 else "shields"
print ("You have {0} {1}".format(shield, word1))
if shield < 1:
print ("Sorry! You ran out of shields! You lose!")
else:
print ("You win")
And have TakeTurn return multiple values accordingly, e.g.:
elif choice == 3:
print ("You have found two shields!")
time.sleep(1)
shield1 = shield1 + 2
return shield1, word1, False
You could make things neater by making choices a list of dictionaries and picking randomly from it:
choices = [{"texts": [("You have found two shields!", 1)],
"shield change": 2, "return": False},
{"texts": [("You have encountered an ogre...", 1.5),
("He bashes you over the head with a steel bar", 2),
("You lose two shields", 1)],
"shield change": -2, "return": False},
...]
Then your main section, instead of all the elifs, becomes simply:
choice = random.choice(choices)
for text, sleep_time in choice['texts']:
print(text)
time.sleep(sleep_time)
shield1 += choice['shield change']
return shield1, word1, choice['return']
I'm writing a blackjack game for my class and I cannot seem to figure out what is wrong with the code at all, maybe I'm just staring at it too long but any help would be appreciated
def payout(betAmount):
global option1
if option1 == "1":
betAmount*1.5
return int(betAmount)
elif option1 == "2":
betAmount*=1.25
return int(betAmount)
elif option1 == "3":
betAmount*=1.2
return int(betAmount)
followed by this:
winning=payout(bet)
playerPool+=winning
sorry about that, the full code is:
import random, pickle
option1=None
def payoutRule():
global option1
pick=None
while pick != "1" or "2" or "3":
pick=input("""
What is the house payout you want to play with?
1- 3:2 (1.5X)
2- 5:4 (1.25X)
3- 6:5 (1.2X)\n
""")
if pick == "1":
option1=1
break
elif pick == "2":
option1=2
break
elif pick == "3":
option1=3
break
else:
print("That is not a valid option!\n")
def payout(betAmount):
global option1
if option1 == "1":
betAmount*1.5
return int(betAmount)
elif option1 == "2":
betAmount*=1.25
return int(betAmount)
elif option1 == "3":
betAmount*=1.2
return int(betAmount)
def hitDeck():
CARDS=(2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11)
drawCard=random.choice(CARDS)
return drawCard
def aceCounter(hand):
aces=hand.count(11)
total=sum(hand)
if total > 21 and aces > 0:
while aces > 0 and total > 21:
total-=10
aces-=1
return total
def main():
print("\t\tWelcome to the Blackjack Table!")
payoutRule()
playerPool=int(250)
while True:
playerCard=[]
dealerCard=[]
playerBust=False
dealerBust=False
endGame=None
bet=None
playerCard.append(hitDeck())
playerCard.append(hitDeck())
print("You have", playerPool, "dollars to play with.")
while True:
bet=input("""
How much are you betting?
\t1- $5
\t2- $10
\t3- $25
""")
if bet == "1":
print("You put down $5 on the table.")
bet=int(5)
break
elif bet == "2":
print("You put down $10 on the table.")
bet=int(10)
break
elif bet == "3":
print("You put down $25 on the table.")
bet=int(25)
break
else:
print("That is not a valid choice!")
while endGame != "1":
totalPlayer=aceCounter(playerCard)
print("You have", len(playerCard), "cards with a total value of", totalPlayer)
if totalPlayer > 21:
print("You are busted!")
playerBust=True
break
elif totalPlayer == 21:
print("You've got a blackjack!!!")
break
else:
hit=input("""
Would you like to:
\t1- Hit
\t2- Stand
""")
if "1" in hit:
playerCard.append(hitDeck())
elif "2" in hit:
break
else:
print("That is not a valid choice!")
while True:
dealerCard.append(hitDeck())
dealerCard.append(hitDeck())
while True:
totalDealer=aceCounter(dealerCard)
if totalDealer <= 17:
dealerCard.append(hitDeck())
else:
break
print("The dealer has", len(dealerCard), "cards with a total value of", totalDealer)
if totalDealer > 21:
print("The dealer busted!")
dealerBust=True
if playerBust == False:
winning=payout(bet)
print("You won!")
print("You just won", winning, "dollars!")
playerPool+=winning
elif playerBust == True:
print("You both busted but the house will still collect.")
print("You just lost", bet, "dollars...")
playerPool-=bet
elif totalPlayer > totalDealer:
if playerBust == False:
winning=payout(bet)
print("You won!")
print("You just won", winning, "dollars!")
playerPool+=winning
if playerBust == True:
print("The dealer won!")
print("You just lost", bet, "dollars...")
playerPool-=bet
elif totalPlayer == totalDealer:
print("It's a draw, but the house still wins.")
print("You just lost", bet, "dollars...")
playerPool-=bet
elif totalPlayer < totalDealer:
print("The dealer won!")
print("You just lost", bet, "dollars...")
playerPool-=bet
break
if playerPool == 0:
print("You don't have anymore money to play with!")
break
elif playerPool < 0:
print("You owe the house", -playerPool, "dollars, time to work in the kitchen...")
break
print("You have", playerPool, "dollars in your pocket now.")
playAgain=input("Press the Enter key to play again or 'q' to quit.\n")
if "q" in playAgain.lower():
break
The actual error is this:
Traceback (most recent call last):
File "C:\Users\Daniel\Desktop\Software Design\Culminating project revised2.py", line 175, in main()
File "C:\Users\Daniel\Desktop\Software Design\Culminating project revised2.py", line 140, in main
playerPool+=winning
TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType'
When you set option1 in payoutRules you assign integer values.
When you check option1 in payout you compare it against strings. It cannot match anything, and thus payout always returns None.
You could change your payout function to:
def payout(betAmount):
return betAmount * (1.5, 1.25, 1.2)[option1]
Doing it this way you use option1, which is an integer to index into the (1.5, 1.25, 1.2) tuple to get the multiplier to multiply with betAmount. If option1 is not an integer, you'll get an error right there.
Your function will return None if option1 is neither '1' nor '2' nor '3'. In this case adding winning (which is the result of payout) to playerPool will fall.
Maybe you add a print(option1) as first line of your function, to see what it looks like.
You can refactor your function this way:
def payout(betAmount, option1):
return int({'1': 1.5, '2': 1.24, '3': 1.2}[option1] * betAmount)
This way you get at least an key error, when the option1 is not a valid option.