Пример #1
0
 def print(self, message="", **kwargs):
     """Print this state to stdout using provided helpers"""
     board_dict = {}
     for sq, n in self.stacks.items():
         board_dict[sq] = "({:X})".format(n)
     for sq in self.all_targets.keys():
         board_dict[sq] = "[X]"
     print_board(board_dict, message, **kwargs)
Пример #2
0
 def print(self, message="", **kwargs):
     board = collections.defaultdict(str)
     for t in self.upper_tokens:
         board[t.hex] += t.symbol.upper()
     for t in self.lower_tokens:
         board[t.hex] += t.symbol.lower()
     for x, s in board.items():
         board[x] = f"({s})"
     for x in ALL_HEXES - self.all_hexes:
         board[x] = "BLOCK"
     print_board(board, message, **kwargs)
Пример #3
0
def run():
    BOARD_SIZE = 8
    MAX_NUM_WHITE = 3
    MAX_NUM_BLACK = 12

    MAX_STACK_WHITE = 3
    MAX_STACK_BLACK = 12

    data = {"white": [], "black": []}

    num_stack_white = random.randint(1, MAX_STACK_WHITE)

    num_stack_black = random.randint(1, MAX_STACK_BLACK)
    #num_stack_black = random.randint(1, MAX_STACK_BLACK)

    occupied = []

    for stack in range(num_stack_white):
        if MAX_NUM_WHITE <= 0: break

        n = random.randint(1, MAX_NUM_WHITE)
        x = random.randint(0, 7)
        y = random.randint(0, 7)

        if (x, y) not in occupied:
            occupied.append((x, y))
            data["white"].append([n, x, y])
            MAX_NUM_WHITE -= n

    for stack in range(num_stack_black):
        if MAX_NUM_BLACK <= 0: break

        n = random.randint(1, min(2, MAX_NUM_BLACK))
        x = random.randint(0, 7)
        y = random.randint(0, 7)

        if (x, y) not in occupied:
            occupied.append((x, y))
            data["black"].append([n, x, y])
            MAX_NUM_BLACK -= n

    #print(data)
    print_board(get_grid_format(data))

    #accepted = input("Accept this arrangement? (y/n): \n")

    if True:
        json_form = json.dumps(data)

        with open("test.json", 'w') as f:
            f.write(json_form)
Пример #4
0
def main():
    board_data_file = os.path.join(dir_path, "board-util-data.json")
    with open(sys.argv[1]) as file, open(board_data_file) as board_file:
        BoardUtil.initialize(json.load(board_file))

        data = json.load(file)
        board = Board(data)

        print_board(board.board, compact=False)

        # comment and uncomment to switch methods
        # BoardUtil.print_solution(wastar(board))
        # BoardUtil.print_solution(bfs(board))
        # BoardUtil.print_solution(dfs(board))
        q_learning(board)
Пример #5
0
def board(data):
    whites, blacks = data['white'], data['black']

    board_dict = dict()

    for white in whites:
        if white[0] > 1:
            board_dict[tuple(white[1:])] = "W" + str(white[0])
        else:
            board_dict[tuple(white[1:])] = "W"

    for black in blacks:

        if black[0] > 1:
            board_dict[tuple(black[1:])] = "B" + str(black[0])
        else:
            board_dict[tuple(black[1:])] = "B"

    print_board(board_dict)
Пример #6
0
def main():
    with open(sys.argv[1]) as file:
        data = json.load(file)

    # TODO: find and print winning action sequence

    start = time.time()

    board = data
    print_board(game.get_grid_format(board), "Start")

    solution = ai.search(data)

    for action, stack_from, stack_to in solution:
        if action == "move":
            board = game.move(stack_from, stack_to, board)
            if DEBUG: print_board(game.get_grid_format(board))
            else:
                print_move(stack_to[N_TOKENS], stack_from[X_POS],
                           stack_from[Y_POS], stack_to[X_POS], stack_to[Y_POS])

        if action == "boom":
            board = game.boom(stack_from, board)
            if DEBUG: print_board(game.get_grid_format(board))
            else: print_boom(stack_from[X_POS], stack_from[Y_POS])

    print("# Length of solution ", len(solution))
    print("# Execution time: ", time.time() - start)
