mmastermind
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
#! /usr/bin/env python3 | |
import collections | |
import random | |
COLORS = ["R", "O", "Y", "G", "B", "V"] | |
MAX_TURNS = 10 | |
def setup_game(): | |
code = random.choices(COLORS, k=4) | |
return { | |
# Choose random code | |
'code': code, | |
# Set turn 1 | |
'turn': 1, | |
} | |
def print_code(code): | |
out = "" | |
for letter in code: | |
if letter == "R": | |
out += "\033[31mR\033[0m" | |
elif letter == "O": | |
out += "\033[1;31mO\033[0m" | |
elif letter == "Y": | |
out += "\033[33mY\033[0m" | |
elif letter == "G": | |
out += "\033[32mG\033[0m" | |
elif letter == "B": | |
out += "\033[34mB\033[0m" | |
elif letter == "V": | |
out += "\033[1;35mV\033[0m" | |
return out | |
def get_code(): | |
code = input("\033[1;37mEnter your guess:\033[0m ") | |
code_onlyLetters = [c for c in code.upper() if c.isalpha()] | |
code_onlyColors = [c for c in code_onlyLetters if c in COLORS] | |
if len(code_onlyLetters) != 4 or len(code_onlyColors) != 4: | |
print("\033[36mPlease enter exactly four colors\033[0m") | |
return get_code() | |
return code_onlyColors | |
def score_code(user_code, master_code): | |
wrongColorsUser = collections.defaultdict(int) | |
wrongColorsMaster = collections.defaultdict(int) | |
correctPositions = 0 | |
for (u, m) in zip(user_code, master_code): | |
if u == m: | |
# color correct and in position | |
correctPositions += 1 | |
else: | |
# color correct and out of position | |
wrongColorsUser[u] += 1 | |
wrongColorsMaster[m] += 1 | |
wrongPositions = 0 | |
for color in wrongColorsUser: | |
nUser = wrongColorsUser[color] | |
nMaster = wrongColorsMaster[color] | |
wrongPositions += min(nUser, nMaster) | |
return (correctPositions, wrongPositions) | |
def main(): | |
print("Welcome to Mmastermind!!!! The colors are {}: ".format(COLORS)) | |
# Add instructions | |
game = setup_game() | |
game_running = True | |
while game_running: | |
user_code = get_code() | |
print("You guessed {}".format(print_code(user_code))) | |
num_correct, num_wrong_pos = score_code(user_code, game['code']) | |
print( | |
"{} correct and in right position, {} correct but in wrong position" | |
.format(num_correct, num_wrong_pos)) | |
if num_correct == 4: | |
print("You win! You are the Mmastermind! ๐๐๐๐๐๐๐๐") | |
game_running = False | |
game['turn'] += 1 | |
if game['turn'] > MAX_TURNS: | |
print("You lose! ๐ข Code was {}".format(print_code(game['code']))) | |
game_running = False | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment