2

I want to write a very simple number guessing game for my girlfriend by Python. Yet I believe that it is a quite logical problem so anyone who doesn't know Python can also read this! This game is quite standard: computer randomly choose a number and ask the user to guess. Here is my code:

while True:
    from random import randint
    ans = randint(1,100)
    print "Guess from 1 to 100"
    bool = True
    while bool:
        num = input()
        if num < ans:
            print str(num) + " is too small!"
        if num > ans:
            print str(num) + " is too BIG!"
        if num == ans:
            print "Bingo! %d is what I am thinking!" % num
            print "Try again =]"
            for i in range(0,40):
                print '*',
            print
            bool = False

However, I want to add a few of new functions into it:

  • 1. Hide the input by the user as I have already printed it in the sentences
  • 2. Add a "cheat code" that when the user input 'cheat', the answer will show up
  • 3. Add a "detecting silly mistakes" function that when the user make a silly mistake, the computer will give recommendation. Silly mistake means that the user input a number that he has already guessed or a number that not in the range. For example, the answer is 50 and the user has already guessed 30 and 80 and computer has already told him that 30 is too small and 80 is too large. From now on, if the user input any number that is not between the range of 30 and 80, the computer will tell the user the correct range such as "You are silly! The answer should be between 30 and 80!"

    I know that it is a hard question but that is an important gift for my girlfriend so I will be really really appreciate it if anyone can help. Python code is not a must for me so if anyone can answer my third question by just telling me the algorithm, I think that I can work the code out by myself. Thank everyone who reads this!

  • Mazdak
    • 105,000
    • 18
    • 159
    • 188

    4 Answers4

    1

    Try this. The getInput() functions will validate all three of your concerns. The raw_input() function takes anything you give it, which is good because then you can enter commands like 'cheat' and 'exit'. The try&except statements allow you to catch guesses that aren't numbers (or integers). Also by the way, there is no need to make a loop for creating a repeated string, you can simply multiple because python is great! (It's also faster, but that's not a big deal with the small amount of code here) Enjoy!

    def getInput(minValue,maxValue):
        while True:
            try:
                num = raw_input("Enter your guess: ")
                if num == 'cheat':
                    return num
                if num == 'exit':
                    return num
                num = int(num)
                if num < minValue or num > maxValue:
                    print "That is a silly guess! Your number is between %d and %d." % (minValue, maxValue)
                    assert False
                else:
                    return num
            except:
                print "That is not a valid guess!"
    
    exit = False
    while not exit:
        from random import randint
        minValue = 1
        maxValue = 100
        ans = randint(minValue,maxValue)
        print "Guess from %d to %d" % (minValue, maxValue)
        while True:
            num = getInput(minValue, maxValue)
            if num == 'cheat':
                print "I was thinking of %d. Cheater!" % ans
                break
            if num == 'exit':
                print "Exiting program!"
                exit = True
                break
            if num < ans:
                print str(num) + " is too small!"
                minValue = num
            if num > ans:
                print str(num) + " is too BIG!"
                maxValue = num
            if num == ans:
                print "Bingo! %d is what I am thinking!" % num
                print "Try again =]"
                print "* "*40
                print
                break
    
    David C
    • 1,898
    • 2
    • 16
    • 31
    0

    For the second question, simply check if the guess is "cheat". If it is, print the ans and break.

    For the third question you can set up a list with a minimum and a maximum. Each time a guess is made, update their values:

    guess_range = [1, 100]
    
    if guess < guess_range[0]:
        # The guess is silly, print so
    elif guess < ans:
        # The guess is not silly but is lower than ans, update range
        guess_range[0] = guess
    
    # Do the same to guess_range[1] changing comparisons.
    
    xbello
    • 7,223
    • 3
    • 28
    • 41
    • I am a noob in Python. I cannot find a way to check whether the guess is "cheat". The input() doesn't allow me the enter string. Can you kindly give me the code please or which built-in method should I use? Thanks! – Tom Lo Shun Ting Sep 18 '14 at 16:16
    • @TomLoShunTing if that is 2.x, you should be using `raw_input`. Again, look at the link I have provided on validating input. – jonrsharpe Sep 18 '14 at 16:17
    • As easy as `if guess == "cheat":`. If you're this new to python, you should be trying harder by yourself. – xbello Sep 18 '14 at 16:18
    • I am so sorry that I seem to be just asking and not trying at all. Actually I tried (if guess == "cheat":) before I asked, and I don't like the result as I have to type ('cheat') instead of just (cheat). But anyway thank you all. I solved this problem by using raw_input =] – Tom Lo Shun Ting Sep 18 '14 at 16:42
    0

    first question:
    I dont think there is a nice way to do it, but you can use this function:

    import msvcrt
    def invisible():
        key=''
        inpt=''
        while True:
            key = msvcrt.getch()
            if key == '\r': break
            inpt += key
            msvcrt.putch(' ')
        return inpt
    

    then, use it instead of input.

    second question:
    simply check if the returned value of the invisible function is "cheat" or whatever you want to be the cheat word

    third question: like @xbello said. you can have two variables that holds the range. for example, minVal,maxVal then, in each iteration, check the input and update them.

    #assuming inp is integer
    if (inp >= maxVal) or (inp <= minVal):
        print "silly"
    else:
        maxVal = max(maxVal,inp)
        minVal = min(minVal,inp)
    
    Elisha
    • 4,811
    • 4
    • 30
    • 46
    0

    How about this?

    import random
    
    def main():
        ans = random.randint(1,100)
        guess = -1
        cheat = "cheat"
        print "Guess from 1 to 100"
        guessed = []
        lower_bound = 1
        upper_bound = 100
        while guess != ans:
            guess = input(">> ")
            if guess == cheat:
                print "The answer is: ", str(ans)
            if not validate(guess, lower_bound, upper_bound):
                print "Silly, the number is between ", str(lower_bound), " and ", str(upper_bound)
                continue
            if guess in guessed:
                print "You've already guessed that!"
                continue
            guessed.append(guess)
            if guess < ans:
                lower_bound = max(lower_bound, guess)
                print "Too low!"
            elif guess > ans:
                upper_bound = min(upper_bound, guess)
                print "Too high!"
            if guess == ans:
                print "That's right!"
                return
    
    def validate(guess, lower_bound, upper_bound):
        return lower_bound < guess < upper_bound
    
    if __name__ == "__main__":
        play = 'y'
        while play in ('y','Y'):
            main()
            play = raw_input("Play again? (y/n): ")
    
    Adam Smith
    • 52,157
    • 12
    • 73
    • 112