Exemplo n.º 1
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)
Exemplo 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()
Exemplo n.º 3
0
    def __init__(self, parent, id=-1, title="Domain Shared Contacts Editor", ico=None,
                pos = wx.DefaultPosition,
                size= (950,600),
                style = wx.DEFAULT_FRAME_STYLE | wx.SUNKEN_BORDER | wx.CLIP_CHILDREN):
        """Setup and configure the main UI
        """

        wx.Frame.__init__(self, parent, id, title, pos, size, style)

        # Make this frame known to the FrameManager
        self._mgr = wx.aui.AuiManager()
        self._mgr.SetManagedWindow(self)

        self.SetMinSize(wx.Size(900, 500))

        if ico:
            self.SetIcon(ico)

        self.createToolbar()
        # make messages available for subscribers
        self.registerMessages()

        # Each supported pane has to be put here
        self.grid = GridView(self)
        self._mgr.AddPane(self.grid, wx.aui.AuiPaneInfo().
                          Name("ContactsTable").Caption("Contacts Table View").CenterPane().
                          CloseButton(False).MaximizeButton(False))



        # bind this frame events
        self.binEvents()

        self._mgr.Update()
Exemplo n.º 4
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()
Exemplo n.º 5
0
    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 = {}
Exemplo n.º 6
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()
Exemplo n.º 7
0
    button.nav_target = f"level_{x + 1}"


