Ejemplo n.º 1
0
    def update_empty_intersection(self):
        n = self.board_size * self.board_size
        ownership = [UNDECIDED] * n
        visited = BitSet(n)
        adjacent_chains = BitSet(n)
        for x in range(self.board_size):
            for y in range(self.board_size):
                z = x * self.board_size + y
                if self._color[z] != EMPTY or visited.contains(z):
                    continue

                self._chain_size[z] = 0
                adjacent_to_black, adjacent_to_white = False, False
                adjacent_chains.clear()

                q = Queue(n)
                q.enqueue((x, y))
                visited.add(z)
                while not q.is_empty():
                    x, y = q.dequeue()
                    for dx, dy in _directions:
                        if self.on_board(x + dx, y + dy):
                            if self.color(x + dx, y + dy) == BLACK:
                                adjacent_chains.add(self.find(x + dx, y + dy))
                                adjacent_to_black = True
                            elif self.color(x + dx, y + dy) == WHITE:
                                adjacent_chains.add(self.find(x + dx, y + dy))
                                adjacent_to_white = True
                            elif not visited.contains(
                                (x + dx) * self.board_size + y + dy):
                                q.enqueue((x + dx, y + dy))
                                visited.add((x + dx) * self.board_size + y +
                                            dy)
                    self._parent[x * self.board_size + y] = z
                    self._chain_size[z] += 1

                if (adjacent_to_black and adjacent_to_white) \
                        or len(adjacent_chains) == 0:
                    ownership[z] = UNDECIDED
                elif len(adjacent_chains) == 1:
                    if adjacent_to_black:
                        ownership[z] = BLACK_EYE
                    else:
                        ownership[z] = WHITE_EYE
                else:
                    if adjacent_to_black:
                        ownership[z] = BLACK_OWNED
                    else:
                        ownership[z] = WHITE_OWNED

        return ownership
Ejemplo n.º 2
0
def bfs(initial, goal_test, successors):
    frontier = Queue()
    frontier.push(Node(initial))
    explored = {initial}

    while not frontier.empty:
        node: Node = frontier.pop()

        if goal_test(node.state):
            return node

        for parent in successors(node.state):
            if parent in explored:
                continue

            explored.add(node.state)
            frontier.push(Node(parent, node))
    return None
Ejemplo n.º 3
0
    def _remove(self, x, y):
        self._liberties[self.find(x, y)] = None

        n = self.board_size * self.board_size
        z = x * self.board_size + y
        color = self._color[z]

        # insert (x, y) into the queue, and mark it as "visited but not
        # processed" (color = _GRAY)
        # we abuse the _color array to store the BFS state here:
        #   - color = EMPTY: processed
        #   - color = BLACK: not visited (for black stones)
        #   - color = WHITE: not visited (for white stones)
        #   - color = _GRAY: visited (i.e., in queue) but not processed
        q = Queue(n)
        q.enqueue((x, y))
        self._color[z] = _GRAY
        adjacent_opponent_chains = SmallSet(4)
        while not q.is_empty():
            x, y = q.dequeue()
            adjacent_opponent_chains.clear()
            for dx, dy in _directions:
                if self.on_board(x + dx, y + dy):
                    # insert all the own adjacent stones that are not
                    # visited into the queue
                    if self.color(x + dx, y + dy) == color:
                        q.enqueue((x + dx, y + dy))
                        self._color[(x + dx) * self.board_size + y +
                                    dy] = _GRAY
                    # save opponent's stone chains that are adjacent to
                    # this new empty intersection
                    if self.color(x + dx, y + dy) == -color:
                        adjacent_opponent_chains.add(self.find(x + dx, y + dy))
            # the new empty intersection (x, y) provides liberty to its
            # adjacent stone chains
            z = x * self.board_size + y
            for c in adjacent_opponent_chains:
                if self._liberties[c] is None:
                    self._liberties[c] = BitSet(n)
                self._liberties[c].add(z)
            self._color[z] = EMPTY
