Advertisement
Guest User

mastermind.py

a guest
May 16th, 2014
413
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.78 KB | None | 0 0
  1. ## Mastermind program
  2. import random
  3.  
  4. # Create a random number of 4 digits between 1 and 6
  5. masterNumber = [random.randint(1,6) for r in range(4)]
  6.  
  7. # User gets 20 guesses
  8. guesscount=20
  9. numposition=0
  10.  
  11. #Loop through until the 4 numbers are guessed or the 20 guesses are exhausted
  12. while guesscount>0 and numposition<4:
  13.     print "You have {} guesses left".format(guesscount)
  14.  
  15.     # Get input and validate that it's in the proper range
  16.     guess = raw_input("Guess my 4 digit number (digits between 1 and 6): ")
  17.     while len([x for x in guess if x not in ("1","2","3","4","5","6")]) > 0:
  18.         guess = raw_input("Invalid guess. Try again: ")
  19.  
  20.     # Convert input to integers
  21.     guess = [int(x) for x in guess]
  22.  
  23.     # Find out the number of matches regardless of position. Using a copy of the master number, figure
  24.     # out the number of correct guesses by looping through while popping correct matches. If our master
  25.     # number could never repeat numbers, this would be as simple as len(set(masterNumber) - set(guess))
  26.     # or len([x for x in masterNumber if x in guess])
  27.  
  28.     right=[]
  29.     numbercopy = masterNumber[:]
  30.     for x in range(4):
  31.         if guess[x] in numbercopy:
  32.             right.append(numbercopy.pop(numbercopy.index(guess[x])))
  33.     numright = len(right)
  34.  
  35.     # Now find out the number of matches at the right position. Simple list comprehension for this one
  36.     numposition = len([x for x in range(4) if guess[x]==masterNumber[x]])
  37.  
  38.     # Print out the information and decrement the guess counter
  39.     print "You have {} digits correct and {} in the right position.".format(numright,numposition)
  40.     print
  41.     guesscount -=1
  42.  
  43. if numposition==4:
  44.   print "CORRECT! The number was",masterNumber
  45. else:
  46.   print "You ran out of guesses. The number was",masterNumber
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement