Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- def make_random_code():
- '''Returns a string of exactly four characters, each of which should be one
- of 'R', 'G', 'B', 'Y', 'O', or 'W'.'''
- colors = ['R', 'G', 'B', 'Y', 'O', 'W']
- code = ''
- i = 0
- while i < 4:
- code += random.choice(colors)
- i += 1
- return code
- def count_exact_matches(str1, str2):
- '''Takes two arguments, both strings of length 4. Returns the number of
- places where the two strings have the exact same letters at the exact same
- locations.'''
- count = 0
- for i in range(len(str1)):
- if str1[i] == str2[i]:
- count += 1
- return count
- def count_letter_matches(str1, str2):
- '''Takes two arguments, both strings of length 4. Returns the number of
- letters used in both strings regardless of location.'''
- lst1 = list(str1)
- lst2 = list(str2)
- count = 0
- for letter in lst1:
- if letter in lst2:
- count += 1
- lst2.remove(letter)
- return count
- def compare_codes(code, guess):
- '''Takes two arguments, both strings of length 4. Returns a string composed
- of the characters "b" (representing a match of both letter and position),
- "w" (representing a match of letter but not of position) and "-"
- (representing no match).'''
- count_black = count_exact_matches(code, guess)
- count_white = count_letter_matches(code, guess) \
- - count_exact_matches(code, guess)
- count_blank = 4 - (count_black + count_white)
- hint = ''
- hint += 'b' * count_black
- hint += 'w' * count_white
- hint += '-' * count_blank
- return hint
- def run_game():
- print 'New game.'
- code = make_random_code()
- count = 0
- while True:
- guess = raw_input('Enter your guess: ')
- hint = compare_codes(code, guess)
- print ' Result: %s' % hint
- count += 1
- if hint == 'bbbb':
- print 'Congratulations! You cracked the code in %d moves!' % count
- break
Advertisement
Add Comment
Please, Sign In to add comment