Ejemplo n.º 4
0
 def setUp(self):
     # print("Initializing queue")
     self.queue = Queue(8, 0, initial_iter=self.initial_list)
Ejemplo n.º 5
0
 def __init__(self, conf):
     self._regret_frac = conf.RESIGN_REGRET_FRAC
     self._histories = Queue(conf.NUM_RESIGN_SAMPLES)
     self._threshold = -1.0
Ejemplo n.º 6
0
 def __init__(self):
     self.stack = Stack()
     self.queue = Queue()
     self.meccaMap = MaccaMap()
     self.start_place = self.meccaMap.set_starting_place()
     self.target_place = self.meccaMap.set_target_place()
 def __init__(self):
     """
     Initialize your data structure here.
     """
     self.input_queue = Queue()
     self.output_queue = Queue()
Ejemplo n.º 8
0
class Game():
    def __init__(self):
        tm.Living.spawn()

    scoring = {0: 0, 1: 40, 2: 100, 3: 300, 4: 1200}
    score = 0

    s = Stack()
    q = Queue()
    holding_bag = Queue()

    GRAY = (150, 150, 150)
    DGRAY = (80, 80, 80)
    WHITE = (255, 255, 255)
    CYAN = (0, 255, 255)
    RED = (255, 0, 0)
    GREEN = (0, 255, 0)
    BLUE = (0, 0, 255)
    ORANGE = (255, 165, 0)
    YELLOW = (255, 255, 0)
    PURPLE = (148, 0, 211)

    pg.font.init()
    fontSize = 25
    main_font = pg.font.SysFont("arial", fontSize)
    BoardHeight, BoardWidth = 20, 10
    WIDTH, HEIGHT = 600, 800
    PrevXPadd, PrevYPadd = 160, 140
    zoom = 40
    start = timeit.default_timer()
    times = 0
    run = True
    end = False

    @classmethod
    def hold(cls, curr):
        if cls.times == 1:
            if len(cls.holding_bag) != 0:
                curr.x, curr.y, curr.ghost.x = 3, 0, 3
                cls.q.add(cls.holding_bag.current())
                cls.holding_bag.add(curr)
            else:  # if empty
                curr.x, curr.y, curr.ghost.x = 3, 0, 3
                cls.holding_bag.add(curr)
                tm.Living.spawn()

    @classmethod
    def update_window(cls, win):
        win.fill((0, 0, 0))
        cls.run_board(win)
        current = cls.q.current()
        cls.preview(current, win, active_tetro=True)
        cls.preview(current.ghost, win, active_tetro=True)

        for m, n in enumerate(range(1, 4)):
            cls.preview(tm.Tetromino(cls.s.peek(n=n)[m]),
                        win, cls.WIDTH - cls.PrevXPadd,
                        cls.PrevYPadd * n * (0.3 * n))

        if len(cls.holding_bag) != 0:
            cls.preview(cls.holding_bag.current(), win,
                        cls.WIDTH - cls.PrevXPadd, cls.HEIGHT - 200)
        else:
            cls.rect(win, cls.DGRAY, cls.WIDTH - cls.PrevXPadd,
                     cls.HEIGHT - 200)

        score_text = Game.main_font.render("Score = {}".format(Game.score), 1,
                                           Game.WHITE)

        win.blit(score_text,
                 ((Game.BoardWidth * Game.zoom), score_text.get_height()))

        pg.display.update()

    @classmethod
    def run_board(cls, win):
        for i in range(cls.BoardHeight):
            for j in range(cls.BoardWidth):
                if tm.Tetromino.board_matrix[i][j] == 0:
                    color = cls.GRAY
                    border = 1
                else:
                    color = tm.Tetromino.colors[tm.Tetromino.board_matrix[i]
                                                [j]]
                    border = 0

                pg.draw.rect(win, color,
                             [j * cls.zoom, i * cls.zoom, cls.zoom, cls.zoom],
                             border)

    @classmethod
    def clear_board(cls):
        def end():
            # if any letters present at the top
            if any(tm.Tetromino.board_matrix[0]):
                return True

        # If all elements in board_matrix's row are != 0, clear them
        update = [tm.Tetromino.board_matrix[i] for i in range(cls.BoardHeight) \
                                    if not all(tm.Tetromino.board_matrix[i])]

        before_clean = len(tm.Tetromino.board_matrix)
        after_clean = len(update)
        clear_amount = before_clean - after_clean

        cls.score += cls.scoring[clear_amount]

        for _ in range(clear_amount):
            update[:0] = [[0 for _ in range(cls.BoardWidth)]]

        tm.Tetromino.board_matrix = update

        if end() and not cls.end:
            cls.end = True
            db.update_db(cls.score)
            cls.run = False

    @classmethod
    def rect(
        cls,
        win,
        color,
        x=1,
        y=1,
        j_mult=1,
        i_mult=1,
    ):
        pg.draw.rect(win, color, [
            x + (j_mult * cls.zoom), y +
            (i_mult * cls.zoom), cls.zoom - 1, cls.zoom - 1
        ])

    @staticmethod
    def delta_t():
        x = lambda a: eval("%.{}f".format(1) % a)
        if x(timeit.default_timer() - Game.start) % 1 == 0:
            Game.start -= 0.1
            return True

    @staticmethod
    def preview(current, win, x=1, y=1, active_tetro=False):
        for i in range(4):
            for j in range(4):
                temp = i * 4 + j
                if temp in current.current_shape():
                    if not active_tetro:
                        Game.rect(win, current.color, x, y, j, i)
                    else:
                        Game.rect(win,
                                  current.color,
                                  j_mult=current.x + j,
                                  i_mult=current.y + i)
