Beispiel #1
0
 def setup(self):
     self.pygame.init()
     self.pygame.font.init()
     self.pygame.display.set_caption("TGMastermind!")
     self.mastermind = Mastermind(self)
     self.view = View(self)
     self.playing = True
     self.carryOn = True
Beispiel #2
0
def main():
    guess_length_rule = GuessLengthRule()
    valid_colour_rule = ValidColourRule()

    rules = [guess_length_rule, valid_colour_rule]
    input_validator = InputValidator(rules)
    hint_checker = HintChecker()

    mastermind = Mastermind(input_validator, hint_checker)
    mastermind.play()
    def __init__(self):
        self.board = Mastermind(size=4, min_value=1, max_value=3)
        self.board_size = self.board.size
        self.min = 1
        self.max = 9

        self.known = {}
        self.existed = set()
        self.cannot = {i: set() for i in range(self.board_size)}
        self.not_existed = set()
    def __init__(self):
        self.HEIGHT, self.WIDTH = 400, 600
        self.BLACK = (0, 0, 0)
        self.WHITE = (255, 255, 255)
        self.game = Mastermind()
        self.size = self.game.size

        #Initialize the window
        pygame.init()
        self.screen = pygame.display.set_mode((self.WIDTH, self.HEIGHT))
        pygame.display.set_caption("Mastermind 1.0")
        self.screen.fill((self.BLACK))
Beispiel #5
0
def eval_genomes(genomes, config):
    solution = [random.randint(1, 4) for i in range(4)]
    solution_2 = [random.randint(1, 4) for i in range(4)]
    for genome_id, genome in genomes:
        genome.fitness = 4.0
        net = neat.nn.FeedForwardNetwork.create(genome, config)
        ## master mind
        mm = Mastermind(4, 8, solution)
        mm_2 = Mastermind(4, 8, solution_2)
        hints_table = mm.play_neat_bot(net, show_board=False)
        hints_table_2 = mm_2.play_neat_bot(net, show_board=False)
        genome.fitness += float(fitness_function(hints_table))
        genome.fitness += float(fitness_function(hints_table_2))
    def launch(self):
        self.draw_guessing_squares(text="Your test")
        hist_board = self.draw_scoreboard(0,
                                          text1="AI guesses: ",
                                          text2="AI past guesses")
        previous = 0
        turn = 0

        while True:
            for event in pygame.event.get():

                if event.type == pygame.MOUSEBUTTONDOWN:
                    pos = pygame.mouse.get_pos()

                    #Handling the clicking of the squares
                    for i, square in enumerate(self.buttons):
                        if square.collidepoint(pos):
                            self.draw_outline(self.buttons[previous],
                                              self.BLACK)
                            self.draw_outline(square, self.GREEN)
                            previous = i

                if event.type == pygame.QUIT:
                    pygame.quit()
                    return False

                #The user enters from a keyboard
                if event.type == pygame.KEYDOWN:
                    output = self.keyboard_pressed(event)

                    if isinstance(output, int):
                        self.draw_entered_guess(output, self.buttons[previous])

                        #Handling error
                        #TODO
                        if output > 5:
                            #Do something
                            pass
                        #If the answer is not full, then raise an error

                        self.answer[previous] = output

                    if output == "left":
                        self.draw_outline(self.buttons[previous], self.BLACK)
                        previous -= 1
                        if previous == -1:
                            previous = self.board_size - 1
                        self.draw_outline(self.buttons[previous], self.GREEN)

                    if output == "right":
                        self.draw_outline(self.buttons[previous], self.BLACK)
                        previous += 1
                        if previous == self.board_size:
                            previous = 0
                        self.draw_outline(self.buttons[previous], self.GREEN)

                    if output == "delete":
                        self.draw_entered_guess(None, self.buttons[previous])

                    if output == "submit":
                        min_val = min(self.answer)
                        max_val = max(self.answer)
                        size = len(self.answer)
                        board = Mastermind(size=size,
                                           min_value=min_val,
                                           max_value=max_val,
                                           rand=False)
                        board.set_board(self.answer)
                        self.AI.set_board(board)
                        guesses = self.AI.solve()
                        hist_board = self.draw_scoreboard(
                            len(guesses),
                            text1="AI guesses: ",
                            text2="AI past guesses")
                        for i in range(len(guesses)):
                            self.draw_past_guess(guesses[i], i + 1, hist_board)

                        self.winning(text="AI solves it!")
Beispiel #7
0
    file.close()


def open_table(file_name, newline=''):
    #A function to open a Q-table stored in a csv file
    file = open(file_name, 'r')
    q_temp = dict()
    for row in csv.reader(file, delimiter=';'):
        q_temp[row[0]] = [float(row[k + 1]) for k in range(1296)]

    file.close()
    return (q_temp)


if __name__ == "__main__":
    env = Mastermind()
    #RL = Sarsa(q_table = open_table(file_name="learnt_table_SARSA_passed.csv"), is_qtable=True)
    #Remove the comment mode if you want to use an already saved Q-table.
    RL = Sarsa()

    n_epochs = 100000
    #update(n_epochs) #Remove the comment mode to directly train the agent
    #save_table(RL.q_table) #Remove the comment mode to save the table

    perf_episode = n_epochs // 10000

    for k in range(perf_episode + 1):
        t1 = time.time()
        print('After ', k * 10000, ' epochs')
        test_perf(10000)
        update(10000)
Beispiel #8
0
    def test_check_guess_b(self):
        code = [1,1,2,2]
        guess = [2,2,5,5]

        master = Mastermind(positions=4, colors=6, code=code)
        self.assertEqual(master.check_guess(guess), (0,2))
Beispiel #9
0
    def test_check_guess_wrong_all(self):
        code = [1,1,1,1]
        guess = [2,2,2,2]

        master = Mastermind(positions=4, colors=6, code=code)
        self.assertEqual(master.check_guess(guess), (0,0))
Beispiel #10
0
def testGame(guess, solution):
    a_game = Mastermind()
    a_game.pegs = Mastermind.pegs[:] + ["EMPTY"]
    a_game.guess = guess
    a_game.solution = solution
    return a_game.checkGuess()
Beispiel #11
0
# winner_net = p.run(eval_genomes, 2)
solution = [random.randint(1, 8) for i in range(4)]
solutions = [[1, 3, 4, 2], [1, 4, 1, 4], [2, 1, 1, 3], [4, 1, 3, 2]]

solutions = list(itertools.product([1, 2, 3, 4], repeat=4))
solutions = [list(sol) for sol in solutions]
how_many_win = 0


def game_won(hints_table):
    winner = False
    winning_round = None  # 0, 1, ...
    for i, row in enumerate(hints_table):
        if all(hint == 2 for hint in list(row)):
            winner = True
            winning_round = i
            break
    return winner


for s in solutions:
    mm = Mastermind(4, 8, s)
    hints_table = mm.play_neat_bot(winner_net, win_show=True, show_board=False)
    if game_won(hints_table):
        how_many_win += 1

print("NN won {0} times per {1} possible.".format(how_many_win, 256))

# p = neat.Checkpointer.restore_checkpoint('neat-checkpoint-299')
# p.run(eval_genomes, 10)
Beispiel #12
0
 def test_return_a_list_of_0_and_4_for_all_misplaced_colors(self):
     self.assertEqual(
         Mastermind.call(BASIC_SECRET, ['yellow', 'red', 'green', 'blue']),
         [0, 4])
class MastermindAI():
    def __init__(self):
        self.board = Mastermind(size=4, min_value=1, max_value=3)
        self.board_size = self.board.size
        self.min = 1
        self.max = 9

        self.known = {}
        self.existed = set()
        self.cannot = {i: set() for i in range(self.board_size)}
        self.not_existed = set()

    def set_board(self, board):
        self.board = board
        self.board_size = board.size

    def make_guess(self):
        """
        Make a guess based on current knowledge
        """
        guess = [0] * self.board_size
        for i in range(self.board_size):

            possible_values = []

            #If a position is known to be correct:
            if i in self.known:
                guess[i] = self.known[i]

            #If not, check for other conditions
            else:
                for value in range(self.min, self.max + 1):
                    if value in self.cannot[i] or value in self.not_existed:
                        pass
                    else:
                        possible_values.append(value)

                #Make a random choice from the possible values
                guess[i] = np.random.choice(possible_values)

        return guess

    def solve(self):
        turn = 0
        guesses = []
        print("The board: ", self.board.board)
        done = False
        while not done:

            guess = self.make_guess()
            guesses.append(guess)
            print(f"The AI guesses: {guess}")

            #Check for results
            results = self.board.check(guess)
            print(f"The results the AI gets: {results}")
            if np.all(results == ([2] * self.board_size)):
                done = True
                pass

            #Append new knowledge
            for i, result in enumerate(results):

                if result == 2:
                    self.known[i] = guess[i]
                    self.existed.add(guess[i])
                elif result == 1:
                    self.existed.add(guess[i])
                    self.cannot[i].add(guess[i])
                else:
                    self.not_existed.add(guess[i])

        return guesses
            guess = self.make_guess()
            guesses.append(guess)
            print(f"The AI guesses: {guess}")

            #Check for results
            results = self.board.check(guess)
            print(f"The results the AI gets: {results}")
            if np.all(results == ([2] * self.board_size)):
                done = True
                pass

            #Append new knowledge
            for i, result in enumerate(results):

                if result == 2:
                    self.known[i] = guess[i]
                    self.existed.add(guess[i])
                elif result == 1:
                    self.existed.add(guess[i])
                    self.cannot[i].add(guess[i])
                else:
                    self.not_existed.add(guess[i])

        return guesses


