Skip to content

Instantly share code, notes, and snippets.

@Yaulendil
Created November 4, 2018 04:10
Show Gist options
  • Save Yaulendil/9ed4d2351fc68785c9609c6834da1dfc to your computer and use it in GitHub Desktop.
Save Yaulendil/9ed4d2351fc68785c9609c6834da1dfc to your computer and use it in GitHub Desktop.
A quick implementation of Mastermind
from numpy import random as npr
SECRET = [npr.randint(1,7) for _ in range(4)]
TURN = 0
guesses = []
def tryseq(sequence):
"""
[2, 2, 5, 4] for example
:type sequence: list
"""
global TURN
TURN += 1
if TURN > 12:
return
guesses.append(sequence)
black=0
white=0
board = SECRET.copy()
for i in range(len(sequence)):
if sequence[i] == board[i]:
black += 1
board[i] = -1
for i in range(len(sequence)):
if sequence[i] in board:
white += 1
board.remove(sequence[i])
return black, white
print("-==# MASTERMIND PYTHON #==-")
print("Input a sequence of four numbers (1-6) until you win or lose ('1234', '3321', etc.)")
try:
while TURN < 12:
guess = list(input("Sequence to try: "))
try:
if len(guess) != 4:
raise ValueError
guess = [int(v) for v in guess if 1 <= int(v) <= 6]
b, w = tryseq(guess)
print("\x1b[1ATURN {}:".format(TURN), guess, "|", (b, w))
if b == 4:
print("VICTORY")
break
elif TURN >= 12:
print("FAILURE")
break
except:
print("It must be 4 numbers!")
except (EOFError, KeyboardInterrupt):
print("QUIT")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment