def detect(self, frame):
        height, width, ch = frame.shape
        center = (width / 2, height / 2)
        regions_of_interest, _ = self.preprocess.get_interest_regions(frame)

        for roi in regions_of_interest:
            utils.draw_red_box(frame, roi)

        # path = self.classifier.classify(frame, regions_of_interest)
        if regions_of_interest:
            path = utils.get_max_area(regions_of_interest)

        else:
            path = None

        path_shape = self.get_shape(path, self.shape_buffer)

        if (path == None):
            self.directions = [0, 0]
            self.found = False
            w, h = 0, 0
        else:
            x, y, w, h = path
            utils.draw_blue_box(frame, path)
            self.directions = utils.get_directions(center, x, y, w, h)
            self.directions.append(0)
            self.found = True
        return (self.found, self.directions, path_shape, (w, h))
Exemple #2
0
    def detect(self, frame):
        if frame is not None:
            height, width, ch = frame.shape
            center = (width / 2, height / 2)
            regions_of_interest = self.preprocess.get_interest_regions(frame)

            for x, y, w, h in regions_of_interest:
                cv2.rectangle(frame, (x, y), (x + w, y + h),
                              utils.colors["red"], 2)

            gate = self.classifier.classify(frame, regions_of_interest)

            gate_shape = self.get_shape(gate, self.shape_buffer)

            if gate_shape == self.shapes[3] or gate_shape == self.shapes[1]:
                gate = None

            if (gate == None):
                self.directions = [0, 0]
                self.found = False
                gate_shape = None
                w, h = 0, 0
            else:
                x, y, w, h = gate
                cv2.rectangle(frame, (x, y), (x + w, y + h),
                              utils.colors["blue"], 6)
                self.directions = utils.get_directions(center, x, y, w, h)
                self.found = True
            return (self.found, self.directions, gate_shape, (w, h))
        else:
            print('error no frame')
            return False, None, None, None
Exemple #3
0
def minimax_succ(state):
    pos = state.player_positions[state.curr_player]
    succ_states = []
    board = state.board.copy()
    board[pos] = -1
    min_fruit_time = min(len(board[0]), len(board))
    if state.lifetime >= 2 * min_fruit_time:
        board = np.where(board >= 3, 0, board)
    for d in utils.get_directions():
        i = pos[0] + d[0]
        j = pos[1] + d[1]

        if 0 <= i < len(board) and 0 <= j < len(board[0]) and (
                board[i][j] not in [-1, 1, 2]):  # then move is legal

            new_pos = (i, j)
            fruit_score = board[new_pos]
            players_score = list(state.players_score)
            players_score[state.curr_player] += fruit_score

            player_positions = list(state.player_positions)
            player_positions[state.curr_player] = new_pos

            old_board_value = board[new_pos]
            board[new_pos] = (state.curr_player + 1)
            yield SearchAlgos.State(board.copy(), tuple(players_score),
                                    tuple(player_positions),
                                    1 - state.curr_player, state.penalty, d,
                                    state.lifetime + 1, state.initial_pos)

            # reset the board: positions + scores
            board[new_pos] = old_board_value
            players_score[state.curr_player] -= fruit_score
Exemple #4
0
def is_stuck(state:State,player_type):
        for d in get_directions():
            i = state.locations[player_type][X] + d[X]
            j = state.locations[player_type][Y] + d[Y]
            if legal_move(state.board,i,j):
                return False
        return True
Exemple #5
0
    def detect(self):
        ret, frame = self.cap.read()
        height, width, ch = frame.shape
        center = (width / 2, height / 2)
        regions_of_interest = self.preprocess.get_interest_regions(frame)

        for x, y, w, h in regions_of_interest:
            cv2.rectangle(frame, (x, y), (x + w, y + h), utils.colors["red"],
                          2)

        #cv2.imshow('frame', frame)
        gate = self.classifier.classify(frame, regions_of_interest)

        if (gate == None):
            self.directions = [0, 0]
            self.found = False
        else:
            x, y, w, h = gate
            cv2.rectangle(frame, (x, y), (x + w, y + h), utils.colors["blue"],
                          6)
            self.directions = utils.get_directions(center, x, y, w, h)
            self.found = True

        self.out.write(frame)

        return self.found, self.directions
Exemple #6
0
    def detect(self, frame):
        height, width, ch = frame.shape
        center = (width / 2, height / 2)
        regions_of_interest = self.preprocess.get_interest_regions(frame)

        for x, y, w, h in regions_of_interest:
            cv2.rectangle(frame, (x, y), (x + w, y + h), utils.colors["red"],
                          2)
            # have idea to use get_shape here so we classify only squares?
            # add each to self.shape_list? - good for testing
            # roi = (x, y, w, h)
            # self.shape_list.add(roi) or
            # gate_rois = self.classifier.classify(frame, roi) etc..

        #cv2.imshow('frame', frame)
        gate = self.classifier.classify(frame, regions_of_interest)

        gate_shape = self.get_shape(gate, self.shape_buffer)

        if (gate == None):
            self.directions = [0, 0]
            self.found = False
            w, h = 0, 0
        else:
            x, y, w, h = gate
            cv2.rectangle(frame, (x, y), (x + w, y + h), utils.colors["blue"],
                          6)
            self.directions = utils.get_directions(center, x, y, w, h)
            self.found = True
        return (self.found, self.directions, gate_shape, (w, h))
def other_player_stuck(board, pos):
    for d in utils.get_directions():
        i = pos[0] + d[0]
        j = pos[1] + d[1]
        if 0 <= i < len(board) and 0 <= j < len(board[0]) and (board[i][j] not in [-1, 1, 2]):
            return False
    return True
Exemple #8
0
    def search_die(self, value):
        candidate_dice = self.pp.get_interest_areas()
        dice = [die for die in candidate_dice if self.classifier.predict(die) > .1]

        for die in dice:
            if self.get_dots(die) == value:
                self.directions = utils.get_directions(die)
 def __init__(self, game_time, penalty_score):
     """
     Player initialization.
     """
     self.game_time = game_time
     self.penalty_score = penalty_score
     self.directions = utils.get_directions() #[(1, 0), (0, 1), (-1, 0), (0, -1)]
Exemple #10
0
def availables(board,loc):
    steps_available = 0
    for d in get_directions():
        i = loc[0] + d[0]
        j = loc[1] + d[1]
        if 0 <= i < len(board) and 0 <= j < len(board[0]) and board[i][j] == 0:  # then move is legal
            steps_available += 1
    return steps_available
def number_of_legal_cells_from_location(object_input, location):
    steps_number = 0
    for d in utils.get_directions():
        i = location[0] + d[0]
        j = location[1] + d[1]
        if 0 <= i < len(object_input.game_board) and 0 <= j < len(object_input.game_board[0]) and object_input.game_board[i][j] not in [-1, 1, 2]:
            steps_number += 1
    return steps_number
Exemple #12
0
 def search_die(self, frame, value):
     found = False
     dice = self.locate_dice(frame)
     for die in dice:
         if self.get_dots(die) == value:
             found = True
             self.directions = utils.get_directions(die)
     return found, self.directions
def is_goal(state):
    pos = state.player_positions[state.curr_player]
    for d in get_directions():
        i = pos[0] + d[0]
        j = pos[1] + d[1]

        if 0 <= i < len(state.board) and 0 <= j < len(state.board[0]) and (
            state.board[i][j] not in [-1, 1, 2]):  # then move is legal
            return False
    return True
Exemple #14
0
def calc_left_moves(board, pos):
    sum_moves = 1
    for direction in utils.get_directions():
        i = pos[0] + direction[0]
        j = pos[1] + direction[1]
        if 0 <= i < len(board) and 0 <= j < len(
                board[0]) and (board[i][j] not in [-1, 1, 2]):
            board[i][j] = -1
            sum_moves += calc_left_moves(board, (i, j))
    return sum_moves
def heuristic_distance_from_fruit(state):
    board = state.board
    pos = state.player_positions[0]
    for d in utils.get_directions():
        i = pos[0] + d[0]
        j = pos[1] + d[1]
        if 0 <= i < len(board) and 0 <= j < len(
                board[0]) and (board[i][j] not in [-1, 1, 2]):
            return board[i][j] / state.penalty
    return 0
