Esempio n. 1
0
def main():
    for iteration in range(ITERATION):
        print("Iteration: " + str(iteration + 1))
        start = time.time()
        step = 0
        matrix = np.zeros((4, 4), dtype=np.int)
        matrix = logic.add_two(matrix)
        while True:
            matrix = logic.add_two(matrix)
            if logic.game_state(matrix) == 'lose':
                break
            if logic.game_state(matrix) == 'lose':
                break
            matrix = montecarlo.getMove(matrix, NUM_BACKGROUND_RUNS)
            step += 1
            # move=montecarlo.getMove(matrix, NUM_BACKGROUND_RUNS)
            # # print("got a move " + str(move))
            # matrix=montecarlo.moveGrid(matrix,move)
            # step+=1
        print(matrix)
        print("Step= " + str(step))
        print("Max= " + str(2**np.max(matrix)))
        print("Score= " + str(logic.getScore(matrix)))
        print('Depth= ' + str(NUM_BACKGROUND_RUNS))
        print('Time= ' + str(time.time() - start))
        print('')
        stat.append((step, 2**np.max(matrix), logic.getScore(matrix)))
Esempio n. 2
0
def main():
    for iteration in range(ITERATION):
        print("Iteration: " + str(iteration + 1))
        start = time.time()
        step = 0
        matrix = logic.new_game()
        matrix = logic.add_two(matrix)
        while True:
            matrix = logic.add_two(matrix)
            if logic.gameOver(matrix):
                break
            # print("given this board")
            # logic.printBoard(matrix)
            move = ExpectiMax.getMove(matrix, DEPTH)
            matrix = ExpectiMax.moveGrid(matrix, move)
            # print("expectimax recommends this move " + str(move))
            # print("resulting in this board")
            # logic.printBoard(matrix)
            step += 1

        print("Step= " + str(step))
        print("Max= " + str(2**logic.getMax(matrix)))
        print("Score= " + str(logic.getScore(matrix)))
        print('Depth= ' + str(DEPTH))
        print('Time= ' + str(time.time() - start))
        print('')
Esempio n. 3
0
def main():
    for iteration in range(ITERATION):
        print("Iternaton: " + str(iteration + 1))
        step = 0
        matrix = np.zeros((4, 4))
        matrix = logic.add_two(matrix)
        while True:
            matrix = logic.add_two(matrix)
            if logic.game_state(matrix) == 'lose':
                break
            while True:
                move = ExpectiMax.getMove(matrix, DEPTH)
                if move == "'w'":
                    newMatrix, _ = logic.up(matrix)
                if move == "'a'":
                    newMatrix, _ = logic.left(matrix)
                if move == "'s'":
                    newMatrix, _ = logic.down(matrix)
                if move == "'d'":
                    newMatrix, _ = logic.right(matrix)
                if ExpectiMax.isSame(newMatrix, matrix) == False:
                    matrix = newMatrix
                    break
            step += 1
        print("Step= " + str(step))
        print("Max= " + str(np.max(matrix)))
        print("Score= " + str(logic.getScore(matrix)))
        print('')
        stat.append((step, np.max(matrix), logic.getScore(matrix)))
    np.savetxt("stat.txt", stat)
