예제 #1
0
 def calc_score(self):
     """ calculated the score
     Adds scores if each cell, where each cell has a score according to:
     2 -> 3
     4 -> 9
     8 -> 27
     ...
     """
     return game_logic.score(self.game_model.mat)
예제 #2
0
def my_score(matrix):
    num_empty = len(find_empty_positions(matrix))
    high_val, high_pos =  max(
        max( (val, (i,j)) for j,val in enumerate(row) )
        for i,row in enumerate(matrix)
    )
    # best_in_corner = (
    #     (high_pos[0] == 0 or high_pos[0] == len(matrix)-1) and
    #     (high_pos[1] == 0 or high_pos[1] == len(matrix)-1)
    # )

    return log2(get_adjacent_goodness(matrix)+1) * (num_empty + 1) *  score(matrix)
예제 #3
0
def my_score(matrix):
    return len(find_empty_positions(matrix)) * 10000 + score(matrix)
예제 #4
0
 def get_value(mat):
     # Tuple ordering prefers earlier values.
     # Here we prefer new matricies, then higher-score matricies.
     return (mat != matrix, score(mat))
예제 #5
0
def main(argv):
    parser = argparse.ArgumentParser(
        description=
        'Script that applies a provided algorithm to solve 2048 puzzle.',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument("-d",
                        '--debug',
                        default=False,
                        action='store_true',
                        help='print in debug output')
    parser.add_argument("--gui",
                        default=False,
                        action="store_true",
                        help="shows graphical interface with current status")
    parser.add_argument("--ascii",
                        default=False,
                        action="store_true",
                        help="prints current status to terminal")
    parser.add_argument("--sleep",
                        default=0,
                        help="time to wait between moves [s].")
    parser.add_argument("-s",
                        "--seed",
                        default=None,
                        help="Set seed ot fixed value.")
    parser.add_argument(
        "-a",
        "--algorithm",
        default="example",
        help="which algorithms to run. multiple algorithms can be split by ','."
    )
    parser.add_argument(
        "-r",
        "--runs",
        default=1,
        help="How many games we run per algorithm. Scores are accumulated.")
    parser.add_argument("--replay-dir",
                        default=None,
                        help="The directory where replays get stored.")
    args = parser.parse_args(argv)
    args.runs = int(args.runs)

    if args.debug:
        logging.basicConfig(level=logging.DEBUG)
        logging.info("Set log level to DEBUG")
    else:
        logging.basicConfig(level=logging.INFO)

    algorithms = args.algorithm.split(",")
    results = [{
        'algorithm': algorithm,
        'score': 0,
        'Nmoves': 0
    } for algorithm in algorithms]

    if args.replay_dir:
        if not os.path.exists(args.replay_dir):
            os.makedirs(args.replay_dir)

    for runIndex in range(args.runs):
        seed = args.seed
        if not args.seed:
            random.seed(time.time())
            seed = [
                random.choice(game_logic.all_directions) for i in range(17)
            ]

        for result, algorithm in zip(results, algorithms):
            replay = []

            logging.debug("Initializing game")
            gamegrid = initializeGame(seed=seed, showGUI=args.gui)

            logging.debug("loading algorithm " + algorithm)
            random.seed(4)
            alg = importlib.import_module("algorithms." + algorithm)

            logging.debug("starting loop")
            done = False
            Nmoves = 0
            NnoMoves = 0
            while not done:
                logging.debug("Getting next move from algorithm")
                old_mat = gamegrid.game_model.mat
                move = alg.get_next_move(old_mat)
                gamegrid.ai_move(move)
                new_mat = gamegrid.game_model.mat

                replay.append(
                    (old_mat, move, new_mat, game_logic.score(new_mat)))
                if old_mat == new_mat:
                    done = True
                    continue

                Nmoves += 1
                NnoMoves = 0

                time.sleep(float(args.sleep))

                # update game grid
                if args.gui:
                    gamegrid.update()
                if args.ascii:
                    print("status: (Score = {})".format(gamegrid.calc_score()))
                    print(
                        tabulate.tabulate(gamegrid.game_model.mat,
                                          tablefmt="grid"))

                if gamegrid.game_over():
                    done = True
                    break

            score = gamegrid.calc_score()
            result["score"] += score
            result["Nmoves"] += Nmoves

            if args.runs <= 1:
                print(
                    "GAME OVER. Final score: {:8.0f} after {:5.0f} moves (algorithm: {})."
                    .format(score, Nmoves, algorithm))

            # save replay
            if args.replay_dir:
                replay_file_name = os.path.join(
                    args.replay_dir, '{}-{}.2048-replay-v1'.format(
                        algorithm,
                        datetime.datetime.utcnow().strftime(
                            '%Y-%m-%d-%H-%M-%S')))
                with open(replay_file_name, 'w') as f:
                    for line in replay:
                        f.write(repr(line) + '\n')

        printSummary(results)

    if args.gui:
        input("Press Enter to terminate.")