## Python || Random Number Guessing Game Using Random MyRNG & While Loop Here is another homework assignment which was presented in introduction class. The following is a simple guessing game using commandline arguments, which demonstrates the use of generating random numbers.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```How To Get User Input Getting Commandline Arguments While Loops MyRNG.py - Random Number Class ```

==== 1. DESCRIPTION ====

The following program is a simple guessing game which demonstrates how to generate random numbers using python. This program will seed the random number generator (located in the file MyRNG.py), select a number at random, and then ask the user for a guess. Using a while loop, the user will keep attempting to guess the selected random number until the correct guess is obtained, afterwhich the user will have the option of continuing play or exiting.

==== 2. USAGE ====

The user enters various options into the program via the commandline. An example of how the commandline can be used is given below.

``` python3 guess.py [-h] [-v] -s [seed] -m 2 -M 353 ```

Where the brackets are meant to represent features which are optional, meaning the user does not have to specify them at run time.

The -m and -M options are mandatory.

• -M is best picked as a large prime integer
• -m is best picked as an integer in the range of 2,3,..,M-1

NOTE: The use of commandline arguments is not mandatory. If any of the mandatory options are not selected, the program uses its own logic to generate random numbers.

==== 3. FEATURES ====

The following lists and explains the command line argument options.

-s (seed): Seed takes an integer as a parameter and is used to seed the random number generator. When omitted, the program uses its own logic to seed the generator

-v (verbose): Turn on debugging messages.

-h (help): Print out a help message which tells the user how to run the program and a brief description of the program.

-m (minimum): Set the minimum of the range of numbers the program will select its numbers from.

-M (maximum): Set the maximum of the range of numbers the program will select its numbers from.

``` I'm Thinking of a Number Between 1 and 1000... Python # ============================================================================= # Name: K Perkins # Date: Aug 6, 2013 # Taken From: http://programmingnotes.org/ # File: guess.py # Description: This is the guess.py module which uses a random number # generator to simulate a simple guessing game. This program will seed the # random number generator (located in the file MyRNG.py), select a number at # random, and then ask the user for a guess. The user will keep attempting # to guess the selected random number until the correct guess is obtained, # afterwhich the user will have the option of continuing play or exiting # ============================================================================= # Sample commandline: guess.py -s 3454 -m 1 -M 1000 import sys, pdb from MyRNG import * def Usage(status, msg = ""): # Function prints out usage directions aswell as a simple # message if a string is sent as a 2nd parameter if(msg): print(msg) print("nUSAGE:n ", sys.argv,"[-h help] [-v] [-s seed] [-m minimum number]", "[-M maximum number]") sys.exit(status) def IsWarmer(userGuess, numGuess, randomNumber): # Function determines if the current number the user guesses is closer # to the random number than the previous guess. # Function returns TRUE if current user guess is 'warmer' # than previous, otherwise returns FALSE currGuessDifference = userGuess[numGuess] - randomNumber currGuessDifference = math.fabs(currGuessDifference) prevGuessDifference = userGuess[numGuess-1] - randomNumber prevGuessDifference = math.fabs(prevGuessDifference) if(currGuessDifference < prevGuessDifference): return True else: return False def main(): # This is the 'main' function which first takes a string via the commandline # and parses it to determine various modes of operation, namely being # 'seed,' 'minimum,' and 'maximum.' After the commandline options # are obtained, that information is sent to the MyRNG class in order # to generate a random number. After a random number is found, using # a while loop, the user is prompted to try and guess that specified # number, repeatedly doing so until a correct guess is found # declare variables index = 0 # counter which is used to index the sys.argv string verbose = False choices = (("y"),("yes"),("n"),("no")) # This is to be used for the while loop seed = 806189064 # saves the seed from the command line minimum = 1 # saves the minimum num from the command line maximum = 1000 # saves the maximum num from the command line loop = True # this controls the while loop randomNumber = 0 # this saves the random number from the generator userGuess = [] # this saves the user guesses numGuess = 0 # this is the counter wgich keeps track of the num of usr guesses newGame = True # bool to determine if the user is playing a new game programDescr = """nDESCRIPTION: The following is a simple guessing game in which the user is prompted to guess a number and the computer determines if the guess is above, below or exactly the random number which was selected.""" # == determine if the user entered enough args via commandline == # if(len(sys.argv) < 1): #if not enough args, stop the program and print an error message Usage(1, "n** Must provide atleast 1 argument") # == parse thru the argv string to find the appropriate tokens == # for currentArg in sys.argv: if(currentArg == "-h"): # print out the usage message and exit. Usage(2, programDescr) elif(currentArg == "-v"): # set verbose mode to be true for debugging messages verbose = True elif(currentArg == "-s"): # set the seed here # if the user doesnt specify a seed, the # default is my CWID if((index+1 < len(sys.argv)) and (sys.argv[index+1].isdigit())): seed = int(sys.argv[index+1]) else: seed = 806189064 elif currentArg == "-m": # set the minimum here # if the user doesnt specify a min, the default is 1 if((index+1 < len(sys.argv)) and (sys.argv[index+1].isdigit())): minimum = int(sys.argv[index+1]) else: minimum = 1 elif currentArg == "-M": # set the maximum here # if the user doesnt specify a max, the default is 1000 if((index+1 < len(sys.argv)) and (sys.argv[index+1].isdigit())): maximum = int(sys.argv[index+1]) else: maximum = 1000 # increment the index counter index += 1 # print debugging messages if debug mode is on if(verbose): print ("nThis message only appears if verbose mode is turned on.") print (""" ** To continue seeing debugging messages, press the "n" button when prompted. To print the current value of variables, press the "p" button followed by the name of the variable you wish to print. Press the "l" button to visually see where you are in the programs souce code. To quit debugging, press the "c" button.n""") pdb.set_trace() print("nSeed = %d, Minimum = %d, Maximum = %d" %(seed, minimum, maximum)) # == declare the class object == # random = MyRNG(minimum, maximum) random.Seed(seed) randomNumber = random.Next() print("nI'm thinking of a number between %d and %d" ". Go ahead and make your first guess. " %(minimum, maximum)) # * this is the while loop which simulates a guessing game. # * the loop gets a number from the user and determines if the # user input is a "winner, warmer, or colder" in relation to the # random number which was generated. # * once the user guesses correctly, they have a choice of continuing # play or exiting the game. If they choose to play again, a new # random number is generated while(loop): userGuess.append(int(input(">> "))) if(newGame): newGame = False if((userGuess[numGuess] > randomNumber) or (userGuess[numGuess] < randomNumber)): print("nSorry that was not correct, please try again...n") elif((userGuess[numGuess] > randomNumber) or (userGuess[numGuess] < randomNumber)): if(IsWarmer(userGuess, numGuess, randomNumber)): print("nWARMERn") else: print("nCOLDERn") if(userGuess[numGuess] == randomNumber): print("nWINNER! You have guessed correctly!") print("It took you %d attempt(s) to find the answer!" %(numGuess+1)) del userGuess[:] numGuess = -1 answer = input("nWould you like to play again? (Yes or No): ") answer = answer.lower() if(answer in choices[:2]): randomNumber = random.Next() print("nMake a guess between %d and %dn" %(minimum, maximum)) newGame = True elif((answer in choices[2:]) or (answer not in choices[2:])): loop = False numGuess += 1 print("nThanks for playing!!") if __name__ == "__main__": main() # http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168 # =============================================================================#   Name:  K Perkins#   Date:   Aug 6, 2013#   Taken From: http://programmingnotes.org/#   File: guess.py#   Description: This is the guess.py module which uses a random number#    generator to simulate a simple guessing game. This program will seed the#    random number generator (located in the file MyRNG.py), select a number at#    random, and then ask the user for a guess. The user will keep attempting#    to guess the selected random number until the correct guess is obtained,#    afterwhich the user will have the option of continuing play or exiting# =============================================================================# Sample commandline: guess.py -s 3454 -m 1 -M 1000import sys, pdbfrom MyRNG import * def Usage(status, msg = ""):    #   Function prints out usage directions aswell as a simple    #        message if a string is sent as a 2nd parameter    if(msg):        print(msg)    print("nUSAGE:n    ",           sys.argv,"[-h help] [-v] [-s seed] [-m minimum number]",            "[-M maximum number]")    sys.exit(status) def IsWarmer(userGuess, numGuess, randomNumber):    #   Function determines if the current number the user guesses is closer    #       to the random number than the previous guess.    #       Function returns TRUE if current user guess is 'warmer'    #       than previous, otherwise returns FALSE    currGuessDifference = userGuess[numGuess] - randomNumber    currGuessDifference = math.fabs(currGuessDifference)    prevGuessDifference = userGuess[numGuess-1] - randomNumber    prevGuessDifference = math.fabs(prevGuessDifference)     if(currGuessDifference < prevGuessDifference):        return True    else:        return False def main():#   This is the 'main' function which first takes a string via the commandline#        and parses it to determine various modes of operation, namely being#        'seed,' 'minimum,' and 'maximum.' After the commandline options#        are obtained, that information is sent to the MyRNG class in order#        to generate a random number. After a random number is found, using#        a while loop, the user is prompted to try and guess that specified#        number, repeatedly doing so until a correct guess is found     # declare variables    index = 0   # counter which is used to index the sys.argv string    verbose = False    choices = (("y"),("yes"),("n"),("no"))  # This is to be used for the while loop    seed = 806189064  # saves the seed from the command line    minimum = 1  # saves the minimum num from the command line    maximum = 1000  # saves the maximum num from the command line    loop = True  # this controls the while loop    randomNumber = 0  # this saves the random number from the generator    userGuess = []  # this saves the user guesses    numGuess = 0  # this is the counter wgich keeps track of the num of usr guesses    newGame = True # bool to determine if the user is playing a new game    programDescr = """nDESCRIPTION:          The following is a simple guessing game in which the user         is prompted to guess a number and the computer determines         if the guess is above, below or exactly the random number         which was selected."""    # == determine if the user entered enough args via commandline == #    if(len(sys.argv) < 1):        #if not enough args, stop the program and print an error message        Usage(1, "n** Must provide atleast 1 argument")     # == parse thru the argv string to find the appropriate tokens == #    for currentArg in sys.argv:        if(currentArg == "-h"):        # print out the usage message and exit.            Usage(2, programDescr)        elif(currentArg == "-v"):        # set verbose mode to be true for debugging messages            verbose = True        elif(currentArg == "-s"):        # set the seed here        # if the user doesnt specify a seed, the        # default is my CWID            if((index+1 < len(sys.argv)) and (sys.argv[index+1].isdigit())):                seed = int(sys.argv[index+1])            else:                seed = 806189064        elif currentArg == "-m":        # set the minimum here        # if the user doesnt specify a min, the default is 1            if((index+1 < len(sys.argv)) and (sys.argv[index+1].isdigit())):                minimum = int(sys.argv[index+1])            else:                minimum = 1        elif currentArg == "-M":        # set the maximum here        # if the user doesnt specify a max, the default is 1000            if((index+1 < len(sys.argv)) and (sys.argv[index+1].isdigit())):                maximum = int(sys.argv[index+1])            else:                maximum = 1000        # increment the index counter        index += 1     # print debugging messages if debug mode is on    if(verbose):        print ("nThis message only appears if verbose mode is turned on.")        print ("""           ** To continue seeing debugging messages, press the "n"           button when prompted. To print the current value of variables,           press the "p" button followed by the name of the variable you           wish to print. Press the "l" button to visually see where you           are in the programs souce code. To quit debugging, press the           "c" button.n""")        pdb.set_trace()     print("nSeed = %d, Minimum = %d, Maximum = %d" %(seed, minimum, maximum))     # == declare the class object == #    random = MyRNG(minimum, maximum)    random.Seed(seed)    randomNumber = random.Next()     print("nI'm thinking of a number between %d and %d"      ". Go ahead and make your first guess. " %(minimum, maximum))     # * this is the while loop which simulates a guessing game.    # * the loop gets a number from the user and determines if the    # user input is a "winner, warmer, or colder" in relation to the    # random number which was generated.    # * once the user guesses correctly, they have a choice of continuing    # play or exiting the game. If they choose to play again, a new    # random number is generated    while(loop):        userGuess.append(int(input(">> ")))         if(newGame):            newGame = False            if((userGuess[numGuess] > randomNumber) or (userGuess[numGuess] < randomNumber)):                print("nSorry that was not correct, please try again...n")        elif((userGuess[numGuess] > randomNumber) or (userGuess[numGuess] < randomNumber)):            if(IsWarmer(userGuess, numGuess, randomNumber)):                print("nWARMERn")            else:                print("nCOLDERn")        if(userGuess[numGuess] == randomNumber):            print("nWINNER! You have guessed correctly!")            print("It took you %d attempt(s) to find the answer!" %(numGuess+1))            del userGuess[:]            numGuess = -1            answer = input("nWould you like to play again? (Yes or No): ")            answer = answer.lower()            if(answer in choices[:2]):                randomNumber = random.Next()                print("nMake a guess between %d and %dn" %(minimum, maximum))                newGame = True            elif((answer in choices[2:]) or (answer not in choices[2:])):                loop = False        numGuess += 1     print("nThanks for playing!!") if __name__ == "__main__":    main()# http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output:

`Seed = 806189064, Minimum = 1, Maximum = 1000`

``` I'm thinking of a number between 1 and 1000. Go ahead and make your first guess. >> 500 Sorry that was not correct, please try again... >> 400 WARMER >> 600 COLDER >> 300 WARMER >> 150 WARMER >> 100 COLDER >> 180 COLDER >> 190 COLDER >> 130 WARMER >> 128 WINNER! You have guessed correctly! It took you 10 attempt(s) to find the answer! Would you like to play again? (Yes or No): y ------------------------------------------------------------ Make a guess between 1 and 1000 >> 500 Sorry that was not correct, please try again... >> 600 COLDER >> 400 WARMER >> 300 WARMER >> 280 WARMER >> 260 WARMER >> 250 COLDER >> 256 WINNER! You have guessed correctly! It took you 8 attempt(s) to find the answer! Would you like to play again? (Yes or No): n ```

```Thanks for playing!! ```