Esempio n. 4
0
def eval_genome(genome, config):
    """
	This function will be run in threads by ThreadedEvaluator.  It takes two
	arguments (a single genome and the genome class configuration data) and
	should return one float (that genome's fitness).
	"""

    # Initialize game
    game_matrix = logic.new_game(4)
    game_matrix = logic.add_two(game_matrix)
    game_matrix = logic.add_two(game_matrix)

    # Flatten function
    flatten = lambda l: [item for sublist in l for item in sublist]
    net = neat.nn.FeedForwardNetwork.create(genome, config)

    # Action functions
    actions = [logic.up, logic.down, logic.left, logic.right]
    fitness = 0
    for i in range(3):
        while logic.game_state(game_matrix) == 'not over':
            # Flatten game matrix
            flat_matrix = flatten(game_matrix)

            # Predict moves
            output = net.activate(flat_matrix)
            # Copy list and sort predictions from lowest to highest
            sorted_output = sorted(enumerate(output), key=lambda x: x[1])
            # Get max index from output list and use assosiated function from actions
            max_index = sorted_output[-1][0]
            new_game_matrix = actions[max_index](game_matrix)
            # If move is not valid use different direction
            if not new_game_matrix[1]:
                # Get second max index from output list and use assosiated function from actions
                second_max_index = sorted_output[-2][0]
                # TODO if output has same values all directions are not checked
                new_game_matrix = actions[second_max_index](game_matrix)
            # If move is not valid use different direction
            if not new_game_matrix[1]:
                # Get third max index from output list and use assosiated function from actions
                third_max_index = sorted_output[-3][0]
                new_game_matrix = actions[third_max_index](game_matrix)
            # If move is not valid use different direction
            if not new_game_matrix[1]:
                # Get fourth max index from output list and use assosiated function from actions
                fourth_max_index = sorted_output[-4][0]
                new_game_matrix = actions[fourth_max_index](game_matrix)

            # Set game matrix to updated matrix from (game, true) tuple
            game_matrix = new_game_matrix[0]
            # Generate new tile
            if logic.game_state(game_matrix) == 'not over':
                game_matrix = logic.add_two(game_matrix)
        #print(game_matrix)
        # Fitness function is a summation of all values on game board
        fitness += sum(flatten(game_matrix))
    return fitness / 3
Esempio n. 5
0
    def init_matrix(self):
        #TODO: IST DIE 90% 10% Wahrscheinlichkeit einer 4 nicht drinnen oder was?
        self.matrix = logic.new_game(4)
        self.history_matrixs = list()
        self.matrix = logic.add_two(self.matrix)
        self.matrix = logic.add_two(self.matrix)

        #TODO: Name anpassen zb. state_
        self.matrix_old = self.matrix
        self.powers_of_two_matrix = np.zeros((4, 4))
Esempio n. 6
0
 def __init__(self, game=None):
     self.score = 0
     self.true_score = 0
     self.invalid_moves = 0
     self.total_moves = 0
     if game is not None:
         self.matrix = game
     else:
         self.matrix = logic.new_game(4)
         logic.add_two(self.matrix)
         logic.add_two(self.matrix)
Esempio n. 7
0
	def __init__(self, random = False):
		self.matrix = logic.new_game(4)
		self.matrix = logic.add_two(self.matrix)
		self.matrix = logic.add_two(self.matrix)

		if(random):
			self.create_random()

		self.state = 'not over'

		self.score = 0
Esempio n. 8
0
 def left(self):
     self.matrix, done, bonus_score = logic.left(self.matrix)
     self.total_moves += 1
     if done:
         logic.add_two(self.matrix)
         self.score += bonus_score
         self.true_score += bonus_score
     else:
         self.invalid_moves += 1
         self.score -= 1
         bonus_score = -1
     return bonus_score