Пример #7
0
def find_boom_dict(chunks):
    boom_dict={}
    #find boom value for board
    for i in range(8):
        for j in range(8):
            boom_dict[(i,j)]=0

    for i in range(8):
        for j in range(8):

            point=(0,i,j)
            for c in chunks:
                for p in c:
                    if is_close(p, point):
                        boom_dict[(i,j)]+=1
                        break
                for p in c:
                    if i == p[1] and j == p[2]:
                        boom_dict[(i, j)] = NEGINF


    print_board(boom_dict, compact= False)
    return boom_dict
Пример #8
0
 def print(self):
     output = {}
     for key in self.board_dict:
         key_new = tuple(self.__array_to_axial(key[0], key[1]))
         output[key_new] = ','.join(self.board_dict[key])
     print_board(output)
Пример #9
0
def main():
    with open(sys.argv[1]) as file:
        data = json.load(file)

    board_dict = {}

    whites = data['white']  # array of arrays
    number_of_whites = 0
    for piece in whites:
        number_of_whites += piece[0]
    print("number of whites: " + str(number_of_whites))

    blacks = data['black']  # array of arrays

    place_pieces(board_dict, whites, blacks)

    killZone = set()
    find_killZones(board_dict, whites, blacks, killZone)

    place_pieces(board_dict, whites, blacks)

    print_board(board_dict)
    print(killZone)

    # find a combination of white positions within the killzone that when they explode they kill every black piece
    # results gives us the positions for white pieces
    possible_white_positions = list(combinations(killZone, number_of_whites))
    for tupl in possible_white_positions:
        for piece in blacks:
            if ((piece[1], piece[2]) in tupl):
                possible_white_positions.remove(tupl)
                break

    combinations_success = set(
    )  # combinations of postiton that kill all blacks
    for tupl in possible_white_positions:
        if (kills_all_blacks(tupl, blacks)):
            combinations_success.add(tupl)

    print("combinations that killed all the black pieces:")
    print(combinations_success)
    print(combinations_success.issuperset({((1, 1), (1, 1), (1, 1))}))

    for e in combinations_success:
        for n in range(number_of_whites):
            board_dict[(e[n][0], e[n][1])] = "!"
    print_board(board_dict)

    # Finally, move whites to the optimum positions in the least amount of moves
    #1st find combination that is closest
    #2nd move peices there

    comb_dsitances = set()
    for ntuple in combinations_success:
        comb_dsitances.add(d_comb_whites(ntuple, whites, number_of_whites))

    print(comb_dsitances)
    print(min(comb_dsitances))

    mintuple = tuple()
    for ntuple in combinations_success:
        if (d_comb_whites(ntuple, whites,
                          number_of_whites) == (min(comb_dsitances))):
            mintuple = ntuple

    print(mintuple)

    #which picece is closest to which point?
    #goal_dict = closest(mintuple, whites, number_of_whites)
    goal_dict = closest(mintuple, whites)

    #last step is to actually move the pices to their optimum position and BOOM!
    endconfig = list()
    for piece in whites:
        spos = (piece[1], piece[2])
        endpos = goal_dict[(piece[1], piece[2])]
        # print("start position: {}, goal position: {}".format((piece[1],piece[2]),goal_dict[(piece[1],piece[2])]))
        # print(goal_dict[(piece[1],piece[2])][0])
        while (not (spos == endpos)):
            if (spos[0] > endpos[0] and
                (not (board_dict.get({(spos[0] - 1, spos[1])})[0] == 'b'))):
                print_move(1, spos[0], spos[1], spos[0] - 1, spos[1])
                spos = (spos[0] - 1, spos[1])
            if (spos[0] < endpos[0]):
                print_move(1, spos[0], spos[1], spos[0] + 1, spos[1])
                spos = (spos[0] + 1, spos[1])
            if (spos[1] > endpos[1]):
                print_move(1, spos[0], spos[1], spos[0], spos[1] - 1)
                spos = (spos[0], spos[1] - 1)
            if (spos[1] < endpos[1]):
                print_move(1, spos[0], spos[1], spos[0], spos[1] + 1)
                spos = (spos[0], spos[1] + 1)
        endconfig.append(spos)
    for spos in endconfig:
        print_boom(spos[0], spos[1])