Exemple #16
0
    def detect(self, frame):
        print 'testing slots detect'
        if frame is not None:
            height, width, ch = frame.shape
            center = (width / 2, height / 2)
            regions_of_interest = self.preprocess.get_interest_regions(frame)

            for x, y, w, h in regions_of_interest:
                cv2.rectangle(frame, (x, y), (x + w, y + h),
                              utils.colors["red"], 2)

            gate = self.classifier.classify(frame, regions_of_interest)

            gate_shape = self.get_shape(gate, self.shape_buffer)

            if gate_shape == self.shapes[3] or gate_shape == self.shapes[1]:
                gate = None

            if (gate == None):
                self.directions = [0, 0]
                self.found = False
                gate_shape = None
                w, h = 0, 0
            else:
                x, y, w, h = gate
                cv2.rectangle(frame, (x, y), (x + w, y + h),
                              utils.colors["blue"], 6)

                w_pad = w / 7
                h_pad = h / 7
                if self.is_direction_center:
                    self.directions = utils.get_directions(center, x, y, w, h)
                    cv2.rectangle(frame, (x + (3 * w_pad), y + (3 * h_pad)),
                                  (x + (4 * w_pad), y + (4 * h_pad)),
                                  utils.colors["green"], 2)
                else:
                    if self.is_red_left:
                        self.directions = utils.get_directions_left(
                            center, x, y, w, h)
                        cv2.rectangle(frame,
                                      (x + (2 * w_pad), y + (3 * h_pad)),
                                      (x + (3 * w_pad), y + (4 * h_pad)),
                                      utils.colors["green"], 2)
                    else:
                        self.directions = utils.get_directions_right(
                            center, x, y, w, h)
                        cv2.rectangle(frame,
                                      (x + (4 * w_pad), y + (3 * h_pad)),
                                      (x + (5 * w_pad), y + (4 * h_pad)),
                                      utils.colors["green"], 2)
                self.found = True
            return (self.found, self.directions, gate_shape, (w, h))
        else:
            print('error no frame')
            return False, None, None, None
Exemple #17
0
    def __init__(self,
                 board,
                 players_positions,
                 max_fruit_score,
                 max_fruit_time,
                 fruits_max_part_of_free_spaces=0.2,
                 animated=False,
                 animation_func=None):
        """Initialize the game properties with parameters.
        input:
            - board: 2D np.array. The initial board
            - players_positions: the initial players positions
            - max_fruit_score: max score for a fruit.
            - max_fruit_time: max time for a fruit to be on board.
            - fruits_max_part_of_free_spaces: the max part on board the fruits can take at each timestamp.
            - animated: bool. Animated game (not in terminal) if true.
            - animated_func: the function doing the animation.
        """
        assert len(players_positions) == 2, 'Supporting 2 players only'
        self.map = board
        self.max_fruit_score = max_fruit_score

        self.max_fruit_time = max_fruit_time
        # min fruit time is set by the min dimension of the board
        self.min_fruit_time = min(len(board[0]), len(board))
        # in case that min_fruit_time is greater/equal to max_fruit_time -> change max_fruit_time
        if self.max_fruit_time <= self.min_fruit_time:
            self.max_fruit_time = self.min_fruit_time + 1

        self.fruits_max_part_of_free_spaces = fruits_max_part_of_free_spaces
        self.players_positions = players_positions
        self.players_score = [0, 0]  # init scores for each player
        self.directions = utils.get_directions()
        # Fruits:
        fruits_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                  'fruits_imgs')
        self.fruits_paths = [
            os.path.join(fruits_dir, fruit_file)
            for fruit_file in os.listdir(fruits_dir)
        ]
        self.fruits_on_board = {}

        self.turn = 0

        self.animated = animated
        self.animation_func = animation_func

        if self.animated:
            self.init_animation()
        #TODO
        self.create_fruits()
        self.players_positions = [
            tuple(reversed(position)) for position in self.players_positions
        ]