num_rows = NUM_LEVELS // LEVELS_PER_ROW
level_select_screen = GridView([
    [View(5, 1, children=[
        Button(
            text="Quit",
            dest=(0.05, 0.05, 0.1, 0.4),
            aspect_ratio=2,
            border_width=5,
            border_radius=10,
            on_click=lambda self, event: self.run_hook("QUIT_APP")
        ),
        Text(
            text="Level Select",
            font_kwargs={
                "font_size": 40,
                "bold": True
            },
            dest=(0.3, 0.1, 0.4, 0.8)
        )
    ])]
] + [
    level_select_buttons[row * LEVELS_PER_ROW:(row + 1) * LEVELS_PER_ROW]   
    for row in range(NUM_LEVELS // LEVELS_PER_ROW)
], margins=(10,)*4)


hoster = Hoster(
    {
Exemplo n.º 8
0
class MainFrame(wx.Frame):
    def __init__(self, parent, id=-1, title="Domain Shared Contacts Editor", ico=None,
                pos = wx.DefaultPosition,
                size= (950,600),
                style = wx.DEFAULT_FRAME_STYLE | wx.SUNKEN_BORDER | wx.CLIP_CHILDREN):
        """Setup and configure the main UI
        """

        wx.Frame.__init__(self, parent, id, title, pos, size, style)

        # Make this frame known to the FrameManager
        self._mgr = wx.aui.AuiManager()
        self._mgr.SetManagedWindow(self)

        self.SetMinSize(wx.Size(900, 500))

        if ico:
            self.SetIcon(ico)

        self.createToolbar()
        # make messages available for subscribers
        self.registerMessages()

        # Each supported pane has to be put here
        self.grid = GridView(self)
        self._mgr.AddPane(self.grid, wx.aui.AuiPaneInfo().
                          Name("ContactsTable").Caption("Contacts Table View").CenterPane().
                          CloseButton(False).MaximizeButton(False))



        # bind this frame events
        self.binEvents()

        self._mgr.Update()


    def createToolbar(self):
        self.tb = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize,
                         wx.TB_FLAT | wx.TB_NODIVIDER)

        self.tb.SetToolBitmapSize(wx.Size(34,24))

        # toolbar bitmaps
        exit_bmp = resources.getasbitmap(resources.R_EXIT)
        add_bmp = resources.getasbitmap(resources.R_ADD)
        del_bmp = resources.getasbitmap(resources.R_DEL)
        grp_bmp = resources.getasbitmap(resources.R_GRP)
        pub_bmp = resources.getasbitmap(resources.R_PUB)
        get_bmp = resources.getasbitmap(resources.R_GET)

        # toolbar dimension
        tsize = exit_bmp.GetSize()
        self.tb.SetToolBitmapSize(tsize)
        self.tb.SetToolSeparation(8)

        # give ids a name
        self.EXIT_ID = 10
        self.ADD_ID  = 20
        self.DEL_ID  = 30
        self.GRP_ID  = 40
        self.GET_ID  = 50
        self.PUB_ID  = 60


        # tools
        self.tb.AddLabelTool(self.EXIT_ID, "Exit", exit_bmp, shortHelp="Exit application", 
                                                             longHelp="Exit application")
        self.tb.AddSeparator()

        self.tb.AddLabelTool(self.ADD_ID, "Add", add_bmp, shortHelp="Add contact", 
                                                          longHelp="Add contact")
        self.tb.AddLabelTool(self.DEL_ID, "Del", del_bmp, shortHelp="Delete contact", 
                                                          longHelp="Delete contact")
        self.tb.AddLabelTool(self.GRP_ID, "Grp", grp_bmp, shortHelp="Manage groups", 
                                                          longHelp="Add, update and delete groups")
        self.tb.AddSeparator()
        self.tb.AddLabelTool(self.GET_ID, "Get", get_bmp, shortHelp="Get contact", 
                                                          longHelp="Get contact")
        self.tb.AddLabelTool(self.PUB_ID, "Pub", pub_bmp, shortHelp="Publish contact", 
                                                          longHelp="Publish contact")

        self.tb.AddSeparator()
        self.search = wx.SearchCtrl(self.tb, size=(150,-1), style=wx.TE_PROCESS_ENTER)
        self.search.SetMenu(None)
        self.search.ShowCancelButton(1)
        
        self.tb.AddControl(self.search)

        self.tb.Realize()


        # add the toolbar to the manager
        self._mgr.AddPane(self.tb, wx.aui.AuiPaneInfo().
                          Name("tb").Caption("Toolbar").
                          ToolbarPane().Top().
                          LeftDockable(True).RightDockable(True))

    def registerMessages(self):
        pmsg.register("ADD_CONTACT") # request to add a contact
        pmsg.register("DEL_CONTACT") # request to delete a contact
        pmsg.register("MAN_GROUPS")  # request to globally manage groups
        pmsg.register("PUB_CONTACT")
        pmsg.register("SEARCH")
        pmsg.register("CANCEL_SEARCH")

    def binEvents(self):
        # toolbar events
        self.tb.Bind(wx.EVT_TOOL, self.publishEvent, id=self.EXIT_ID)
        self.tb.Bind(wx.EVT_TOOL, self.publishEvent, id=self.ADD_ID)
        self.tb.Bind(wx.EVT_TOOL, self.publishEvent, id=self.DEL_ID)
        self.tb.Bind(wx.EVT_TOOL, self.publishEvent, id=self.GRP_ID)
        self.tb.Bind(wx.EVT_TOOL, self.publishEvent, id=self.GET_ID)
        self.tb.Bind(wx.EVT_TOOL, self.publishEvent, id=self.PUB_ID)
        self.tb.Bind(wx.EVT_TEXT, self.onSearch)
        self.tb.Bind(wx.EVT_TEXT_ENTER, self.onSearch)
        self.tb.Bind(wx.EVT_SEARCHCTRL_SEARCH_BTN, self.onSearch)
        self.tb.Bind(wx.EVT_SEARCHCTRL_CANCEL_BTN, self.resetSearch)

    def publishEvent(self, event):
        """Depending on the id the event with the appropriate message 
        will be published.
        """
        if event.GetId() == self.ADD_ID:
            observer.send_message(pmsg.ADD_CONTACT, event)

        elif event.GetId() == self.DEL_ID:
            observer.send_message(pmsg.DEL_CONTACT, data=self.grid.getActiveRows())

        elif event.GetId() == self.GRP_ID:
            observer.send_message(pmsg.MAN_GROUPS, event)

        elif event.GetId() == self.PUB_ID:
            observer.send_message(pmsg.PUB_CONTACT, event)

        elif event.GetId() == self.GET_ID:
            observer.send_message(pmsg.PUB_CONTACT, event)

        elif event.GetId() == self.EXIT_ID:
            observer.send_message(pmsg.EXIT_APP, event)


    def onSearch(self, evt):
        s = self.search.GetValue()
        if len(s) > 0:
            observer.send_message(pmsg.SEARCH, data=s)
        else:
            observer.send_message(pmsg.CANCEL_SEARCH, data=s)

    def resetSearch(self, evt):
        self.search.Clear()
        observer.send_message(pmsg.CANCEL_SEARCH)
Exemplo n.º 9
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()
Exemplo n.º 10
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)
Exemplo n.º 11
0
 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)
 GridView(
     [[Text(2, 3, text="Arithma", **menu_h1_style)],
      [
          Button(2,
                 2,
                 text="Levels",
                 on_click=lambda self, event: self.run_hook(
                     "NAVIGATE_TO", "level_select"),
                 **menu_button_style)
      ],
      [
          Button(2,
                 2,
                 text="Settings",
                 on_click=lambda self, event: self.run_hook(
                     "NAVIGATE_TO", "settings"),
                 **menu_button_style)
      ],
      [
          Button(1,
                 2,
                 text="Credits",
                 on_click=lambda self, event: self.run_hook(
                     "NAVIGATE_TO", "credits"),
                 **menu_button_style),
          Button(1,
                 2,
                 text="Quit",
                 on_click=lambda self, event: self.run_hook("QUIT_APP"),
                 **menu_button_style)
      ]],
     dest=(0.3, 0.0, 0.4, 0.9))
Exemplo n.º 13
0
            if self.rerender_on_next_frame:
                self.update_screen()
                self.rerender_on_next_frame = False

        pygame.display.quit()


if __name__ == "__main__":
    test_button = Button(
        1, 1, RED,
        text="Navigate to Other!",
        on_click=lambda self, event: self.run_hook("NAVIGATE_TO", "other")
    )

    test_component_1 = GridView([
        [View(5, 1, RED), View(2, 1, GREEN)],
        [View(6, 1, BLUE), test_button]
    ])

    test_component_2a = GridView([
        [View(1, 1, GREEN), View(1, 1, RED)],
        [Button(1, 1, RED, text="HIT", on_click=lambda self, event: print("HIT")), View(1, 1, GREEN)]
    ], x_flex=1, y_flex=1)

    test_assets_dir = os.path.join(os.path.dirname(__file__), "test_assets")
    test_image_source = pygame.image.load(os.path.join(test_assets_dir, "smile.png"))

    test_component_2 = GridView([
        [Image(image=test_image_source), test_component_2a],
        [Text(2, 1, BLUE, "Hello, World!")]
    ])
Exemplo n.º 14
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()