Пример #10
0
def main():
    try:
        with open(sys.argv[1]) as file:
            data = json.load(file)
    except IndexError:
        print("usage: python3 -m search path/to/input.json", file=sys.stderr)
        sys.exit(1)

    # TODO:
    # Find and print a solution to the board configuration described
    # by `data`.
    # Why not start by trying to print this configuration out using the
    # `print_board` helper function? (See the `util.py` source code for
    # usage information).

    #All possible operators for each piece.
    moves = [(1, -1), (1, 0), (0, 1), (-1, 1), (-1, 0), (0, -1)]

    upper = data['upper']
    lower = data['lower']
    block = data['block']

    #reformatting data from ('p', x, y) -> ('p', (x, y))
    new_upper = []
    for each in data['upper']:
        new_upper.append(
            (each[0], (each[1], each[2])))  #perhaps make coords np.array

    data['upper'] = new_upper

    new_lower = []
    for each in data['lower']:
        new_lower.append((each[0], (each[1], each[2])))

    data['lower'] = new_lower

    #changing format of data['block'] as '' is not necessary.
    blocks = []
    for cell in block:
        blocks.append((cell[1], cell[2]))

    data['block'] = blocks

    #to draw board
    board_dict = {}
    print(blocks)
    for cell in blocks:
        board_dict[(cell[0], cell[1])] = "[ ]"

    for cell in new_upper:
        board_dict[(cell[1][0], cell[1][1])] = cell[0]
    for cell in new_lower:
        board_dict[(cell[1][0], cell[1][1])] = cell[0]

    start = time.time()
    moves = generate_moves(data, moves)

    for each in moves:
        print("h")
        for e in each:
            print(e)

    # if len(moves) == 3:
    #     x = moves[0]
    #     y = moves[1]
    #     z = moves[2]

    #     all_possible_moves = np.array(np.meshgrid(x, y ,z)).T.reshape(-1,3)
    # elif len(moves) == 2:
    #     x = moves[0]
    #     y = moves[1]

    #     all_possible_moves = np.array(np.meshgrid(x, y)).T.reshape(-1,2)
    # else:
    #     all_possible_moves = moves[0]

    all_possible_moves = list(itertools.product(*moves))

    print(all_possible_moves)
    print(len(all_possible_moves))
    end = time.time()
    print(end - start)

    print_board(board_dict, "", ansi=False)
Пример #11
0
def best_first_search(ally_dict, enemy_dict, block_dict):
    visited = []
    path = [(ally_dict, enemy_dict)]
    initial_enemies = len(enemy_dict)
    frontier = PriorityQueue()

    priority = calculate_priority(ally_dict, enemy_dict, initial_enemies,
                                  block_dict)
    frontier.put((0, priority, ally_dict, enemy_dict, path))

    while not frontier.empty():
        depth, priority, ally_dict, enemy_dict, path = frontier.get()
        print_board(ally_dict)
        if has_won(enemy_dict):
            return path + [
                (copy.deepcopy(ally_dict), copy.deepcopy(enemy_dict))
            ]

        visited += [(copy.deepcopy(ally_dict), copy.deepcopy(enemy_dict))]
        states = PriorityQueue()
        for state in get_next_states(ally_dict, enemy_dict, block_dict):
            next_ally_dict, next_enemy_dict = state
            priority = calculate_priority(next_ally_dict, next_enemy_dict,
                                          initial_enemies, block_dict)
            print(priority.priority)
            states.put((priority, next_ally_dict, next_enemy_dict))

        depth -= 1
        while not states.empty():
            priority, next_ally_dict, next_enemy_dict = states.get()

            if (next_ally_dict, next_enemy_dict) not in visited:
                if has_won(next_enemy_dict):
                    return path + [(copy.deepcopy(next_ally_dict),
                                    copy.deepcopy(enemy_dict))]
                new_path = path + [
                    (copy.deepcopy(next_ally_dict), copy.deepcopy(enemy_dict))
                ]
                frontier.put((depth, priority, next_ally_dict, next_enemy_dict,
                              new_path))

    return path


