Esempio n. 1
0
def main(speed=0.1, sort_method=sort_alg.bubble_sort):
    screen = pygame.display.set_mode(resolution, 0, 32)
    clock = pygame.time.Clock()
    grid_view = GridView(screen, width, height, grid_size, grid_line_color)

    sort_alg.generate_random_array()
    path_track = sort_method()
    print path_track

    # some utility variable
    index = 0
    pass_time = 0

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                exit()

        screen.fill(background_color)

        grid_view.draw_array_in_grid(path_track[index][0], cell_color,
                                     path_track[index][1], special_cell_color)

        grid_view.draw()
        time_passed_second = clock.tick() / 1000.0
        pass_time += time_passed_second

        if pass_time >= speed:
            pass_time = 0
            index = index + 1
            if index >= len(path_track):
                index = len(path_track) - 1

        pygame.display.update()
Esempio n. 2
0
def main(speed=0.1, sort_method=sort_alg.bubble_sort):
    screen = pygame.display.set_mode(resolution, 0, 32)
    clock = pygame.time.Clock()
    grid_view = GridView(screen, width, height, grid_size, grid_line_color)

    sort_alg.generate_random_array()
    path_track = sort_method()
    print path_track

    # some utility variable
    index = 0
    pass_time = 0

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                exit()

        screen.fill(background_color)

        grid_view.draw_array_in_grid(path_track[index][0], cell_color,
                                     path_track[index][1], special_cell_color)

        grid_view.draw()
        time_passed_second = clock.tick() / 1000.0
        pass_time += time_passed_second

        if pass_time >= speed:
            pass_time = 0
            index = index + 1
            if index >= len(path_track):
                index = len(path_track) - 1

        pygame.display.update()
Esempio n. 3
0
class Grid():
    def __init__(self):
        pygame.init()
        pygame.display.set_caption("Grid with agents")
        self.model = GridModel()
        self.view = GridView(self.model)
        self.control = GridControl(self.model)

    def start_loop(self, parameters):
        clock = pygame.time.Clock()
        crashed = False

        timestep = 0
        while not crashed:
            timestep = timestep + 1
            print("t = " + str(timestep))
            # handle input
            crashed = self.control.check_events()

            self.model.update()

            # draw screen
            self.view.draw()

            # update
            pygame.display.update()
            clock.tick(parameters.updates)
Esempio n. 4
0
def main(maze_method, speed=0.010, mode=0):
    """
        the main program of the program
        mode 0: default mode, build the wall
        mode 1: first all cell are wall, then pull down the wall
        """
    screen = pygame.display.set_mode(resolution, 0, 32)
    clock = pygame.time.Clock()
    maze, cell_list = maze_method()

    path_finder = MazePathFinder(maze, (2, 1), (cell_row_num * 2, cell_col_num * 2 + 1),
                                 height // grid_size, width // grid_size)
    path = path_finder.bfs_find_path()

    index = 0
    path_index = 0
    maze_finished = False

    pass_time = 0
    grid_view = GridView(screen, width, height, grid_size, grid_line_color)
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                exit()

        press_key = pygame.key.get_pressed()

        # press F5 to regenerate the maze
        if press_key[K_F5]:
            index = 0
            path_index = 0
            maze, cell_list = maze_method()
            path_finder = MazePathFinder(maze, (2, 1), (cell_row_num * 2, cell_col_num * 2 + 1),
                                         height // grid_size, width // grid_size)
            path = path_finder.bfs_find_path()
            maze_finished = False

        # print index

        if mode == 0:
            screen.fill(background_color)
        else:
            screen.fill(cell_color)

        # draw the cell
        for i in range(index + 1):
            if mode == 0:
                grid_view.fill_a_cell(cell_list[i][1], cell_list[i][0], cell_color)
            else:
                grid_view.fill_a_cell(cell_list[i][1], cell_list[i][0], background_color)

        # draw the grid
        grid_view.draw()

        # draw the path
        if maze_finished and path:
            for i in range(path_index + 1):
                grid_view.fill_a_cell_with_circle(path[len(path) - i - 1][1],
                                                  path[len(path) - i - 1][0], path_color)

        time_passed_seconds = clock.tick() / 1000.0
        pass_time += time_passed_seconds

        if pass_time >= speed:
            pass_time = 0
            if maze_finished:
                if path_index + 1 < len(path):
                    path_index += 1

            if index >= len(cell_list) - 1:
                # print 'maze_finished'
                maze_finished = True

            if index + 1 < len(cell_list):
                index += 1

        pygame.display.update()
Esempio n. 5
0
def main(maze_method, speed=0.010, mode=0):
        """
        the main program of the program
        mode 0: default mode, build the wall
        mode 1: first all cell are wall, then pull down the wall
        """
        screen = pygame.display.set_mode(resolution, 0, 32)
        clock = pygame.time.Clock()
        maze, cell_list = maze_method()

        path_finder = MazePathFinder(maze, (2, 1), (cell_row_num * 2, cell_col_num * 2 + 1), 
                              height//grid_size, width//grid_size)
        path = path_finder.bfs_find_path()

        index = 0
        path_index = 0
        maze_finished = False

        pass_time = 0
        grid_view = GridView(screen, width, height, grid_size, grid_line_color) 
        while True:
                for event in pygame.event.get():
                        if event.type == QUIT:
                                exit()

                press_key = pygame.key.get_pressed()
                
                # press F5 to regenerate the maze
                if press_key[K_F5]:
                        index = 0
                        path_index = 0
                        maze, cell_list = maze_method()
                        path_finder = MazePathFinder(maze, (2, 1), (cell_row_num * 2, cell_col_num * 2 + 1), 
                                height//grid_size, width//grid_size)
                        path = path_finder.bfs_find_path()
                        maze_finished = False

                #print index
                
                if mode == 0:
                    screen.fill(background_color)
                else:
                        screen.fill(cell_color)

                # draw the cell
                for i in range(index + 1):
                        if mode == 0:
                            grid_view.fill_a_cell(cell_list[i][1], cell_list[i][0], cell_color)
                        else:
                            grid_view.fill_a_cell(cell_list[i][1], cell_list[i][0], background_color)

                # draw the grid
                grid_view.draw()

                # draw the path
                if maze_finished and path:
                        for i in range(path_index + 1):
                                grid_view.fill_a_cell_with_circle(path[len(path) - i - 1][1], 
                                                                  path[len(path) - i - 1][0], path_color)

                time_passed_seconds = clock.tick() / 1000.0
                pass_time += time_passed_seconds

                if pass_time >= speed:
                        pass_time = 0
                        if maze_finished:
                                if path_index + 1 < len(path):
                                        path_index += 1

                        if index >= len(cell_list) - 1:
                                #print 'maze_finished'
                                maze_finished = True
                                
                        if index + 1 < len(cell_list):
                                index += 1

                pygame.display.update()
Esempio n. 6
0
class System():
    """docstring for System"""
    def __init__(self, display):
        self.time = 0
        self.agents = dict()
        self.display = display

        self.model = GridModel()

        if display:
            pygame.init()
            pygame.display.set_caption("Grid with agents")
            self.view = GridView(self)
            self.control = GridControl(self.model)

        self.entities = [Entity(x) for x in constants.FRUITS]
        self.entity_global_average_price = {}

        self.price_trends = {}

        self.total_negotiations = []

        #This is a dict to maintain price update requests coming from system in the given time step
        self.entity_global_price_updates = {}

    def create_agent(self, name, agent_id, no_agents, x=None, y=None):
        """Create a new Agent in the system."""
        x = randint(0, constants.TILES_X - 1) if x == None else x
        y = randint(0, constants.TILES_Y - 1) if y == None else x
        new_agent = Agent(name=name,
                          agent_id=agent_id,
                          no_agents=no_agents,
                          x_pos=x,
                          y_pos=y)

        self.agents[name] = new_agent

    def advance(self):
        """Advance the time by a value of 1."""

        requests_sent = 0
        requests_received = 0

        responses_sent = 0
        responses_received = 0

        self.set_global_average_price_for_all_entities(
        )  # Update global average price collected in the last step.
        items = list(self.agents.items())
        shuffle(items)

        # Let all agents send their messages
        for name, agent in items:
            agent.send_requests()
            responses_sent += agent.send_responses()

        # Let all agents receive messages
        for name, agent in items:
            requests_received += agent.receive_requests()
            responses_received += agent.receive_responses()

        for name, agent in items:
            agent.neighbors = self.get_neighbors(agent)
            if isinstance(agent.state, NegotiationState):
                if not isinstance(agent.state.other_agent.state,
                                  NegotiationState):
                    agent.state = RandomWalkState(this_agent=agent)
                    continue

                time_remaining = constants.MAX_TIME - self.time
                if agent.patience * time_remaining * 0.5 < agent.state.duration or \
                    (agent.state.buy_or_sell == 'sell' and agent.state.other_agent.money < agent.state.price_each*agent.state.quantity) or \
                    (agent.state.buy_or_sell == 'buy' and agent.money < agent.state.price_each*agent.state.quantity) or \
                    (agent.state.buy_or_sell == 'sell' and agent.entities_info[agent.state.fruit]['quantity'] < agent.state.quantity) or \
                    (agent.state.buy_or_sell == 'buy' and agent.state.other_agent.entities_info[agent.state.fruit]['quantity'] < agent.state.quantity):
                    agent.state.decline()
                    continue

                # Accept offer if within price range
                if agent.state.buy_or_sell == 'buy':
                    if agent.state.other_agent.state.price_each <= agent.state.price_each:
                        agent.state.accept()
                        continue

                # At this point, price should be further negotiated
                if agent.state.buy_or_sell == 'buy':
                    agent.state.price_each = triangular(
                        agent.state.price_each,
                        agent.entities_info[agent.state.fruit]
                        ['max_buying_price'] * (1 + agent.elasticity),
                        agent.state.price_each)  #/(1+agent.state.duration)
                    agent.state.duration += 1

                if agent.state.buy_or_sell == 'sell':
                    agent.state.price_each = triangular(
                        agent.entities_info[agent.state.fruit]
                        ['min_selling_price'] * (1 - agent.elasticity),
                        agent.state.price_each,
                        agent.state.price_each)  #/(1+agent.state.duration)
                    agent.state.duration += 1

            elif isinstance(
                    agent.state, RandomWalkState
            ) and not agent.incoming_requests and not agent.incoming_responses:
                agent.random_walk()

            elif isinstance(
                    agent.state, WalkToAgentState
            ) and not agent.incoming_requests and not agent.incoming_responses:
                agent.search_agent(self.find_path(agent))

            elif isinstance(agent.state, WaitForResponseState):
                if agent.state.counter <= 0:
                    agent.state = RandomWalkState(this_agent=agent)
                else:
                    agent.state.counter = agent.state.counter - 1

        for name, agent in self.agents.items():
            agent.set_color(
                max_money=max([a.money for _, a in self.agents.items()]))
            agent.freeze_movement = False

        self.time += 1

        self.model.update()
        closed = False

        # draw screen
        if self.display:
            self.view.draw()

            # update
            pygame.display.update()
            time.sleep(0)
            closed = self.control.check_events()

        return closed

    # set the neighbors of an agent (required for preventing agents from walking through each other)
    def get_neighbors(self, agent):
        neighbors = [None, None, None, None]  # [North, East, South, West]
        for name, possible_neighbor in self.agents.items():
            if possible_neighbor.x_pos == agent.x_pos and possible_neighbor.y_pos == (
                    agent.y_pos - 1):
                neighbors[constants.NORTH] = possible_neighbor
            if possible_neighbor.x_pos == (
                    agent.x_pos +
                    1) and possible_neighbor.y_pos == agent.y_pos:
                neighbors[constants.EAST] = possible_neighbor
            if possible_neighbor.x_pos == agent.x_pos and possible_neighbor.y_pos == (
                    agent.y_pos + 1):
                neighbors[constants.SOUTH] = possible_neighbor
            if possible_neighbor.x_pos == (
                    agent.x_pos -
                    1) and possible_neighbor.y_pos == agent.y_pos:
                neighbors[constants.WEST] = possible_neighbor
        return neighbors

    #This will return current global price of the entity
    def get_entity_global_average_price(self, entity_name):
        return self.entity_global_average_price.get(entity_name, None)

    #This will return list of all entities in the System
    def get_all_entities(self):
        return self.entities

    #This will return all agents in a list other than agents in except list
    def get_all_agents_in_list(self, except_agents=[]):
        return [
            agent for name, agent in self.agents.items()
            if name not in except_agents
        ]

    #To set global average price of entity
    def update_entity_global_average_price(self, entity_name, price, quantity):
        if entity_name in self.entity_global_price_updates.keys():
            self.entity_global_price_updates[entity_name].append(
                (price, quantity))
        else:
            self.entity_global_price_updates[entity_name] = [(price, quantity)]

    #Should only be called when time step changes
    def set_global_average_price_for_all_entities(self):
        def _weighted_sum(tpls):
            ttl = sum([x[1] for x in tpls])
            return sum([x[0] * x[1] for x in tpls]) / ttl

        for entity_name, prices in self.entity_global_price_updates.items():
            if len(prices) > 0:
                weighted_sum = _weighted_sum(prices)
                gape = (self.entity_global_average_price.get(
                    entity_name, weighted_sum) + weighted_sum) / 2
                self.entity_global_average_price[entity_name] = gape

            #Add average price to entity trend
            temp_price = self.entity_global_average_price.get(
                entity_name, None)
            if temp_price:
                self.add_price_to_entity_trend(entity_name, temp_price)

        #Reset this when all the calculation are done
        self.reset_enity_global_price_updates_dict()

    def add_price_to_entity_trend(self, entity_name, price):
        entity_trend = self.price_trends.get(entity_name, None)
        if not entity_trend:
            self.price_trends[entity_name] = EntityTimeSeries(entity_name)
            entity_trend = self.price_trends[entity_name]
        entity_trend.add_price_to_time_series(price)

    def reset_enity_global_price_updates_dict(self):
        self.entity_global_price_updates = dict()

    def is_price_going_up(self, entity_name):
        entity_trend = self.price_trends.get(entity_name, None)
        return entity_trend.is_price_going_up() if entity_trend else (
            'CAN NOT TELL', False)

    def is_price_going_down(self, entity_name):
        entity_trend = self.price_trends.get(entity_name, None)
        return entity_trend.is_price_going_down() if entity_trend else (
            'CAN NOT TELL', False)

    def get_fraction_change_in_price(self, entity_name):
        entity_trend = self.price_trends.get(entity_name, None)
        if entity_trend:
            return entity_trend.get_fraction_change_in_price()
        return 0.0

    def agent_at(self, x, y):
        for name, agent in self.agents.items():
            if agent.x == x and agent.y == y:
                return agent
        return None

    def find_path(self, agent):
        target = agent.state.other_agent
        directions = []
        if constants.BFS:
            distances = [
                constants.INF, constants.INF, constants.INF, constants.INF
            ]  # [north, east, south, west]

            distances[constants.NORTH] = self.bfs(
                (agent.x_pos, agent.y_pos - 1), (target.x_pos, target.y_pos))
            distances[constants.EAST] = self.bfs(
                (agent.x_pos + 1, agent.y_pos), (target.x_pos, target.y_pos))
            distances[constants.SOUTH] = self.bfs(
                (agent.x_pos, agent.y_pos + 1), (target.x_pos, target.y_pos))
            distances[constants.WEST] = self.bfs(
                (agent.x_pos - 1, agent.y_pos), (target.x_pos, target.y_pos))

            min_dist = min(distances)

            if min_dist == constants.INF:
                return directions

            if distances[constants.NORTH] == min_dist:
                directions.append(constants.NORTH)
            if distances[constants.EAST] == min_dist:
                directions.append(constants.EAST)
            if distances[constants.SOUTH] == min_dist:
                directions.append(constants.SOUTH)
            if distances[constants.WEST] == min_dist:
                directions.append(constants.WEST)
        else:
            if target.y_pos < agent.y_pos:
                directions.append(constants.NORTH)  # North
            if target.x_pos > agent.x_pos:
                directions.append(constants.EAST)  # East
            if target.y_pos > agent.y_pos:
                directions.append(constants.SOUTH)  # South
            if target.x_pos < agent.x_pos:
                directions.append(constants.WEST)  # West

        return directions

    def bfs(self, start, end):
        explored = []
        queue = [start]
        levels = {}
        levels[start] = 0
        visited = [start]

        while queue:
            pos = queue.pop(0)
            x = pos[0]
            y = pos[1]
            explored.append(pos)
            neighbors = [(x, y - 1), (x + 1, y), (x, y + 1), (x - 1, y)]
            for neighbor in neighbors:
                if neighbor[0] < 0 or neighbor[0] >= constants.TILES_X or neighbor[1] < 0 or neighbor[1] \
                        >= constants.TILES_Y:
                    continue
                if self.agent_at(neighbor[0],
                                 neighbor[1]) and not neighbor == end:
                    continue
                if neighbor not in visited:
                    queue.append(neighbor)
                    visited.append(neighbor)

                    levels[neighbor] = levels[pos] + 1

        if end not in levels:  # not a single step could have been taken (impossible position)
            return constants.INF
        return levels[end]

    def get_random_target(self, agent_id):
        name, target = choice(list(self.agents.items()))
        while target.agent_id == agent_id:
            name, target = choice(list(self.agents.items()))
        return target

    def print_info(self):
        """Print the information about the system."""
        print("Time = {0}.\n".format(self.time))

    #Initialize total negotiations.
    def initialize_total_negotiations_count(self):
        agents = self.get_all_agents_in_list()
        self.total_negotiations = [[[0, 0] for a in agents]
                                   for out_a in agents]

    #This will update negotiation count
    def update_negotiation_happened(self, agent1_id, agent2_id, isPositive):
        if isPositive:
            self.total_negotiations[agent1_id][agent2_id][0] += 1
            self.total_negotiations[agent2_id][agent1_id][0] += 1
        else:
            self.total_negotiations[agent1_id][agent2_id][1] += 1
            self.total_negotiations[agent2_id][agent1_id][1] += 1

    def get_total_negotiation(self, agent1_id, agent2_id):
        negotiations = self.total_negotiations[agent1_id][agent2_id]
        return (negotiations[0] + negotiations[1] + 1, negotiations[0],
                negotiations[1]
                )  #This will return total , total positive , total negative

    def get_negotiations_parameter_of_agent(self, agent_id):
        negotiations = self.total_negotiations[agent_id]
        total = 0
        pos = 0
        neg = 0
        for temp in negotiations:
            total += temp[0] + temp[1]
            pos += temp[0]
            neg += temp[1]

        return (total, pos, neg)
Esempio n. 7
0
def main(maze_method, speed=0.010, mode=0):
    pygame.init()
    check = 0
    screen = pygame.display.set_mode(resolution)
    pygame.display.set_caption("A_star_Maze")
    clock = pygame.time.Clock()
    maze, cell_list = maze_method()  # 랜덤으로 생성된 2차원 리스트 미로와 xxx 좌표가 담긴 리스트를 받는다

    path = A_star_logic.main(maze, start_point, end_point)
    index = 0
    maze_finished = False

    pass_time = 0
    grid_view = GridView(screen, width, height, grid_size, grid_line_color)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        press_key = pygame.key.get_pressed()

        # press F5 to regenerate the maze
        if press_key[pygame.K_F5]:
            index = 0
            # path_index = 0
            maze, cell_list = maze_method()
            path = A_star_logic.main(maze, start_point, end_point)
            maze_finished = False
            check = 0
        elif press_key[pygame.K_d]:
            main(maze_method=get_maze_method(DFS), mode=1)
            pass
        elif press_key[pygame.K_k]:
            main(maze_method=get_maze_method(Kruskal), mode=1)

        # print index

        if mode == 0:
            screen.fill(background_color)
        else:
            screen.fill(cell_color)

        # draw the cell
        for i in range(index + 1):
            if mode == 0:
                grid_view.fill_a_cell(
                    cell_list[i][1], cell_list[i][0], cell_color)
            else:
                grid_view.fill_a_cell(
                    cell_list[i][1], cell_list[i][0], background_color)

        # draw the grid
        grid_view.draw()

        # draw the path
        if maze_finished and path:
                for i in range(len(path)):
                    grid_view.fill_a_cell_with_circle(
                        path[i][1], path[i][0], path_color)
                    pygame.display.update()
                    sleep(0.1)
                maze_finished = False
                check = 1

        time_passed_seconds = clock.tick() / 1000.0
        pass_time += time_passed_seconds

        if pass_time >= speed:
            pass_time = 0

            if index >= len(cell_list) - 1 and check == 0:
                    maze_finished = True
                    print("랜덤으로 생성된 미로 탐색 비용은 : "+str(len(path)))

            if index + 1 < len(cell_list):
                index += 1
                pygame.display.update()