Exemple #18
0
def get_legal_moves(board, location):
    legal_moves = []
    for d in get_directions():
        i = location[0] + d[0]
        j = location[1] + d[1]

        # check legal move
        if 0 <= i < len(board) and 0 <= j < len(
                board[0]) and (board[i][j] not in [-1, 1, 2]):
            legal_moves.append((i, j))
    return legal_moves
    def make_move(self, time_limit, players_score):
        """Make move with this Player.
        input:
            - time_limit: float, time limit for a single turn.
        output:
            - direction: tuple, specifing the Player's movement, chosen from self.directions
        """

        start_time = time.time()
        d = 1

        reach_the_end = False
        best_direction = None
        chosen_state = None

        time_limit = (2 * self.game_time *
                      float(self.player_turns - self.turns + 1)) / (
                          (self.player_turns + 1) * self.player_turns)
        time_limit += self.spaire_time

        if time_limit >= 5:
            TIME_ESTIMATION = 0.9
        else:
            TIME_ESTIMATION = 0.85
        #print(f'Time limit: {time_limit}')
        while not reach_the_end:  # and d < len(state.board)*len(state.board[0]):

            iter_time_limit = TIME_ESTIMATION * (time_limit -
                                                 (time.time() - start_time))
            #print(f'>>>Iter time: {iter_time_limit}')
            state = State(get_directions(), self.board, self.locations,
                          self.fruits_on_board_dict, PLAYER, players_score,
                          self.penalty_score, self.fruits_ttl, self.turns)

            try:
                _, best_direction, reach_the_end, chosen_state = self.alphabeta.search(
                    state,
                    d,
                    True,
                    iter_time_limit,
                    alpha=float('-inf'),
                    beta=float('inf'))
                d += 1
            except Exception as e:
                self.spaire_time = time_limit - (time.time() - start_time)
                break

        # Set new location
        if best_direction == None:
            best_direction = self.get_random_move()
        self.set_player_location(best_direction)

        self.turns += 1
        return best_direction
def heuristic_num_steps(board, pos):
    num_steps_available = 0
    for d in utils.get_directions():
        i = pos[0] + d[0]
        j = pos[1] + d[1]

        # check legal move
        if 0 <= i < len(board) and 0 <= j < len(board[0]) and (board[i][j] not in [-1, 1, 2]):
            num_steps_available += 1
    if num_steps_available == 0:
        return 0
    return 1 / num_steps_available
 def __init__(self, game_time, penalty_score):
     AbstractPlayer.__init__(
         self, game_time, penalty_score
     )  # keep the inheritance of the parent's (AbstractPlayer) __init__()
     # Might need to add here usage of minimax.
     self.max_fruit_turn = None
     self.penalty_score = penalty_score
     self.directions = utils.get_directions()
     # TODO: Remember update this
     self.current_turn = 0
     self.board = None
     self.pos = None
     self.minimax_algo = AlphaBeta(self.utility, self.succ, None)
def get_moves_from_location(state, maximizing_player):
    current_location = state.location if maximizing_player else state.rival_location
    board = state.game_board
    available_moves = []
    directions = utils.get_directions()
    for d in directions:
        current_i = current_location[0] + d[0]
        current_j = current_location[1] + d[1]

        if 0 <= current_i < len(board) and 0 <= current_j < len(board[0]) and board[current_i][current_j] not in [-1, 1, 2]:
            available_moves.append((d[0], d[1]))

    return available_moves
Exemple #23
0
def api_station_directions():
    from_name = request.args.get('from')
    to_name = request.args.get('to')

    from_station = Station.nodes.filter(short__iexact=from_name)[0]
    to_station = Station.nodes.filter(short__iexact=to_name)[0]

    current_user.stats.directed += 1
    current_user.save()

    result = utils.get_directions(from_station, to_station)

    return jsonify(result)
def state_score(board, pos):
    num_steps_available = 0
    for d in utils.get_directions():
        i = pos[0] + d[0]
        j = pos[1] + d[1]

        # check legal move
        if 0 <= i < len(board) and 0 <= j < len(board[0]) and (board[i][j] not in [-1, 1, 2]):
            num_steps_available += 1

    if num_steps_available == 0:
        return -1
    else:
        return 4 - num_steps_available
 def __init__(self, game_time, penalty_score):
     AbstractPlayer.__init__(
         self, game_time, penalty_score
     )  # keep the inheritance of the parent's (AbstractPlayer) __init__()
     # TODO: initialize more fields, if needed, and the Minimax algorithm from SearchAlgos.py
     # Might need to add here usage of minimax.
     self.max_fruit_turn = None
     self.penalty_score = penalty_score
     self.directions = utils.get_directions()
     # TODO: Remember update this
     self.current_turn = 0
     self.board = None
     self.pos = None
     self.minimax_algo = MiniMax(self.utility, self.succ, None)