# ally_dict = {(0,0): ["r0", "p0", "s0"],
#              (0,1): ["r1", "p1"],
#              (0,2): ["r2", "r3"],
#              (0,3): ["r4"],
#              (0,4): ["p2"],
#              (0,5): ["s1", "p3"],
#              (0,6): ["s2"],
#              (0,7): ["s3", "p4"]
#             }

# enemy_dict = {(0,0): ["r", "p", "s"],
#               (0,1): ["p", "p"],
#               (0,2): ["p"],
#               (0,3): ["r"],
#               (0,5): ["p"],
#               (0,6): ["r"],
#               (0,7): ["r"]
#              }

# print(ally_dict)
# print(enemy_dict)
# battle(ally_dict, enemy_dict)
# print(ally_dict)
# print(enemy_dict)

# ally_dict = {(0,0): ["r"],
#              (1,0): ["r", "p"],
#             }

# enemy_dict = {(0,0): ["r", "p", "s"],
#               (0,1): ["p", "p"],
#               (0,2): ["p"],
#              }

# block_dict = {(2,1): [""],
#               (0,-1): [""],
#               (-1,0): [""]
#              }

# ally_dict = {(-2,4): ["p"]
#              }

# enemy_dict = {(-2,4): ["r"]
#               }

# block_dict = {}

# print(can_win(ally_dict, enemy_dict))

# print(get_next_states(ally_dict, enemy_dict, block_dict))

# prev_state_dict = defaultdict(list)
# for state in path:
#     ally_dict, enemy_dict = state

#     # Populate the dictonary with states of each tokens in current state
#     curr_state_dict = defaultdict(list)
#     for key, values in ally_dict.items():
#         for token in values:
#             path_dict[token] += key

#     # First state hence no previous path
#     if len(prev_state_dict) == 0:
#         continue
#     else:
#         for token in curr_state_dict:
#             if len()
Пример #12
0
def main():
    try:
        with open(sys.argv[1]) as file:
            data = json.load(file)
    except IndexError:
        print("usage: python3 -m search path/to/input.json", file=sys.stderr)
        sys.exit(1)

    # TO-DO:
    # Find and print a solution to the board configuration described
    # by `data`.
    # Why not start by trying to print this configuration out using the
    # `print_board` helper function? (See the `util.py` source code for
    # usage information).

    print(data)
    ally_dict, enemy_dict, block_dict = read_file(data)

    print_board(ally_dict)
    print_board(enemy_dict)
    path = best_first_search(ally_dict, enemy_dict, block_dict)
    print(path)

    # prev_state_dict = defaultdict(list)
    # for state in path:
    #     ally_dict, enemy_dict = state

    #     # Populate the dictonary with states of each tokens in current state
    #     curr_state_dict = defaultdict(list)
    #     for key, values in ally_dict.items():
    #         for token in values:
    #             path_dict[token] += key

    #     # First state hence no previous path
    #     if len(prev_state_dict) == 0:
    #         continue
    #     else:
    #         for token in curr_state_dict:
    #             if len()

    for state in path:
        ally, enemy = state
        board_dict = {}
        # Add lower token (enemies) onto the board to be printed
        for key, values in enemy.items():
            if len(values) == 1:
                string = f"({values[0]})"
            else:
                string = "("
                for value in values:
                    string = string + value + ")"
            board_dict[key] = string
        # Add upper token (allies) onto the board to be printed
        for key, values in ally.items():
            if key not in board_dict:
                if len(values) == 1:
                    string = f"({values[0].upper()})"
                else:
                    string = "("
                    for value in values:
                        string = string + value.upper() + ")"
                board_dict[key] = string
            else:
                for value in values:
                    board_dict[key] = board_dict[key] + value.upper() + ")"
        # Add the blocks onto the board to be printed
        for key, value in block_dict.items():
            board_dict[key] = "[ ]"
        print_board(board_dict, "Next State")
Пример #13
0
 def __str__(self):
     return util.print_board(self.board_dict, unicode=True, compact=False,
                             return_as_string=True)