giladh

Random number guessing game - Python

Jul 21st, 2011
389
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.67 KB | None | 0 0
  1. #!/usr/bin/python2.7
  2.  
  3. '''
  4. Random number guessing game
  5. Created on Jul 19, 2011
  6. @author: giladh
  7. '''
  8.  
  9. import random # Random number generator
  10. import sys
  11. import csv
  12. import re  #Regular expression module
  13. from itertools import islice
  14.  
  15. def hscores ():
  16.     hscoresfile="/tmp/scorefile2"
  17.     try:
  18.         hscoresfile
  19.     except:
  20.         with open('/tmp/scorefile2', 'w') as hscores_fh_w:
  21.             pass    #create the scorefile if it doesn't exist
  22.        
  23.     with open('/tmp/scorefile2', 'rb') as hscores_fh_r:  #open hscores file for reading
  24.         reader = csv.reader(hscores_fh_r) #call csv.reader to parse file
  25.         sorted_scores = (sorted(reader, key=lambda x:float(x[1]) )) #sort numeric by score
  26.         top_ten = list(islice(sorted_scores,10))    #slice off top 10 players
  27.    
  28.         format = "%-8s %-8s %8s"    #generate print format
  29.         print "The top 10 players are:\n"  
  30.         print format % ("RANK","PLAYER","SCORE")
  31.         print format % ("----","------","-----")
  32.         rank = 1
  33.         for row in top_ten:
  34.             name,score = row[0],row[1]
  35.             print format % (rank,name,score)
  36.             rank += 1
  37.         print
  38.  
  39. #Core game function
  40. def playgame ():
  41.     global player
  42.     randnum = random.randint(0,100)
  43.     print "The random number is:", randnum
  44.     print "\nThis is a random number guessing game...  You are to guess a number between 1-100...\n"
  45.     try:    #Is player defined?
  46.         player  
  47.     except: #Get player's name
  48.         player = raw_input("Please enter your name: ")
  49.         print "Hello " + player + ", welcome!\n"
  50.     hscores()
  51.      
  52.     allguess = []   #Initialize array of player's guesses
  53.     guess = []  #Initialize the 'guess' variable
  54.     while guess != randnum:
  55.         if allguess:
  56.             guess = (raw_input("Enter your next guess: "))
  57.         else:
  58.             guess = (raw_input(player + ", please enter your first guess: "))
  59.         try:
  60.             int(guess)
  61.         except:
  62.             print "Sorry, you must enter a valid integer..."    
  63.             continue
  64.         guess = int(guess)  #make sure its a number
  65.         if guess in allguess:
  66.             print "You already guessed that number, please try again..."
  67.             continue
  68.         elif guess < 1 or guess > 100:
  69.             print "Please enter a valid integer between 1 and 100..."
  70.             continue
  71.         allguess.append(guess)  #Add the guess to the array
  72.        
  73.         if len(allguess) > 1 and guess != randnum:  #Should we calculate warmer/colder?
  74.             prev_gdiff = abs(randnum - allguess[-2])
  75.             curr_gdiff = abs(randnum - allguess[-1])
  76.             if curr_gdiff < prev_gdiff:
  77.                 print "you're getting warmer..."
  78.             elif curr_gdiff > prev_gdiff:
  79.                 print "you're getting colder..."
  80.             elif curr_gdiff == prev_gdiff:
  81.                 print "same difference..."
  82.    
  83.     num_tries = int(len(allguess))                    
  84.     print "\n" + player + ", you guessed it in " + str(num_tries) + " tries!"
  85.     print "Your guesses were: " + str(allguess) + "\n"
  86.    
  87.     #write to scorefile
  88.     with open('/tmp/scorefile2', 'a') as hscores_fh_w:   #open hscores file for append
  89.         writer = csv.writer(hscores_fh_w)
  90.         writer.writerow([player, num_tries])
  91.        
  92.     repeat()    #See if user wants to play again, call repeat func
  93.  
  94. #Repeat game function    
  95. def repeat ():    
  96.     repeat = raw_input("Play Again? (Y/N): ").lower()
  97.     if re.match('y', repeat):
  98.         playgame()
  99.     else:
  100.         print
  101.         hscores()
  102.         print "Thanks for playing " + player + "!"
  103.         sys.exit(0)            
  104.  
  105. #Start the game
  106. playgame()
Advertisement
Add Comment
Please, Sign In to add comment