I'm building a game as part of a tutorial on learning code.
The following class has a while loop that should return either 'finished' or, leave the loop and return 'death' (These are dict entries that run the game) but instead does not even seem to run. I'm looking at the while loop after def guess:
The loop is meant to ask the user to guess a number between 1 and three. If they guess wrong more than three times they "lose" and 'death' is returned, else 'finished'.
But, when I play the game I am not even prompted to enter a number, instead "Too many failed guesses, you lose!" is printed, even if guesses is 0.
class Smaug(Scene):
def enter(self):
print "Smaug is a terrifying huge fire breathing dragon, but you must get the Arkenstone from him for Thorin"
print "In Smaug's cave, the Lonely Mountain, Smaug notices your presence and challenges you to a game"
print "He says \"Guess a number between 1 and 3\""
smaugNum = random.randint(1, 3)
print "Smaugs number cheat:", smaugNum
guesses = 0
def guess():
while guesses < 4:
print "Guess a number between 1 and 3"
numb = raw_input("> ")
if numb == smaugNum:
print "Well done! You win."
Player.BilbosStuff.append('arkenstone')
print "Now Bilbo has", Player.BilbosStuff
return 'finished'
else:
print "You lose!"
guesses += 1
guess()
print "Too many failed guesses, you lose!"
return 'death'
Looking at the nesting of the code blocks, is it that when 'finished' is returned in the while loop, does it also, automatically, get returned as part of the wider class? Put another way, if numb == smaugNum then I need Smaug class to return finished.
The problem is that you are not calling the guess() function at all.. You have guess() as a function and it is not called at all. so, the control directly jumps to the next line after the function. The best way is to remove the function and use the code like this:
guesses = 0
while guesses < 4:
print "Guess a number between 1 and 3"
numb = raw_input("> ")
if numb == smaugNum:
print "Well done! You win."
Player.BilbosStuff.append('arkenstone')
print "Now Bilbo has", Player.BilbosStuff
return 'finished'
else:
print "You lose!"
guesses += 1
print "Too many failed guesses, you lose!"
return 'death'
You are defining guess smack dab in the middle of enter, but you are never calling it.
The blocks are like
class Smaug:
def enter:
#here's what to do when enter() is called
def guess:
#here's what to do when guess() is called
#here's some more stuff to do when enter() is called
The problem here is that you are infinitely recursing down the guess function and never calling guess() in the first place.
After you increase your guesses counter you do not need to call guess() again as the execution will still be inside the while loop due to the number of guesses being less than 4, simply trust the while loop to do the comparison. Avoid calling guess() manually.
Related
I was writing a code that will ask you to play a guessing game. It will ask you whether you want to play or not and proceed.
It was supposed to ask a number again if the entered value is not in the list but It is not working. I couldn't get it. Thx by now!
import random
import math
import time
repeat=True
numbers = ["1","2","3","4","5"]
gamestart=False
gamecontinue=True
def guess():
chosennumber=random.choice(numbers)
guessnumber=raw_input(">Guess the number I chose between 0 and 6:")
if guessnumber==chosennumber and guessnumber in numbers:
print ">Congratulations, I chose %d too!" % (int(chosennumber))
print
elif guessnumber!=chosennumber:
print "That is not right."
print "I chose %d." % (int(chosennumber))
print
elif not guessnumber in numbers:
while not guessnumber in numbers:
guessnumber=raw_input(">Please enter a number between 0 and 6:")
if raw_input(">Do you want to play guessing game? Y or N:") == "Y":
gamestart=True
else:
print "Okay, I will play myself."
time.sleep(2)
print "Bye :("
while gamestart==True and gamecontinue==True:
guess()
if raw_input (">Do you want to play again? Y or N:") == "N":
gamecontinue=False
print "Okay, I will play myself."
time.sleep(2)
print "Bye :("
so you figured out what was the issue, good! but i have one more tip for you, a better approach to achieve this is check if the input is correct as soon is readed, if it is correct you keep going, if it not, you ask for it again right there:
while True:
guessnumber=raw_input(">Guess the number I chose between 0 and 6:")
if guessnumber in numbers:
print "good!"
break
else:
print "bad!"
and now you're sure that the input is correct so you only check:
if guessnumber==chosennumber:
print ">Congratulations, I chose %d too!" % (int(chosennumber))
else:
print "That is not right."
print "I chose %d." % (int(chosennumber))
if number not in numbers
That will do the trick
It checks if it is true that the selected number is in the list
The problem is that if you put two elif statements the first one will proceed first.
elif guessnumber!=chosennumber:
print "That is not right."
print "I chose %d." % (int(chosennumber))
print
This condition will be asked first. But if you look again at it whether the input (guessnumber) is in the list or not it will proceed. So if we want it to become a condition which we enter a number that is in a list but not matching with the chosen number, we will add another condition to elif statement.
code will be like this
elif guessnumber!=chosennumber and guessnumber in numbers:
Slight detail but good to keep in mind I think.
So I'm learning to code and I started with Python.
I've learned the very basics of programming in python, like what are variables, operators, some functions etc.
I have this code:
def guessGame():
import random
guesses = 0
randomNo = random.randint(0, 100)
print "I think of a number between 0 and 100, you have 10 guesses to get it right!"
while guesses < 10:
guess = input("Take a guess ")
guess = int(guess)
guesses += 1
if guess < randomNo:
print "The number is higher than your guess"
if guess > randomNo:
print "The number is lower than your guess"
if guess == randomNo:
break
if guess == randomNo:
guesses = str(guesses)
print "You got it in %s guesses!" % guesses
if guess != randomNo:
print "You failed to guess!"
guessGame()
when I run the code in cmd it just ends before the function gets "recalled".
cmd output
You called the game only once in your main program -- which consists of the last line only. It runs the game once and quits. There is no second call in your code. Perhaps you want a classic "play again?" loop:
play = True
while play:
guessGame()
play = lower(raw_input("Play again?")[0]) == 'y'
after each game, you ask the player for input. If that input begins with the letter 'y' (upper or lower case), then you continue playing; otherwise, play becomes False and you drop out of the loop.
Is that what you wanted?
I just started out in python and I am programming a hangman game base on a book. May I know why is my code below not running in the order that I want it to run?
When I execute the program, the letter guessed in guess is suppose to go into used to indicate which letters has the player already guessed to find out the right word. However, this only happens every 2 turns and not every 1 turn. I've indicated the hangman ACSII art at the start of the program in an image file for reference, below the image are the code. Would gladly appreciate any help. Thanks!
MAX_WRONG = len(HANGMAN)-1
WORDS = ("book","toy","paper","school","house","computer","television")
word=random.choice(WORDS)
so_far = "-"*len(word)
wrong = 0
used = []
print "Welcome to hangman! Guess the the word before the the man is hang dead!"
print "You can only guess one letter at a time!"
while wrong < MAX_WRONG and so_far!=word:
print HANGMAN[wrong]
print "\nYou've used the following letters:\n",used
print "\nSo far, the word is:\n", so_far
guess = raw_input("\n\nEnter your guess:")
guess = guess.lower()
if guess in word:
used+=guess
print "\nYou've used the following letters:\n",used
print"\nYes!",guess,"is in the word!"
new=""
for i in range(len(word)):
if guess == word[i]:
new+=guess
else:
new+=so_far[i]
so_far=new
else:
used+=guess
print "\nYou've used the following letters:\n",used
print "\nSo far, the word is:\n", so_far
print"\nSorry,",guess,"isn't in the word."
guess = raw_input("\n\nEnter your guess:")
wrong+=1
while guess in used:
print "You've already guessed the letter:",guess
print "\nYou've used the following letters:\n",used
print "\nSo far, the word is:\n", so_far
guess = raw_input("Enter your guess:")
guess = guess.lower
if wrong == MAX_WRONG:
print HANGMAN[wrong]
print "\nYou've been hanged!"
else:
print "\nYou guessed it!"
print "\nThe word was",word
raw_input("\n\nPress the enter key to exit.")
It appears to be happening 2 turns, but that is not the case. The problem is that your program prompts the user twice in a single turn. At the start of the loop you ask the user for a letter. If it was tell me it was wrong, then you ask for another letter. Then your loop repeats and you ask for a letter again.
The problem is that you are asking for a letter twice within the loop, not once. In programming we have what is called the DRY principle which means don't repeat yourself. Your code shows one of many reasons not to repeat yourself. You thought that your loop was running twice, but you were actually just running the same code multiple times in your loop.
so I am trying to do simple rolling of the dice to see if you win(excuse if something is indented wrong, the copy n paste is kinda wonky, here is a pastbin if you would rather have that http://pastebin.com/thg7ruT1). I am not exactly sure what is happen but when I run the YouMightWin function, no matter what StanDice's outcome is it always says "You Win!" even if it rolls less than 6. I am not sure what looks like it should work to me, at least from other things I've played around. If you can help thanks.
def StanDice():
num_dice = 2
num_sides = 6
rand_num = random.randint(1, num_dice*num_sides)
print rand_num
def YouMightWin():
Ans = raw_input("Roll the dice? [Y/N]: ")
Ans = Ans.lower()
dice_roll = StanDice()
if Ans in ("y" or "yes"):
print dice_roll, "This is the Dice"
if dice_roll < 6:
print "You win!"
elif dice_roll > 6:
print "You lose!"
else:
print "Something went wrong!"
elif Ans in ('n' or 'no'):
print "Are you sure you don't want to roll?"
YouMightWin()
else:
print "Something went in the main if statement"
You're printing the value of rand_num instead of returning it, so the function returns None, which is less than 6.
That said, your dice are too naive-- real don't have an equal chance of rolling 2 and 7. Check out a probability table. You should roll each die independently and add them together instead.
I have been set some homework to make a word guessing game, I have got it to work for the most part but at this point I am using random.choice and that command allows the same string to repeat more than once. I need to know how to use random.randint in this instance.
""" This is a guessing game which allows the person operating the program to
guess what i want for christmas"""
import random
sw = ("Trainers")
print ("In this game you will have 10 chances to guess what I want for christmas, you start with 10 points, each time you guess incorrectly you will be deducted one point. Each time you guess incorrectly you will be given another clue.")
clue_list = ["They are an item of clothing", "The item comes in pairs", "The Item is worn whilst playing sport", "The item is an inanimate object", "The item can be made of leather","They come in differant sizes", "They have laces", "can be all differant colours", "the item has soles", "Im getting it for christmas ;)"]
def guessing_game(sw, clue_list):
x = 10
while x<=10 and x > 0:
answer = input("What do I want for christmas?")
if sw.lower() == answer and answer.isalpha():
print ("Good Guess thats what I want for christmas")
print ("You scored %s points" % (x))
break
else:
print ("incorrect, " + random.choice(clue_list))
x -=1
if x == 0:
print ("You lost, try again")
guessing_game(sw, clue_list)
for your implementation I think you want:
clueint = random.randint(0, len(clue_list))
print("incorrect, " + clue_list[clueint])
to ensure the same clues are not displayed twice declare an empty list to store guess in OUTSIDE the function definition:
clues_shown = []
and then add each int to the list:
def showClue():
clueint = random.randint(0, len(clue_list))
if clueint in clues_shown:
showClue()
else:
clues_shown.append(clueint)
print("incorrect, " + clue_list[clueint])