if __name__ == "__main__":
    board = Mastermind(size=4, min_value=1, max_value=4)
    AI = MastermindAI(board)
    AI.solve()
Beispiel #15
0
from mastermind import Mastermind

print("Enter the size of the game:", end="  ")
size = int(input())

mm = Mastermind(size)
mm.declare_pegs()

game = mm.game_over
while not game:
    guess = mm.ask_user()
    mm.print_matches(guess)
    game = mm.game_over
print("You won")
    
Beispiel #16
0
from builtins import print
from util import pretty_name_8_colors, colour_mapping
from mastermind import Mastermind
from argparser import parser
import sys


class InvalidStateException(Exception):
    pass


args = parser.parse_args()
game_solver = Mastermind(args.k, args.n)

print("Welcome to Mastermind interactive solver.")
print(
    "Please think of a code combination containing {} pegs from {} colors ({})."
    .format(args.n, args.k, ", ".join(list(colour_mapping.values())[:args.k])))
print("\n")

# number of red and white pegs from the opponent's response
w, r = 0, 0
all_combinations = game_solver.all_possible_combinations
possible_combinations = game_solver.all_possible_combinations
attempt = game_solver.initial_attempt
num_attempts = 0

try:
    while r != args.n:
        num_attempts += 1
        print("Attempt {} is {}.".format(num_attempts,
Beispiel #17
0
def testGame(guess, solution):
    a_game = Mastermind()
    a_game.pegs = Mastermind.pegs[:] + ['EMPTY']
    a_game.guess = guess
    a_game.solution = solution
    return a_game.checkGuess()
Beispiel #18
0
from mastermind import Mastermind
import random
import numpy as np
MAX_NUMBER = 6
MAX_ITER = 5000

if __name__ == '__main__':
    solution = [random.randint(1,MAX_NUMBER) for i in range(4)]
    mm = Mastermind(4, 8, solution, MAX_NUMBER)
    mm.play_swaszek()
    #results = []
    #for i in range(MAX_ITER):
    #    solution = [random.randint(1,MAX_NUMBER) for i in range(4)]
    #    mm = Mastermind(4, 8, solution, MAX_NUMBER)
    #    res = mm.play_swaszek(show_board=False, show_win=False)
    #    if res >= 0:
    #        results.append(res)

    #results.sort()
    #print("\nPlayed %d rounds" % (MAX_ITER))
    #print("Games won: %d" % (len(results)))
    #print("Games lost: %d" % (MAX_ITER - len(results)))
    #print("Min round: %d" % (min(results)))
    #print("Max round: %d" % (max(results)))
    #print("AVG round: %f" % (sum(results)/len(results)))
Beispiel #19
0
def play_game(bots_list):
    solution = [random.randint(1, 8) for i in range(4)]
    for bot in bots_list:
        mm = Mastermind(4, 8, solution)
        hints_table = mm.play_bot(bot, show_board=False)
        bot.score = fitness_function(hints_table)
Beispiel #20
0
 def test_return_a_list_of_0_and_1_for_one_misplaced_color(self):
     self.assertEqual(
         Mastermind.call(BASIC_SECRET, ['pink', 'pink', 'pink', 'blue']),
         [0, 1])
Beispiel #21
0
        color_names.append(
            input("Please enter an identifier (string) for color " +
                  str(i + 1) + " : "))
else:
    number_of_colors = 7
    code_length = 4
    color_names = [
        "Red", "Blue", "Green", "White", "Black", "Orange", "Purple"
    ]
    print("Color names are " + ",".join(color_names))

should_use_complex_guessing = args.complex_guessing
should_computer_makes_first_guess_randomly = True

print("Game is started!")
puzzle = Mastermind(color_names, code_length)

is_first_action_round = True

# Start cracking the code
while True:
    if not is_first_action_round:
        if should_use_complex_guessing:
            puzzle.predict_by_complex_algorithm()
        else:
            puzzle.make_prediction()
    else:
        if should_computer_makes_first_guess_randomly:
            puzzle.make_prediction()
        else:
            t = input("Please enter a guess").split(" ")
Beispiel #22
0
 def test_return_a_list_of_2_elements(self):
     self.assertEqual(len(Mastermind.call(BASIC_SECRET, BASIC_SECRET)), 2)
Beispiel #23
0
                brush.setStyle(QtCore.Qt.SolidPattern)
                item = QtWidgets.QTableWidgetItem()
                item.setBackground(brush) 
                self.scoreTable.setItem(self.tries, col, item)
        

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Mastermind"))
        self.submitButton.setText(_translate("MainWindow", "Submit"))
        __sortingEnabled = self.colorsTable.isSortingEnabled()
        self.colorsTable.setSortingEnabled(False)
        self.colorsTable.setSortingEnabled(__sortingEnabled)
        __sortingEnabled = self.thisGuessTable.isSortingEnabled()
        self.thisGuessTable.setSortingEnabled(False)
        self.thisGuessTable.setSortingEnabled(__sortingEnabled)
        self.resetButton.setText(_translate("MainWindow", "Reset"))


if __name__ == "__main__":
    import sys
    mastermind = Mastermind([3, 0, 5, 5])
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow, mastermind)
    MainWindow.show()
    sys.exit(app.exec_())


def test_S_creation():
    m = Mastermind(weapons=6, gladiators=4)
Beispiel #25
0
 def test_return_a_list_of_2_integers(self):
     list_result = Mastermind.call(BASIC_SECRET, BASIC_SECRET)
     self.assertEqual(type(list_result[0]), int)
     self.assertEqual(type(list_result[1]), int)
Beispiel #26
0
    def test_check_guess_correct_all(self):
        code = [1,2,3,4]
        guess = [1,2,3,4]

        master = Mastermind(positions=4, colors=6, code=code)
        self.assertEqual(master.check_guess(guess), (4,0))
Beispiel #27
0
 def test_return_a_list_of_4_and_0_for_a_perfect_match(self):
     self.assertEqual(Mastermind.call(BASIC_SECRET, BASIC_SECRET), [4, 0])
Beispiel #28
0
    def test_check_guess_a(self):
        code = [1,2,3,4]
        guess = [4,3,2,1]

        master = Mastermind(positions=4, colors=6, code=code)
        self.assertEqual(master.check_guess(guess), (0,4))
Beispiel #29
0
class Controller(object):

    def __init__(self):
        self.pygame = pg
        self.mastermind = None
        self.view = None
        self.playing = None
        self.carryOn = None

    def setup(self):
        self.pygame.init()
        self.pygame.font.init()
        self.pygame.display.set_caption("TGMastermind!")
        self.mastermind = Mastermind(self)
        self.view = View(self)
        self.playing = True
        self.carryOn = True

    def run_game(self):
        # The clock will be used to control how fast the screen updates
        clock = self.pygame.time.Clock()
        # -------- Main Program Loop -----------
        while self.carryOn:
            # --- Main event loop
            for event in self.pygame.event.get():  # User did something
                if event.type == self.pygame.QUIT:  # If user clicked close
                    self.carryOn = False  # Flag that we are done so we exit this loop
                #print(self.playing)
                if self.playing:
                    self.view.confirm.handle_event(event)
                    self.view.solve.handle_event(event)
                    if event.type == self.pygame.MOUSEBUTTONUP:
                        pos = self.pygame.mouse.get_pos()
                        # Color selection
                        self.view.color_selected(pos)
                        # entering a colored pin
                        self.view.pin_entered(pos)
                elif not self.view.restart:
                    self.view.give_restart_option()
                    self.view.confirm = None
                    self.view.restart.handle_event(event)
                else:
                    self.view.restart.handle_event(event)
                    # if self.view.confirm.collidepoint(pos):
                    #
                    #if self.view.solve.collidepoint(pos):
                        #colors = self.mastermind.solve_mystery()
                        #self.view.solve_mystery(colors)

                # --- Game logic should go here

                # --- Drawing code should go here
                # First, clear the screen to white.
            if self.view.restart:
                self.view.restart.update()
            else:
                self.view.confirm.update()
            self.view.solve.update()


            # --- Go ahead and update the screen with what we've drawn.
            if self.carryOn:
                self.pygame.display.flip()

            # --- Limit to 60 frames per second
            clock.tick(60)
        # Once we have exited the main program loop we can stop the game engine:
        self.pygame.quit()

    def confirm_guess(self):
        hints = self.mastermind.check_input(self.view.current_guess)
        if hints != "WIN":
            self.view.add_hints(hints)

    def solve_mystery(self):
        self.playing = False
        colors = self.mastermind.solve_mystery()
        self.view.solve_mystery(colors)

    def guesser_won(self):
        self.playing = False
        self.view.add_hints(['BLACK', 'BLACK', 'BLACK', 'BLACK'])
        self.view.display_guesser_won(self.mastermind.solve_mystery())

    def guesser_lost(self):
        self.playing = False
        self.view.display_guesser_lost(self.mastermind.solve_mystery())

    def restart(self):
        self.carryOn = False
        self.setup()
        self.view.create_ui()
        self.run_game()
Beispiel #30
0
    def test_check_guess_c(self):
        code = [1,4,4,3]
        guess = [4,4,3,2]

        master = Mastermind(positions=4, colors=6, code=code)
        self.assertEqual(master.check_guess(guess), (1,2))
Beispiel #31
0
 def test_return_a_list_of_2_and_0_for_two_missing_colors(self):
     self.assertEqual(
         Mastermind.call(BASIC_SECRET, ['pink', 'pink', 'red', 'green']),
         [2, 0])
Beispiel #32
0
logger = logging.getLogger('mastermind')
logger.propagate = False
logger.setLevel(logging.INFO)

# create console handler with a higher log level
ch = logging.StreamHandler()

# create formatter and add it to the handlers
formatter = logging.Formatter('%(levelname)s - %(message)s')

ch.setFormatter(formatter)

logger.addHandler(ch)

args = parser.parse_args()
game_solver = Mastermind(args.k, args.n, logger=logger, pretty_printer=pretty_name_8_colors)


def init_worker(shared_counter):
    global counter
    counter = shared_counter


# hack to overcome limitation of Pool.map which is unable to execute instance methods
def f(x):
    res = game_solver.batch_solve(x)
    counter.value += 1
    logger.info("{}/{} {}%".format(counter.value, len(game_solver.all_possible_combinations),
                                   100.0 * counter.value / len(game_solver.all_possible_combinations)))
    return res
Beispiel #33
0
 def test_return_a_list_of_0_and_0_for_a_completely_wrong_match(self):
     self.assertEqual(
         Mastermind.call(BASIC_SECRET, ['pink', 'pink', 'pink', 'pink']),
         [0, 0])
Beispiel #34
0
 def test_return_a_list_of_3_and_0_for_one_missing_color(self):
     self.assertEqual(
         Mastermind.call(BASIC_SECRET, ['pink', 'yellow', 'red', 'green']),
         [3, 0])
Beispiel #35
0
import numpy as np
from ai.bot import Bot
from mastermind import Mastermind
import copy

import random


def shake(bot):
    layers_weights = bot.brain.get_weights()
    #print(layers_weights)
    for layer in range(len(layers_weights)):
        for x in range(len(layers_weights[layer])):
            for y in range(len(layers_weights[layer][x])):
                layers_weights[layer][x][y] *= (10 * np.random.randn() + 1)
    bot.brain.set_weights(layers_weights)
    #print(bot.brain.get_weights())


if __name__ == "__main__":
    bot = Bot(4, 8, 8, name="Marek")
    bot2 = Bot(4, 8, 8, name="Hanka")
    solution = [random.randint(1, 8) for i in range(4)]
    mm = Mastermind(4, 8, solution)
    mm2 = Mastermind(4, 8, solution)
    score = mm.play_bot(bot)
    mm2.play_bot(bot2)
    # print(bot.brain.get_weights())
    # print(bot2.brain.get_weights())
    shake(bot)