def is_enemy_reachable(board, pos):
    queue = deque([(pos, 0)])
    seen = {pos}
    while queue:
        pos, distance = queue.popleft()
        if board[pos] == 2:
            return True
        for d in utils.get_directions():
            i = pos[0] + d[0]
            j = pos[1] + d[1]
            if 0 <= i < len(board) and 0 <= j < len(board[0]) and (
                    board[i][j] not in [-1, 1]) and (i, j) not in seen:
                queue.append(((i, j), distance + 1))
                seen.add((i, j))
    return False
Exemple #27
0
def can_I_move(board, pos):
    num_steps_available = 0
    for d in get_directions():
        i = pos[0] + d[0]
        j = pos[1] + d[1]

        # check legal move
        if 0 <= i < len(board) and 0 <= j < len(
                board[0]) and (board[i][j] not in [-1, 1, 2]):
            # print(num_steps_available, '^^^^^^^^^^^^^^^^^^^^^^^^^^^^^')
            num_steps_available += 1
    # print(pos, 'line 33')
    if num_steps_available == 0:
        return False
    return True
    def detect(self, frame, die_num=None):
        if die_num is None:
            die_num = 5

        if frame is not None:
            interest_regions = self.preprocessor.get_interest_regions(frame)
            # die = [die for die in interest_regions if self.classifier.predict(die) > .1]
            classified_rois = self.classifier.classify(frame, interest_regions)
            dice = self.has_2_neighbors(classified_rois, self.shapes[3])
            #TODO we need to implement a way to use self.die_1 and self.die_2
            # in the detect to return the right coordinates. we can check if the die
            # is touched by the sub if the frame is equal to the region of interest (744x480)
            # or (640x480) for the laptop camera

            # we can also use the dictionary, whichever one is easier

            for x, y, w, h in classified_rois:
                cv2.rectangle(frame, (x, y), (x + w, y + h),
                              utils.colors["red"], 2)

            ht, wd, ch = frame.shape

            dice_shape = self.get_shape(dice, self.shape_buffer)
            # if dice_shape != self.shapes[1]:
            #     dice = None

            if not dice:
                self.found = False
                dice_shape = None
                self.directions = [0, 0]
                w, h = 0, 0
            else:
                x, y, w, h = dice
                # dice_shape = self.get_shape(dice, self.shape_buffer)
                # dice_shape = None
                cv2.rectangle(frame, (x, y), (x + w, y + h),
                              utils.colors["blue"], 6)
                self.directions = utils.get_directions((wd / 2, ht / 2), x, y,
                                                       w, h)
                self.found = True

            #found, direction, shape, width, heightk
            # return (self.found, self.directions, None, (0, 0))
            return (self.found, self.directions, dice_shape, (w, h))

        else:
            print('error no frame')
            return False, None, None, None
Exemple #29
0
    def make_move(self, time_limit, players_score):
        """Make move with this Player.
        input:
            - time_limit: float, time limit for a single turn.
        output:
            - direction: tuple, specifing the Player's movement, chosen from self.directions
        """

        start_time = time.time()
        d = 1

        # Make the initial state:

        reach_the_end = False
        best_direction = None
        chosen_state = None
        if time_limit >= 5:
            TIME_ESTIMATION = 0.9
        else:
            TIME_ESTIMATION = 0.85

        while not reach_the_end:

            iter_time_limit = TIME_ESTIMATION * (time_limit -
                                                 (time.time() - start_time))
            state = State(get_directions(), self.board, self.locations,
                          self.fruits_on_board_dict, PLAYER, players_score,
                          self.penalty_score, self.fruits_ttl, self.turns)

            try:
                _, best_direction, reach_the_end, chosen_state = self.minimax.search(
                    state, d, True, iter_time_limit)
                d += 1

            except Exception as e:
                break

        # Set new location
        if best_direction == None:
            best_direction = self.get_random_move()
        self.set_player_location(best_direction)

        self.turns += 1
        return best_direction
Exemple #30
0
def respond(request):
    """Respond to an HTTP request

    Parameters
    ----------
    request

    Returns
    -------

    """
    text = request.form.get("text", None)
    channel = request.form.get("channel_id")
    start, end = text.split(" to ")
    path_nodes, path_edges = get_directions(start, end)
    plot_path(path_nodes, path_edges)
    plt.savefig("directions.png", format="png", dpi=200)
    client = slack.WebClient(token=os.environ['SLACK_API_TOKEN'])
    response = client.files_upload(channels=channel, file="directions.png")