Ejemplo n.º 9
0
    def _level_order_traversal(self, starting_node=None, include_none=True):
        """
        Traverses the binary tree from top level to bottom and saves data/height/depth for testing purpose

        Args:
            starting_node (TreeNode): traverse the subtree rooted at given starting node
            include_none (bool): True if including None node in binary tree

        Returns:
            data_array ([3-tuple]): [(data saved in node, height, depth)]
        """
        data_array = []

        # returns empty list if the binary tree is empty
        if self._root is None:
            return data_array

        # traverse from root if starting node is not given
        if starting_node is None:
            starting_node = self._root

        queue = Queue()
        # (data, height, depth, left child, right child)
        queue.enqueue((starting_node.data(), starting_node.height(),
                       starting_node.depth(), starting_node.left_child(),
                       starting_node.right_child()))

        while not queue.empty():
            top_node = queue.dequeue()

            if top_node[0] is not None:
                # if it's a non-trival node, append data/height/depth
                data_array.append((top_node[0], top_node[1], top_node[2]))
            else:
                data_array.append(None)

            # if the node is not on the deepest level, left and right child can be added into queue and visited soon
            if top_node[2] < self.depth():
                top_node_left_child, top_node_right_child = top_node[
                    3], top_node[4]

                entry = [None, top_node[1] - 1, top_node[2] + 1, None, None]
                if top_node_left_child is not None:
                    entry[0] = top_node_left_child.data()
                    entry[3] = top_node_left_child.left_child()
                    entry[4] = top_node_left_child.right_child()
                queue.enqueue(tuple(entry))

                entry = [None, top_node[1] - 1, top_node[2] + 1, None, None]
                if top_node_right_child is not None:
                    entry[0] = top_node_right_child.data()
                    entry[3] = top_node_right_child.left_child()
                    entry[4] = top_node_right_child.right_child()
                queue.enqueue(tuple(entry))

        # if include_none == False, filter out the None element
        if not include_none:
            data_array = list(filter(lambda x: x is not None, data_array))

        # remove all None at the end of list since they are trival and not informative
        while data_array[-1] is None:
            data_array.pop()

        return data_array