mos_basik

CS 1 Lab 2 Part B

Feb 11th, 2013
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.05 KB | None | 0 0
  1. import random
  2.  
  3. def make_random_code():
  4.     '''Returns a string of exactly four characters, each of which should be one
  5.    of 'R', 'G', 'B', 'Y', 'O', or 'W'.'''
  6.     colors = ['R', 'G', 'B', 'Y', 'O', 'W']
  7.     code = ''
  8.     i = 0
  9.     while i < 4:
  10.         code += random.choice(colors)
  11.         i += 1
  12.     return code
  13.  
  14. def count_exact_matches(str1, str2):
  15.     '''Takes two arguments, both strings of length 4.  Returns the number of
  16.    places where the two strings have the exact same letters at the exact same
  17.    locations.'''
  18.     count = 0
  19.     for i in range(len(str1)):
  20.         if str1[i] == str2[i]:
  21.             count += 1
  22.     return count
  23.  
  24. def count_letter_matches(str1, str2):
  25.     '''Takes two arguments, both strings of length 4.  Returns the number of
  26.    letters used in both strings regardless of location.'''
  27.     lst1 = list(str1)
  28.     lst2 = list(str2)
  29.     count = 0
  30.     for letter in lst1:
  31.         if letter in lst2:
  32.             count += 1
  33.             lst2.remove(letter)
  34.     return count
  35.  
  36. def compare_codes(code, guess):
  37.     '''Takes two arguments, both strings of length 4.  Returns a string composed
  38.    of the characters "b" (representing a match of both letter and position),
  39.    "w" (representing a match of letter but not of position) and "-"
  40.    (representing no match).'''
  41.     count_black = count_exact_matches(code, guess)
  42.     count_white = count_letter_matches(code, guess) \
  43.                                             - count_exact_matches(code, guess)
  44.     count_blank = 4 - (count_black + count_white)
  45.     hint = ''
  46.     hint += 'b' * count_black
  47.     hint += 'w' * count_white
  48.     hint += '-' * count_blank
  49.     return hint
  50.  
  51. def run_game():
  52.     print 'New game.'
  53.     code = make_random_code()
  54.     count = 0
  55.     while True:
  56.         guess = raw_input('Enter your guess: ')
  57.         hint = compare_codes(code, guess)
  58.         print '          Result: %s' % hint
  59.         count += 1
  60.         if hint == 'bbbb':
  61.             print 'Congratulations!  You cracked the code in %d moves!' % count
  62.             break
Advertisement
Add Comment
Please, Sign In to add comment