Esempio n. 9
0
 def key_down(self, event):
     key = repr(event.char)
     if key == c.KEY_BACK and len(self.history_matrixs) > 1:
         self.matrix = self.history_matrixs.pop()
         self.update_grid_cells()
         # print('back on step total step:', len(self.history_matrixs))
     elif key in self.commands:
         #AA: Perform key command
         self.matrix, done = self.commands[repr(event.char)](self.matrix)
         if done:
             #AA: Add a 2 to a random location?
             self.matrix = logic.add_two(self.matrix)
             # record last move
             self.history_matrixs.append(self.matrix)
             self.update_grid_cells()
             done = False
             # print("pastDone")
             if logic.game_state(self.matrix) == 'win':
                 self.grid_cells[1][1].configure(
                     text="You", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
                 self.grid_cells[1][2].configure(
                     text="Win!", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
             elif logic.game_state(self.matrix) == 'lose':
                 # print("LOOOOOOOOOOOOOSER")
                 self.grid_cells[1][1].configure(
                     text="You", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
                 self.grid_cells[1][2].configure(
                     text="Lose!", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
Esempio n. 10
0
    def key_down(self, key):
        # key = repr(event.char)
        if self.done == 1:
            # time.sleep(SLEEP_TIME)
            self.score = self.getScore(self.matrix)
            max = np.max(np.max(self.matrix))
            stat.append((self.score, max, self.step))
            self.quit()

        if key == c.KEY_BACK and len(self.history_matrixs) > 1:
            self.matrix = self.history_matrixs.pop()
            self.update_grid_cells()
            print('back on step total step:', len(self.history_matrixs))
        elif key in self.commands:
            self.matrix, done = self.commands[key](self.matrix)
            if done:
                self.matrix = logic.add_two(self.matrix)
                # record last move
                self.history_matrixs.append(self.matrix)
                self.update_grid_cells()
                done = False
                if logic.game_state(self.matrix) == 'win':
                    self.grid_cells[1][1].configure(
                        text="You", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
                    self.grid_cells[1][2].configure(
                        text="Win!", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
                    self.done = 1
                if logic.game_state(self.matrix) == 'lose':
                    self.grid_cells[1][1].configure(
                        text="You", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
                    self.grid_cells[1][2].configure(
                        text="Lose!", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
                    self.done = 1
            self.step += 1
Esempio n. 11
0
 def key_down(self, event):
     key = repr(event.char)
     if key == c.KEY_BACK and len(self.history_matrixs) > 1:
         self.matrix = self.history_matrixs.pop()
         self.update_grid_cells()
         print('back on step total step:', len(self.history_matrixs))
     elif key in self.commands:
         self.matrix, done = self.commands[repr(event.char)](self.matrix)
         if done:
             self.matrix = logic.add_two(self.matrix)
             # record last move
             self.history_matrixs.append(self.matrix)
             self.update_grid_cells()
             if logic.game_state(self.matrix) == 'win':
                 self.grid_cells[1][1].configure(
                     text="You", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
                 self.grid_cells[1][2].configure(
                     text="Win!", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
             if logic.game_state(self.matrix) == 'lose':
                 self.grid_cells[1][1].configure(
                     text="You", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
                 self.grid_cells[1][2].configure(
                     text="Lose!", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
     elif key == c.KEY_R:
         self.reset()
Esempio n. 12
0
    def key_down(self, event):
        key = repr(event.char)
        if key == c.KEY_BACK and len(self.history_matrixs) > 1:
            self.matrix = self.history_matrixs.pop()
            self.update_grid_cells()
        elif key in self.commands:
            self.matrix, done = self.commands[repr(event.char)](self.matrix)
            if done:
                self.matrix = logic.add_two(self.matrix)
                # record last move
                self.history_matrixs.append(self.matrix)
                self.update_grid_cells()
                if logic.game_state(self.matrix) == 'win':
                    self.grid_cells[1][1].configure(
                        text="You", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
                    self.grid_cells[1][2].configure(
                        text="Win!", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
                if logic.game_state(self.matrix) == 'lose':
                    self.grid_cells[1][1].configure(
                        text="Try", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
                    self.grid_cells[1][2].configure(
                        text="Again!", bg=c.BACKGROUND_COLOR_CELL_EMPTY)

        # Scoring: runs even after loss or win
        RightView.setCurrentScore(cfg.wrapper.app_gui.right_view,
                                  cfg.currentScore)
        if (cfg.currentScore > cfg.highScore):
            cfg.highScore = cfg.currentScore
            RightView.setHighScore(cfg.wrapper.app_gui.right_view)
Esempio n. 13
0
 def act(self, event):
     key = event
     if key in commands:
         new_matrix, done = commands[key](self.matrix)
         if done:
             new_matrix = logic.add_two(new_matrix)
             # record last move
             done = False
     return new_matrix
Esempio n. 14
0
 def key_down(self, dir):
     key = dir
     if key in self.commands:
         self.matrix, done, n, g = self.commands[dir](self.matrix)
         self.score += n * 2
         if done:
             self.matrix = logic.add_two(self.matrix)
         self.history_matrixs.append(self.matrix)
     return logic.game_state(self.matrix)
Esempio n. 15
0
    def key_down(self, event):
        key = event
        game_done = False
        game_result = False
        temp = 0
        current_state = self.matrix

        if key == c.KEY_BACK and len(self.history_matrixs) > 1:
            self.matrix = self.history_matrixs.pop()
            self.update_grid_cells()
            print('back on step total step:', len(self.history_matrixs))

        elif key in self.game.commands:
            self.matrix, done = self.game.commands[key](self.matrix)

            if done:
                self.matrix = logic.add_two(self.matrix)
                # record last move
                self.history_matrixs.append(self.matrix)
                self.update_grid_cells(self.game)

                done = False
                if logic.game_state(self.matrix) == 'win':
                    game_done = True
                    game_result = True
                    self.game.grid_cells[1][1].configure(
                        text="You", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
                    self.game.grid_cells[1][2].configure(
                        text="Win!", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
                if logic.game_state(self.matrix) == 'lose':
                    game_done = True
                    game_result = False
                    self.game.grid_cells[1][1].configure(
                        text="You", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
                    self.game.grid_cells[1][2].configure(
                        text="Lose!", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
        if (game_done and game_result):
            self.score = sum(np.array(self.matrix).flatten())
        elif (game_done and not (game_result)):
            self.score = -1 * sum(np.array(self.matrix).flatten())
        else:
            if (self.score != sum(np.array(self.matrix).flatten())):

                for i in range(4):
                    for j in range(4):
                        if (self.matrix[i][j] == 2 * current_state[i][j]):
                            temp += self.matrix[i][j]
                self.score = sum(np.array(self.matrix).flatten())
                return self.matrix, game_done, temp

            else:

                # print(0)
                return self.matrix, game_done, -100

        return self.matrix, game_done, self.score
Esempio n. 16
0
def takeAction(game, action):
    done = False
    if action in action_map:
        game, done = action_map[action](game)
        if done:
            game = add_two(game)
    else:
        logging.error("Invalid action '{}'".format(action))

    return game, done
Esempio n. 17
0
def randomPolicyUntilGameOver(grid, numBackgroundRuns):
    score = 0
    for i in range(numBackgroundRuns):
        curGrid = grid.copy()
        while True:
            curGrid = logic.add_two(curGrid)
            board_list = randomMove(curGrid)
            if not board_list:
                break
            curGrid = random.choice(board_list)
        score += logic.getScore(curGrid)
    return score
Esempio n. 18
0
def main():
    f = open("expectimax2.txt", "w+")
    for iteration in range(ITERATION):
        print("Iteration: " + str(iteration + 1))
        start = time.time()
        step = 0
        matrix = np.zeros((4, 4), dtype=np.int)
        matrix = logic.add_two(matrix)
        while True:
            matrix = logic.add_two(matrix)
            if logic.game_state(matrix) == 'lose':
                break

            move = ExpectiMax.getMove(matrix, DEPTH)
            matrix = ExpectiMax.moveGrid(matrix, move)
            step += 1

        f.write("Step %d, max %d, Score %d, \r\n" %
                (step, 2**np.max(matrix), logic.getScore(matrix)))
        f.flush()

    f.close()
Esempio n. 19
0
def iteration(iter):
    start = time.time()
    step = 0
    matrix = np.zeros((4, 4), dtype=np.int)
    matrix = logic.add_two(matrix)
    while True:
        matrix = logic.add_two(matrix)
        if logic.game_state(matrix) == 'lose':
            break

        move = ExpectiMax.getMove(matrix, DEPTH)
        matrix = ExpectiMax.moveGrid(matrix, move)
        step += 1

    print("Iteration: " + str(iter + 1))
    print("Step= " + str(step))
    print("Max= " + str(2**np.max(matrix)))
    print("Score= " + str(logic.getScore(matrix)))
    print('Depth= ' + str(DEPTH))
    print('Time= ' + str(time.time() - start))
    print('')

    return (step, 2**np.max(matrix), logic.getScore(matrix))
Esempio n. 20
0
 def check_if_done(self, done):
     if done:
         self.matrix = logic.add_two(self.matrix)
         # record last move
         self.history_matrixs.append(self.matrix)
         self.update_grid_cells()
         done = False
         if logic.game_state(self.matrix) == 'win':
             #TODO: Hier den limit für 2048 löschen um zu schauen wie weit er kommen wird
             self.grid_cells[1][1].configure(
                 text="You", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
             self.grid_cells[1][2].configure(
                 text="Win!", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
         if logic.game_state(self.matrix) == 'lose':
             self.quit()
             self.destroy()
             return True
Esempio n. 21
0
    def step(self, action):
        self.steps += 1
        if self.human and self.random:
            time.sleep(0.01)
        action = action if not self.random else random.randint(0, 3)
        # if self.human:
        #     print(f'Action: {["up", "down", "left", "right"][action]}')
        self.matrix, valid, self.rew = self.commands[str(action)](self.matrix)
        if valid:
            self.matrix = logic.add_two(self.matrix)
        else:
            self.rew -= 10
        state = logic.game_state(self.matrix)
        if state == 'win':
            self.rew += 10000
        elif state == 'lose':
            self.rew -= 1000
        self.score += self.rew

        info = {}
        return self.get_observation(), self.get_reward(), self.is_done(), info
Esempio n. 22
0
 def action(self, event):
     key = event
     if key == c.KEY_BACK and len(self.history_matrixs) > 1:
         self.matrix = self.history_matrixs.pop()
         print('back on step total step:', len(self.history_matrixs))
     elif key in self.commands:
         self.matrix, done = self.commands[key](self.matrix)
         if done:
             self.matrix = logic.add_two(self.matrix)
             # record last move
             self.history_matrixs.append(self.matrix)
             done = False
             if logic.game_state(self.matrix) == 'win':
                 self.is_win = True 
                 self.is_over = True
             if logic.game_state(self.matrix) == 'lose':
                 self.is_win = False 
                 self.is_over = True
     self.step =self.step+1
     self.max_value = max(max(row) for row in self.matrix)
     self.sum_value = sum(sum(np.array(self.matrix)))
     return self 
Esempio n. 23
0
	def movement(self, move):
		if move == 'w':
			self.matrix, done, points = logic.up(self.matrix)
		elif move == 's':
			self.matrix, done, points = logic.down(self.matrix)
		elif move == 'a':
			self.matrix, done, points = logic.left(self.matrix)
		elif move == 'd':
			self.matrix, done, points = logic.right(self.matrix)
		else:
			done = False
			print('Error, not a valid move')
			points = 0

		self.score += points

		self.state = logic.game_state(self.matrix)

		if done and self.state == 'not over':
			self.matrix = logic.add_two(self.matrix)

		return points
Esempio n. 24
0
    def action(self, event):
        key = event
        if key == c.KEY_BACK and len(self.history_matrixs) > 1:
            self.matrix = self.history_matrixs.pop()
            # self.update_grid_cells()
            print('back on step total step:', len(self.history_matrixs))
        elif key in self.commands:
            self.matrix, done = self.commands[key](self.matrix)
            if done:
                self.matrix = logic.add_two(self.matrix)
                # record last move
                self.history_matrixs.append(self.matrix)
                # self.update_grid_cells()
                done = False
                if logic.game_state(self.matrix) == 'win':
                    self.grid_cells[1][1].configure(
                        text="You", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
                    self.grid_cells[1][2].configure(
                        text="Win!", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
                    # self.update_idletasks()

                    # time.sleep(1)
                    self.is_win = True
                    self.is_over = True

                if logic.game_state(self.matrix) == 'lose':
                    self.grid_cells[1][1].configure(
                        text="You", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
                    self.grid_cells[1][2].configure(
                        text="Lose!", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
                    # self.update_idletasks()

                    # time.sleep(1)
                    self.is_win = False
                    self.is_over = True
        self.step = self.step + 1
        self.max_value = max(max(row) for row in self.matrix)
        self.sum_value = sum(sum(np.array(self.matrix)))
        return self
Esempio n. 25
0
    def key_down(self, event):
        self.matrix, done = self.commands[event](self.matrix)

        state = self.game_over(self.matrix)

        if state != 'continue':
            if state == 'win':
                self.grid_cells[1][1].configure(
                    text="You", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
                self.grid_cells[1][2].configure(
                    text="Win!", bg=c.BACKGROUND_COLOR_CELL_EMPTY)

            elif state == 'lose':
                self.grid_cells[1][1].configure(
                    text="You", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
                self.grid_cells[1][2].configure(
                    text="Lose!", bg=c.BACKGROUND_COLOR_CELL_EMPTY)

            self.update_idletasks()
        else:
            self.matrix = logic.add_two(self.matrix)
            self.update_grid_cells()
Esempio n. 26
0
    def play(self, strategy):
        while logic.game_state(self.matrix) == 'not over':
            if strategy == 0:
                key = np.random.randint(4)
            elif strategy == 1:
                key = self.predict_maximin(self.matrix)
            if key in self.commands:
                self.matrix, done, score = self.commands[key](self.matrix)
                self.score += score
                # print(self.score)
                if done:

                    self.matrix = logic.add_two(self.matrix)
                    # record last move
                    self.history_matrixs.append(self.matrix)
                    done = False
                    if logic.game_state(self.matrix) == 'win':
                        print('you win')
                        print(self.score)
                        print(self.matrix)
                    if logic.game_state(self.matrix) == 'lose':
                        print('you lose')
                        print(self.score)
                        print(self.matrix)
Esempio n. 27
0
 def stateOfGame(self):
     self.playSound(APP_FOLDER + c.SOUNDS_DICT["move"])
     self.matrix = logic.add_two(self.matrix)
     # record last move
     self.history_matrixs.append(self.matrix)
     #print(self.history_matrixs[-1])
     self.update_grid_cells()
     if logic.game_state(self.matrix) == 'win':
         if logic.winNum != 65535:
             print("num: " + str(logic.winNum))
             for key, value in c.SOUNDS_DICT.items():
                 if key == str(logic.winNum):
                     self.playSound(APP_FOLDER + value)
             winLooseDlg.WinLooseDialog(self).dialogTypes("WIN")
             print("Κερδίσες")
         else:
             winLooseDlg.WinLooseDialog(self).dialogTypes("ENDGAME")
     if logic.game_state(self.matrix) == 'lose':
         self.playSound(APP_FOLDER + c.SOUNDS_DICT["lose"])
         winLooseDlg.WinLooseDialog(self).dialogTypes("LOOSE")
         print("Έχασες")
     self.lScore.setText(str(c.SCORE))
     if int(self.lHiScore.text()) < int(self.lScore.text()):
         self.lHiScore.setText(self.lScore.text())
Esempio n. 28
0
 def key_down(self, event):
     key = repr(event.char)
     if key == c.KEY_BACK and len(self.history_matrixs) > 1:
         self.matrix = self.history_matrixs.pop()
         self.update_grid_cells()
         print('back on step total step:', len(self.history_matrixs))
     elif key in self.commands:
         self.matrix, done = self.commands[repr(event.char)](self.matrix)
         if done:
             self.matrix = logic.add_two(self.matrix)
             # record last move
             self.history_matrixs.append(self.matrix)
             self.update_grid_cells()
             done = False
             if logic.game_state(self.matrix) == 'win':
                 self.grid_cells[1][1].configure(
                     text="You", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
                 self.grid_cells[1][2].configure(
                     text="Win!", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
             if logic.game_state(self.matrix) == 'lose':
                 self.grid_cells[1][1].configure(
                     text="You", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
                 self.grid_cells[1][2].configure(
                     text="Lose!", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
Esempio n. 29
0
 def Update_ByCommand(self, Command):
     self.matrix, done = self.Commands_AI[Command](self.matrix)
     if done:
         self.matrix = logic.add_two(self.matrix)
         # record last move
         self.history_matrixs.append(self.matrix)
         self.update_grid_cells()
         done = False
         if logic.game_state(self.matrix) == 'win':
             self.grid_cells[1][1].configure(
                 text="You", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
             self.grid_cells[1][2].configure(
                 text="Win!", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
             return "Win"
         if logic.game_state(self.matrix) == 'lose':
             self.grid_cells[1][1].configure(
                 text="You", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
             self.grid_cells[1][2].configure(
                 text="Lose!", bg=c.BACKGROUND_COLOR_CELL_EMPTY)
             return "Lose"
     else:
         print("Hareket Uygulanamıyor")
         return "Stop"
     return "Cont"
Esempio n. 30
0
    def key_down(self, event):
        print("KEY DOWN")
        with open('winner.pkl', 'rb') as filehandler:
            local_dir = os.path.dirname(__file__)
            config_path = os.path.join(local_dir, 'config-feedforward')
            config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
                                 neat.DefaultSpeciesSet,
                                 neat.DefaultStagnation, config_path)
            winner = pickle.load(filehandler)
            net = neat.nn.FeedForwardNetwork.create(winner, config)

            # Initialize game
            game_matrix = logic.new_game(4)
            game_matrix = logic.add_two(game_matrix)
            game_matrix = logic.add_two(game_matrix)
            self.matrix = game_matrix
            self.update_grid_cells()

            # Flatten function
            flatten = lambda l: [item for sublist in l for item in sublist]

            # Action functions
            actions = [logic.up, logic.down, logic.left, logic.right]
            move_counter = 0
            while logic.game_state(game_matrix) == 'not over':
                move_counter += 1
                # Flatten game matrix
                flat_matrix = flatten(game_matrix)

                # Predict moves
                output = net.activate(flat_matrix)
                # Copy list and sort predictions from lowest to highest
                sorted_output = sorted(enumerate(output), key=lambda x: x[1])
                # Get max index from output list and use assosiated function from actions
                max_index = sorted_output[-1][0]
                new_game_matrix = actions[max_index](game_matrix)
                # If move is not valid use different direction
                if not new_game_matrix[1]:
                    # Get second max index from output list and use assosiated function from actions
                    second_max_index = sorted_output[-2][0]
                    new_game_matrix = actions[second_max_index](game_matrix)
                # If move is not valid use different direction
                if not new_game_matrix[1]:
                    # Get third max index from output list and use assosiated function from actions
                    third_max_index = sorted_output[-3][0]
                    new_game_matrix = actions[third_max_index](game_matrix)
                # If move is not valid use different direction
                if not new_game_matrix[1]:
                    # Get fourth max index from output list and use assosiated function from actions
                    fourth_max_index = sorted_output[-4][0]
                    new_game_matrix = actions[fourth_max_index](game_matrix)

                # Set game matrix to updated matrix from (game, true) tuple
                game_matrix = new_game_matrix[0]
                if logic.game_state(game_matrix) == 'not over':
                    game_matrix = logic.add_two(game_matrix)
                self.matrix = game_matrix
                self.history_matrixs.append(self.matrix)
                self.update_grid_cells()
                # Generate new tile
            print(f"Number of moves was {move_counter}")
Esempio n. 31
0
 def init_matrix(self):
     self.matrix = logic.new_game(4)
     self.history_matrixs = list()
     self.matrix = logic.add_two(self.matrix)
     self.matrix = logic.add_two(self.matrix)
Esempio n. 32
0
 def init_matrix(self):
     self.matrix = logic.new_game(4)
     self.history_matrixs = list()
     self.matrix = logic.add_two(self.matrix)
     self.matrix = logic.add_two(self.matrix)