Last active
November 25, 2021 07:06
-
-
Save msyvr/9a93c9c6e5a8a5f6f76ed199bf54789a to your computer and use it in GitHub Desktop.
mastermind: guess the color code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
def is_win(g, s): | |
'''check for a win, assign win value, return boolean''' | |
if all(g[i] == s[i] for i in range(len(s))): | |
win = True | |
print(f'You won! The code was {s}') | |
return win | |
else: | |
win = False | |
return win | |
def valid_max(max_g): | |
'''check if the max chosen is int > 0''' | |
if type(max_g) == int and max_g > 0: | |
return True | |
else: | |
return False | |
def play(): | |
'''play mastermind''' | |
print('*****\nFour stones are lined up in a color code: guess the code!\n(The colors don\'t have to all be different.)\n\nhints:\nb = right color, right spot\nw = right color, wrong spot\n*****\n') | |
n_guess = 1 | |
win = False | |
n_code = 4 | |
colors = list('roygbp') | |
s = [random.choice(colors) for _ in range(n_code)] | |
valid_max = False | |
while valid_max == False: | |
try: | |
max_g = int(input('Max # guesses (int > 0): ')) | |
# check if guess in colors and len 4 | |
if max_g > 0: | |
valid_max = True | |
else: | |
print('Invalid max.') | |
except: | |
print('Invalid max.') | |
while n_guess <= max_g and win == False: | |
valid_guess = False | |
print(f'Guess {n_guess} of {max_g}') | |
while valid_guess == False: | |
g = list(input(f'{len(s)} colors from {colors}:\n').lower()) | |
if len(g) == len(s) and all(g[i] in colors for i in range(len(g))): | |
valid_guess = True | |
else: | |
print(f'Not a valid guess') | |
n_guess += 1 | |
win = is_win(g, s) | |
if win == True: | |
return | |
# check for any color + position matches: these are black pins | |
matches = [] | |
match_i = [] | |
nbp = 0 | |
for i in range(len(g)): | |
if g[i] == s[i]: | |
matches.append((i, s[i])) | |
nbp += 1 | |
# check for color-only matches: these are black pins (don't double count) | |
nwp = 0 | |
match_i = [i for (j, (i, val)) in enumerate(matches)] | |
valid_i = list(range(len(g))) | |
for i in match_i: | |
valid_i.remove(i) | |
valid_j = valid_i[:] | |
for i in valid_i: | |
for j in valid_j: | |
if i != j: | |
if g[i] == s[j]: | |
nwp += 1 | |
valid_j.remove(j) | |
break | |
print(f'black: {nbp}, white: {nwp}') | |
if win == False: | |
print(f'Sorry! The code was {s}') | |
if __name__ == "__main__": | |
play() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment