Exemple #1
0
            g,
            "took:",
            time.strftime("%H:%M:%S", time.gmtime(time.time() - start_time)),
        )
        print(best, "\n")

        with open(
                build_absolute_path(
                    "learning/deap/pso/downstack/PSOoutput.txt"),
                "a") as text_file:
            text_file.writelines([log, "\n", str(best)])

        if g % FREQ == 0:
            # Fill the dictionary using the dict(key=value[, ...]) constructor
            cp = dict(population=pop, generation=g, best=best)

            with open("PSO_checkpoint.pkl", "wb") as cp_file:
                pickle.dump(cp, cp_file)

    return pop, logbook, best


NGEN = 500
population_size = 100
game_attempts = 5
FREQ = 1

if __name__ == "__main__":
    main(checkpoint=build_absolute_path(
        "learning/deap/pso/downstack/PSO_checkpoint.pkl"))
            if combo_counter:
                combos.append(combo_counter)
                sent = True
            if detailed_combos[-1]:
                detailed_combos.append([])
            combo_counter = 0

        return [
            field, combo_counter, combo_time, combos, detailed_combos, sent
        ]


if __name__ == "__main__":

    ## Initialize piece sequence
    with open(build_absolute_path("base/pieces.txt"), "r") as file:
        sequence = file.read().replace("\n", "")
        # print(sequence)
        # sequence = sequence.strip("\n")
    seed = random.randint(0, int(len(sequence) / 4))

    piece_count = 1
    current_tetromino = Tetromino.create(sequence[piece_count])

    while True:
        next_tetromino = Tetromino.create(sequence[piece_count + 1])

        if piece_count == 1:
            ## Initialize Player 1
            player1_recieved_garbage = 0
            player1_combo_counter = 0
Exemple #3
0
    def run_game(n, render=False):
        """
        Runs a Tetris simulation until either 1) The max piece count is reached or 2) The game was lost

        Parameters: weights: scoring function weights array (1x29)
        Returns: piece_count: pieces placed prior to game end

        """
        field = Field()
        with open(build_absolute_path("base/pieces.txt"), "r") as file:
            sequence = file.read().replace("\n", "")
            # print(sequence)
            # sequence = sequence.strip("\n")

        piece_count = 1
        max_piece_count = 500
        exit = 1
        seed = random.randint(0, int(len(sequence) / 4))
        # seed = 0
        sequence = sequence[seed:]

        current_tetromino = Tetromino.create(sequence[piece_count])
        clears_count = random.uniform(0.001, 1)

        while exit == 1:
            try:
                next_tetromino = Tetromino.create(sequence[piece_count + 1])

                ## GET BEST MOVE ##
                t0 = time.time()
                best_drop = Optimizer.best_move(field, current_tetromino,
                                                next_tetromino, n)
                t1 = time.time()

                rotation = best_drop[1]
                column = best_drop[2]
                current_tetromino.rotate(rotation)

                ## RENDER & DEBUG ##
                if render == True:
                    if piece_count % 1 == 0:
                        print(field)
                        print(
                            "GETTING BEST DROP TOOK",
                            "{0:.4f}".format(t1 - t0),
                            "seconds",
                        )
                        print(
                            "Current Piece:",
                            sequence[piece_count],
                            "NEW Best Rotation:",
                            rotation,
                            "NEW Best Column:",
                            column,
                        )
                        print("Next Piece:", sequence[piece_count + 1])
                        print("piece_count:", piece_count, "clears_count:",
                              clears_count)
                        heuristics = field.heuristics()
                        print(
                            "gaps",
                            heuristics[0],
                            "bumpiness",
                            heuristics[1],
                            "bog1",
                            heuristics[2],
                            "bog2",
                            heuristics[3],
                            "tall_holes",
                            heuristics[4],
                            "field_height",
                            heuristics[5],
                            "\n" + "stack gaps",
                            heuristics[6],
                            "stack height",
                            heuristics[7],
                            "sum_bumps_above_two",
                            heuristics[8],
                            "trans_above_gap1",
                            heuristics[9],
                        )
                        # input()

                        ## PLACE BLOCK AND GET LINE CLEARS ##
                returns = field.drop(current_tetromino, column)
                if returns[1] > 0:
                    clears_count += returns[1]

                    ## SET UP NEXT INSTANCE ##
                previous_tetromino = current_tetromino
                current_tetromino = next_tetromino

                if piece_count % 18 == 0:
                    for i in range(4):
                        field.add_garbage()

                        ## CHECK FOR GAME END ##
                    if field.height() > 20:
                        score = [piece_count]
                        return score
                        break

                if piece_count == max_piece_count:
                    score = [piece_count]
                    return score
                    break

                piece_count += 1

            except IndexError:
                if render == True:
                    print("GAME OVER")
                score = [piece_count]
                return score
                break
Exemple #4
0
def leave_room():
    pyautogui.press("escape")
    time.sleep(0.3)
    target = Classifier.template_match(build_absolute_path("Images/yes.png"))
    pyautogui.moveTo(target)
    pyautogui.doubleClick(target)
Exemple #5
0

while True:
    with keyboard.Listener(on_press=on_press) as listener:

        while break_program == False:
            while count > -5:
                while count == -2 and break_program == False:

                    ############# STARTING GAME MODE ################

                    if sys.argv[1] == "-maserati":
                        os.system("open /Applications/cultris4.app")
                        print("maserati mode selected")
                        maserati = Classifier.template_match(
                            build_absolute_path("Images/maserati.png")
                        )
                        if maserati == False:
                            maserati = Classifier.template_match(
                                build_absolute_path("Images/maserati2.png")
                            )
                        if maserati == False:
                            print("ERROR finding maserati template match")
                            count = -100
                            break
                        pyautogui.moveTo(maserati)
                        pyautogui.doubleClick(maserati)
                        time.sleep(0.25)

                        No = Classifier.template_match(
                            build_absolute_path("Images/No.png")
Exemple #6
0
    def run_game(weights, render=False):
        """
		Runs a Tetris simulation until either 1) The max piece count is reached or 2) The game was lost

		Parameters: weights: scoring function weights array (1x29)
		Returns: piece_count: pieces placed prior to game end

		"""
        field = Field()
        with open(build_absolute_path("base/pieces.txt"), "r") as file:
            sequence = file.read().replace("\n", "")
            # print(sequence)
            # sequence = sequence.strip('\n')

        piece_count = 1
        max_piece_count = 100000
        exit = 1
        seed = random.randint(0, int(len(sequence) / 4))
        sequence = sequence[seed:]

        current_tetromino = Tetromino.create(sequence[piece_count])

        clears_count = random.uniform(0.001, 1)

        while exit == 1:
            try:
                next_tetromino = Tetromino.create(sequence[piece_count + 1])

                best_drop = Optimizer.get_best_drop(
                    field, current_tetromino, next_tetromino, weights
                )
                # best_drop = Optimizer.get_optimal_drop(field, current_tetromino, next_tetromino, weights)
                # opt = best_drop[0]

                rotation = best_drop[1]
                column = best_drop[2]

                current_tetromino.rotate(rotation)
                returns = field.drop(current_tetromino, column)
                if returns[1] > 0:
                    clears_count += 1

                previous_tetromino = current_tetromino
                current_tetromino = next_tetromino

                if piece_count == max_piece_count:
                    score = [piece_count + random.uniform(0.001, 1), clears_count]
                    return score
                    break

                if render == True:
                    if piece_count % 10 == 0:
                        print(field)
                        print(
                            "piece_count:", piece_count, "clears_count:", clears_count
                        )
                        # time.sleep(0.040)

                piece_count += 1

            except:
                score = [piece_count + random.uniform(0.001, 1), clears_count]
                return score
                break
Exemple #7
0
    def run_game(n, render=False):
        """
        Runs a Tetris simulation until either:
        1) The max piece count is reached
        2) The game was lost

        Parameters: weights: scoring function weights array (1x29)
        Returns: piece_count: pieces placed prior to game end
        """
        field = Field()
        with open(build_absolute_path("base/pieces.txt"), "r") as file:
            sequence = file.read().replace("\n", "")
            # print(sequence)
            # sequence = sequence.strip("\n")

        piece_count = 1
        max_piece_count = 500
        exit = 1
        seed = random.randint(0, int(len(sequence) / 4))
        combo_counter = 0
        combo_time = 0
        combos = []
        detailed_combos = [[]]
        # seed = 0
        sequence = sequence[seed:]

        current_tetromino = Tetromino.create(sequence[piece_count])
        clears_count = random.uniform(0.001, 1)

        while exit == 1:
            try:
                next_tetromino = Tetromino.create(sequence[piece_count + 1])

                if settings.mode == "upstack":
                    if (field.height() > 12 or field.count_gaps() > 2
                            or field.max_bump() > 6):
                        # print(
                        #     "MODE SWITCH TO DOWNSTACK",
                        #     # field.height(),
                        #     # field.count_gaps(),
                        # )
                        settings.mode = "downstack"
                if settings.mode == "downstack":
                    if combo_counter > 6 or combo_counter + combo_time > 8.5:
                        settings.combo = True
                        # print("COMBO ACTIVE")
                    else:
                        settings.combo = False
                    if (field.height() < 4 and field.count_gaps() < 3
                            and combo_counter < 3):
                        # print(
                        #     "MODE SWITCH TO UPSTACK",
                        #     # field.height(),
                        #     # field.count_gaps(),
                        # )
                        settings.mode = "upstack"

                ## GET BEST MOVE ##
                t0 = time.time()
                best_drop = Optimizer.best_move(
                    field=field,
                    tetromino=current_tetromino,
                    next_tetromino=next_tetromino,
                    n=n,
                    combo_time=combo_time,
                    combo_counter=combo_counter,
                )
                t1 = time.time()

                rotation = best_drop[1]
                column = best_drop[2]
                current_tetromino.rotate(rotation)

                ## RENDER & DEBUG ##
                if render:
                    if piece_count % 1 == 0:
                        print(field)
                        print(
                            "GETTING BEST DROP TOOK",
                            "{0:.4f}".format(t1 - t0),
                            "seconds",
                        )
                        print(
                            "Current Piece:",
                            sequence[piece_count],
                            "NEW Best Rotation:",
                            rotation,
                            "NEW Best Column:",
                            column,
                        )
                        print("Next Piece:", sequence[piece_count + 1])
                        print("piece_count:", piece_count, "clears_count:",
                              clears_count)
                        heuristics = field.heuristics()
                        # print(
                        #     "gaps",
                        #     heuristics[0],
                        #     "bumpiness",
                        #     heuristics[1],
                        #     "bog1",
                        #     heuristics[2],
                        #     "bog2",
                        #     heuristics[3],
                        #     "tall_holes",
                        #     heuristics[4],
                        #     "field_height",
                        #     heuristics[5],
                        #     "\n" + "stack gaps",
                        #     heuristics[6],
                        #     "stack height",
                        #     heuristics[7],
                        #     "sum_bumps_above_two",
                        #     heuristics[8],
                        #     "trans_above_gap1",
                        #     heuristics[9],
                        # )
                        # input()

                ## PLACE BLOCK AND GET LINE CLEARS ##
                returns = field.drop(current_tetromino, column)
                if returns[1] > 0:
                    clears_count += returns[1]
                    detailed_combos[-1].append(returns[1])

                combo_time, combo_counter = timer(combo_time, returns[1],
                                                  combo_counter)

                ## SET UP NEXT INSTANCE ##
                current_tetromino = next_tetromino
                combo_time = (
                    combo_time -
                    0.0900634319213337  # Average compute time for executing moves
                    -
                    0.024662579271626208  # Average compute time for field image processing
                    - 0.007466887216673049  # time to check game over
                    -
                    (t1 - t0
                     )  # time to get/compute best move based on nodes + depth
                )

                if combo_time < 0:
                    combo_time = 0
                    if combo_counter:
                        combos.append(combo_counter)
                    if detailed_combos[-1]:
                        detailed_combos.append([])
                    combo_counter = 0
                # print("combo_time", combo_time)
                # print("TOTAL LINES SENT:", compute_score(combos))

                if piece_count % 21 == 0:
                    for i in range(4):
                        field.add_garbage()

                    ## CHECK FOR GAME END ##
                    if field.height() > 20:
                        return piece_count

                if piece_count == max_piece_count:
                    return compute_score(detailed_combos)

                piece_count += 1

            except IndexError:
                if render:
                    print("GAME OVER")
                    print("Combos: ", combos)
                    print("Detailed Combos: ", detailed_combos)
                return compute_score(detailed_combos)
Exemple #8
0
def main(checkpoint=None):
    try:
        # A file name has been given, then load the data from the file
        with open(checkpoint, "rb") as cp_file:
            cp = pickle.load(cp_file, encoding="bytes")
            pop = cp["population"]
            g = cp["generation"]
            best_ind = cp["best_ind"]
            random.setstate(cp["rndstate"])
            fits = [ind.fitness.values[0] for ind in pop]
    except:
        # Start a new evolution
        # random.seed(64)
        pop = toolbox.population(population_size)
        g = 0
        print("Start of evolution")

        # Evaluate the entire population
        fitnesses = list(toolbox.map(toolbox.evaluate, pop))
        for ind, fit in zip(pop, fitnesses):
            ind.fitness.values = fit

        print("  Evaluated %i individuals" % len(pop))

        # Extracting all the fitnesses of
        fits = [ind.fitness.values[0] for ind in pop]

    # Begin the evolution
    while max(fits) < 100000 and g < NGEN:
        # A new generation
        g = g + 1
        print("-- Generation %i --" % g)

        # Select the next generation individuals
        offspring = toolbox.select(pop, len(pop))
        # Clone the selected individuals
        offspring = list(map(toolbox.clone, offspring))

        # Apply crossover and mutation on the offspring
        for child1, child2 in zip(offspring[::2], offspring[1::2]):

            # cross two individuals with probability CXPB
            if random.random() < CXPB:
                toolbox.mate(child1, child2)

                # fitness values of the children
                # must be recalculated later
                del child1.fitness.values
                del child2.fitness.values

        for mutant in offspring:

            # mutate an individual with probability MUTPB
            if random.random() < MUTPB:
                toolbox.mutate(mutant)
                del mutant.fitness.values

        if g % RECALCGEN == 0:

            # recalculate all individuals fitness every kth generation
            for ind in offspring:
                del ind.fitness.values

        # Evaluate the individuals with an invalid fitness
        invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
        fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)
        for ind, fit in zip(invalid_ind, fitnesses):
            ind.fitness.values = fit

        print("  Evaluated %i individuals" % len(invalid_ind))

        # The population is entirely replaced by the offspring
        pop[:] = offspring

        # Gather all the fitnesses in one list and print the stats
        fits = [ind.fitness.values[0] for ind in pop]

        length = len(pop)
        mean = sum(fits) / length
        sum2 = sum(x * x for x in fits)
        std = abs(sum2 / length - mean**2)**0.5

        print("  Min %s" % min(fits))
        print("  Max %s" % max(fits))
        print("  Avg %s" % mean)
        print("  Std %s" % std)
        best_ind = tools.selBest(pop, 1)[0]
        print("Best individual so far is %s, %s" %
              (best_ind, best_ind.fitness.values))
        with open(
                build_absolute_path(
                    "learning/deap/pso/downstack/GAoutput.txt"),
                "a") as text_file:
            text_file.writelines(["\n", str(best_ind)])

        if g % FREQ == 0:
            # Fill the dictionary using the dict(key=value[, ...]) constructor
            cp = dict(
                population=pop,
                generation=g,
                best_ind=best_ind,
                rndstate=random.getstate(),
            )

            with open("GA_checkpoint.pkl", "wb") as cp_file:
                pickle.dump(cp, cp_file)

    print("-- End of (successful) evolution --")

    best_ind = tools.selBest(pop, 1)[0]
    print("Best individual is %s, %s" % (best_ind, best_ind.fitness.values))