Example #1
0
    def add(self, client):
        Layout.add(self, client)

        if not client.initial_map:
            self.place(client)

        self.save(client)
Example #2
0
    def __init__(self, spacing, is_homogeneous):
        """Initialize a new BoxLayout object.

        Parameters.
        -----------

        * spacing: positive integer.

          The space that the BoxLayout allocates BETWEEN the children, not
          around them.

        * is_homogeneous: boolean.

          True for a homogeneous BoxLayout (all the children get the same
          size), False for a heterogeneous BoxLayout.

        >>> box = BoxLayout(8, True)
        >>> print box.spacing
        8
        >>> print box.is_homogeneous
        True

        Note that modifying spacing and is_homogeneous after the creation is
        not guaranteed to work.

        """
        Layout.__init__(self)
        self.spacing = spacing
        self.is_homogeneous = is_homogeneous
Example #3
0
def chamfer_callback(event):
    '''Initiates the chamfer tool based on existing settings.'''
    net = None
    layer = None
    center = pcbnew.wxPoint(0, 0)
    spads = Layout.get_selected_pads()
    stracks = Layout.get_selected_tracks()
    
    if len(spads) == 2:
        if spads[0].GetNetname() != spads[1].GetNetname():
            gui.menu_dialog('Pads must be assigned\nto the same net.')
            return
        
        net = spads[0].GetNet()
        layer = spads[0].GetParent().GetLayer()

        p0 = spads[0].GetPosition()
        p1 = spads[1].GetPosition()

        center = pcbnew.wxPoint((p0.x + p1.x)/2, (p0.y + p1.y)/2)
    elif len(stracks) == 2:
        if stracks[0].GetNetname() != stracks[1].GetNetname():
            gui.menu_dialog('Tracks must be assigned\nto the same net.')
            return
        
        net = stracks[0].GetNet()
        layer = stracks[0].GetLayer()

        # Find closest selected endpoints
        p0, p1 = Layout.closest_track_endpoints(stracks)
        center = pcbnew.wxPoint((p0.x + p1.x)/2, (p0.y + p1.y)/2)
    elif len(stracks) == 1 and len(spads) == 1:
        net = stracks[0].GetNet()
        layer = stracks[0].GetLayer()

        # Find closest endpoints
        p0, p1 = Layout.closest_track_pad_endpoints(spads[0], stracks[0])
        center = pcbnew.wxPoint((p0.x + p1.x)/2, (p0.y + p1.y)/2)
    else:
        gui.menu_dialog('Select two tracks, two pads, or a track and pad.')
        return

    cfgSettings = settings.ChamferSettings()
    cfgSettings.Load()
    
    lw = float(cfgSettings.lineWidth)
    bh = float(cfgSettings.boardHeight)
    ca = float(cfgSettings.chamferAngle)
    
    if cfgSettings.lineUnit == '1': lw = lw * 0.0254
    elif cfgSettings.lineUnit == '2': lw = lw * 25.4
    
    if cfgSettings.heightUnit == '1': bh = bh * 0.0254
    elif cfgSettings.heightUnit == '2': bh = bh * 25.4
    
    if cfgSettings.angleUnit == '1': ca = ca * 57.2958

    c = chamfer.Chamfer(lw, bh, ca, net, layer)
    c.ChamferFootprint(center)
 def add_uniform_core(self, num_stations, r_max_m, r_min_m=0):
     """Add uniform random core"""
     if self.seed is None:
         self.seed = np.random.randint(1, 1e8)
     layout = Layout(self.seed, self.trial_timeout_s, self.num_trials)
     layout.uniform_cluster(num_stations, self.station_diameter_m, r_max_m,
                            r_min_m)
     self.layouts['uniform_core'] = dict(x=layout.x, y=layout.y)
Example #5
0
 def __init__(self, margins=0):
     """margins can be an int or a tuple/list of 1, 2 or 4 int."""
     Layout.__init__(self)
     self.left = 0
     self.top = 0
     self.right = 0
     self.bottom = 0
     self.parseMargins(margins)
def test_layout_from_json():
    json_str = '{"cols": 1, "keys": [{"col": 0, "position": {"angle": 1, "width": 1, "x": 1, "y": 1}, "row": 0}], "rows": 1}'
    layout = Layout.from_json(json_str)

    expected_key = Key(0, 0, Position(1, 1, 1, 1))
    expected_layout = Layout(1, 1, [expected_key])

    assert layout == expected_layout
 def draw_minimap(self):
     """Draw minimap."""
     lay = Layout(200, (200, self._resolution[1] - 170), False)
     points = lay.polygon_corners(self._grid.get_hextile(self._color1))
     x, y = 0, self._resolution[1] - 344
     pygame.draw.rect(self._screen, self._background, (x, y, 100, 350), 0)
     pygame.draw.polygon(self._screen, self._background, points, 0)
     self.draw_hex_grid()
Example #8
0
class CoopaModel(Model):
    """A model with some number of agents."""
    def __init__(self, N, width, height, agent_type, log_path=None):
        self.running = True
        self.num_agents = N
        self.grid = SingleGrid(width, height, torus=False)
        self.schedule = RandomActivation(self)
        self.message_dispatcher = MessageDispatcher()
        self.layout = Layout()
        self._context = Context()
        self.agent_type = AGENT_TYPES[agent_type]

        self.layout.draw(self.grid)

        # Add drop point(s)
        self.drop_points = [DropPoint(1, self)]
        self.grid.place_agent(self.drop_points[0], (5, 5))

        # Add recharging station(s)
        self.recharge_points = [RechargePoint(1, self)]
        self.grid.place_agent(self.recharge_points[0], (55, 5))

        # Place resources tactically
        self._context.place_few_trash_in_all_rooms(self)

        # the mighty agents arrive
        for i in range(self.num_agents):
            a = self.agent_type(i, self, log_path=log_path)
            self.schedule.add(a)
            self.grid.position_agent(a)

        self.datacollector = DataCollector(
            model_reporters={
                "Trash collected": compute_dropped_trashes,
                "Average battery power": compute_average_battery_power,
                "Max battery power": compute_max_battery_power,
                "Min battery power": compute_min_battery_power
            },
            # agent_reporters={"Trash": "trash_count"}
        )  # An agent attribute

        self.name = "CoopaModel"
        self._logger = utils.create_logger(self.name, log_path=log_path)

    @property
    def time(self):
        return self.schedule.time

    def step(self):
        t = time.monotonic()
        self.datacollector.collect(self)
        self.schedule.step()
        self._log("Finished in {:.5f} seconds.".format(time.monotonic() - t),
                  logging.INFO)

    def _log(self, msg, lvl=logging.DEBUG):
        self._logger.log(lvl, msg, extra={'time': self.time})
Example #9
0
    def remove(self, client):
        self.restore(client)

        Layout.remove(self, client)

        for leaf in self.root.childs():
            if leaf.client == client:
                leaf.parent.remove_child(leaf)
                break
Example #10
0
def loadLayout(name):
    if name is None:
        name = "default"
    if '.' in name:
        return Layout(name)
    else:
        return Layout(
            os.path.join(os.path.dirname(os.path.realpath(__file__)),
                         "layouts", f"{name}.yaml"))
Example #11
0
    def remove(self, client):
        self.restore(client)

        Layout.remove(self, client)

        for leaf in self.root.childs():
            if leaf.client == client:
                leaf.parent.remove_child(leaf)
                break
Example #12
0
    def __init__(self):
        """Initialize a new BoardLayout object.

        >>> my_board = BoardLayout()
        >>> print my_board.preferred_size
        Size(64, 64)

        """
        Layout.__init__(self)
        self.preferred_size = Size(*BoardLayout.PREFERRED_SIZE)
Example #13
0
 def initialize_threads(self):
     """ Initializes io threads"""
     super().initialize_threads()
     self.dashboard_interval = int(self.ping_interval * 2)
     self.topic_fastclock_pub = self.publish_topics[Global.FASTCLOCK]
     self.topic_dashboard_pub = self.publish_topics[Global.DASHBOARD]
     self.topic_node_pub = self.publish_topics[Global.NODE]
     self.topic_ping_sub = self.subscribed_topics[Global.PING]
     # print("!!! ping sub: "+self.topic_ping_sub)
     self.topic_sensor_sub = self.subscribed_topics[Global.SENSOR]
     self.topic_backup_sub = self.subscribed_topics[Global.BACKUP]
     # print("!!! backup sub: "+self.topic_backup_sub)
     if Global.CONFIG in self.config:
         if Global.OPTIONS in self.config[Global.CONFIG]:
             if Global.TIME in self.config[Global.CONFIG][Global.OPTIONS]:
                 if Global.FAST in self.config[Global.CONFIG][
                         Global.OPTIONS][Global.TIME]:
                     if Global.RATIO in self.config[Global.CONFIG][
                             Global.OPTIONS][Global.TIME][Global.FAST]:
                         self.fast_ratio = int(
                             self.config[Global.CONFIG][Global.OPTIONS][
                                 Global.TIME][Global.FAST][Global.RATIO])
                     if Global.INTERVAL in self.config[Global.CONFIG][
                             Global.OPTIONS][Global.TIME][Global.FAST]:
                         self.fast_interval = int(
                             self.config[Global.CONFIG][Global.OPTIONS][
                                 Global.TIME][Global.FAST][Global.INTERVAL])
             if Global.PING in self.config[Global.CONFIG][Global.OPTIONS]:
                 self.ping_interval = self.config[Global.CONFIG][
                     Global.OPTIONS][Global.PING]
             if Global.BACKUP in self.config[Global.CONFIG][Global.OPTIONS]:
                 self.backup_path = self.config[Global.CONFIG][
                     Global.OPTIONS][Global.BACKUP]
     self.roster = Roster(self.log_queue,
                          file_path=Global.DATA + "/" + Global.ROSTER +
                          ".json")
     self.switches = Switches(self.log_queue,
                              file_path=Global.DATA + "/" +
                              Global.SWITCHES + ".json")
     self.warrants = Warrants(self.log_queue,
                              file_path=Global.DATA + "/" +
                              Global.WARRANTS + ".json")
     self.signals = Signals(self.log_queue,
                            file_path=Global.DATA + "/" + Global.SIGNALS +
                            ".json")
     self.layout = Layout(self.log_queue,
                          file_path=Global.DATA + "/" + Global.LAYOUT +
                          ".json")
     self.dashboard = Dashboard(self.log_queue,
                                file_path=Global.DATA + "/" +
                                Global.DASHBOARD + ".json")
     self.sensors = Sensors(self.log_queue,
                            file_path=Global.DATA + "/" + Global.SENSORS +
                            ".json")
Example #14
0
    def __init__(self, workspace):
        Layout.__init__(self, workspace)

        self.maxmasters = 1

        self.root = TileRoot()
        self.root.add_child(TileVerticalBox(self.root))
        self.master = TileHorizontalBox(self.root.child)
        self.slave = TileHorizontalBox(self.root.child)

        self.proportions = (0.5, 0.5)
Example #15
0
 def __init__(self, player_no=0):
     self.field = Field()
     self.queue = MinoQueue()
     self.score = Score()
     self.__holding = Holding()
     self.layout = Layout(self.field, self.queue, self.score,
                          self.__holding, player_no)
     self.mino = self.queue.get_next()
     self.state = GameState.PLAYING
     self.__reset_counter()
     self.player_no = player_no
Example #16
0
    def __init__(self, workspace):
        Layout.__init__(self, workspace)

        self.maxmasters = 1

        self.root = TileRoot()
        self.root.add_child(TileVerticalBox(self.root))
        self.master = TileHorizontalBox(self.root.child)
        self.slave = TileHorizontalBox(self.root.child)

        self.proportions = (0.5, 0.5)
 def test_polygon_corners(self):
     """Test polygon corners."""
     hexagon = Hex(1, 0, -1)
     pointy = Layout(10, (200, 200))
     self.assertEqual(pointy.polygon_corners(hexagon),
                      [(225.98076211353316, 205.0),
                       (225.98076211353316, 195.0),
                       (217.32050807568876, 190.0),
                       (208.66025403784437, 195.0),
                       (208.66025403784437, 205.0),
                       (217.32050807568876, 210.0)])
Example #18
0
def pipeline(inputs):
    # inputs = interface.load_inputs(sys.argv)

    layout = Layout(inputs)
    try:
        # layout.elevate('poly','m1')
        controller.lafrieda(layout, inputs)
    except KeyboardInterrupt:
        inputs['output'] = 'interrupted-' + inputs['output']
        print(
            aux.color_format(
                "\n\nKeyboard interrupt. Output current layout to {}".format(
                    inputs['output']), 'HEADER'))
    layout.emit_tcl(inputs['output'])
    aux.Timer.print_times()
Example #19
0
    def add(self, client, force_master=False, doplace=True):
        Layout.add(self, client)

        self.save(client)

        if force_master or self._masters() < self.maxmasters:
            self._add_master(client)
        else:
            if self._get_focused_section() is self.master:
                self._add_master(client)
            else:
                self._add_slave(client)

        if doplace:
            self.place()
Example #20
0
    def add(self, client, force_master=False, doplace=True):
        Layout.add(self, client)

        self.save(client)

        if force_master or self._masters() < self.maxmasters:
            self._add_master(client)
        else:
            if self._get_focused_section() is self.master:
                self._add_master(client)
            else:
                self._add_slave(client)

        if doplace:
            self.place()
def find_maximum_power_budget(layout):

    # No search because the user specified a fixed power budget?
    if (utils.argv.power_budget):
        [temperature, power_distribution] = optimize_power_distribution(
            layout, utils.argv.power_budget, utils.argv.powerdistopt,
            utils.argv.power_distribution_optimization_num_trials,
            utils.argv.power_distribution_optimization_num_iterations)
        [power_distribution, temperature
         ] = make_power_distribution_feasible(layout, power_distribution,
                                              temperature)
        return [power_distribution, temperature]

    # No search because the maximum power possible is already below temperature?
    utils.info(1, "Checking if the maximum power is cool enough")
    temperature = Layout.compute_layout_temperature(
        layout,
        [layout.get_chip().get_power_levels()[-1]] * layout.get_num_chips())
    if (temperature <= utils.argv.max_allowed_temperature):
        #utils.info(2, "We can set all chips to the max power level!")
        return [[layout.get_chip().get_power_levels()[-1]] *
                layout.get_num_chips(), temperature]

    # No search because the minimum power possible is already above temperature?
    utils.info(1, "Checking if the minimum power is already too hot")
    temperature = Layout.compute_layout_temperature(
        layout,
        [layout.get_chip().get_power_levels()[0]] * layout.get_num_chips())
    if (temperature > utils.argv.max_allowed_temperature):
        sys.stderr.write(
            "Even setting all chips to minimum power gives a temperature of " +
            str(temperature) +
            ", which is above the maximum allowed temperature of " +
            str(utils.argv.max_allowed_temperature) + "\n")
        return None

    # DISCRETE?
    if is_power_optimization_method_discrete(utils.argv.powerdistopt):
        [power_distribution,
         temperature] = find_maximum_power_budget_discrete(layout)
        return [power_distribution, temperature]
    else:  # OR CONTINUOUS?
        [power_distribution,
         temperature] = find_maximum_power_budget_continuous(layout)
        [power_distribution, temperature
         ] = make_power_distribution_feasible(layout, power_distribution,
                                              temperature)
        return [power_distribution, temperature]
Example #22
0
def make_walls():
    # get data from google spreadsheet table
    print('Getting data...')
    gcw = GoogleClientWrapper();
    data = gcw.gs_aslist(config['input_table']['spreadsheetid'], config['input_table']['named_range'])

    # filter by scenename in config
    filtered = list(filter(lambda v: v['scene'] == config['arena']['scenename'], data))

    # get layout coordinates
    t = Layout(getattr(Layout, config[config['arena']['scenename']]['layout']), filtered).get_transforms(**(config[config['arena']['scenename']]['layout_args']))

    btns = {}
    for i in range(len(filtered)):
        wall_btns = make_wall(
            filtered[i]['id'], # use id as a suffix for the objects of each wall
            Position(t[i]['x'], t[i]['y'], t[i]['z']), # position as given by the layout
            Rotation(t[i]['rx'],t[i]['ry'],t[i]['rz']), # rotation as given by layout
            filtered[i],
            config,
        )

        btns.update(wall_btns)

    # save buttons data on gdrive
    gcw.gd_save_json(config['links_config']['fileid'], btns, f'{config["input_table"]["spreadsheetid"]}.json');

    print('\nDone. Press Ctrl+C to disconnect.')
def find_maximum_power_budget_discrete_random(layout):
    power_levels = layout.get_chip().get_power_levels()
    distribution = layout.get_chip().get_power_levels(
    )[0] * layout.get_num_chips()
    best_distribution = None
    best_distribution_temperature = None

    for trial in xrange(0,
                        utils.argv.power_distribution_optimization_num_trials):
        utils.info(2, "Trial #" + str(trial))
        distribution = []
        for i in xrange(0, layout.get_num_chips()):
            distribution.append(utils.pick_random_element(power_levels))
        temperature = Layout.compute_layout_temperature(layout, distribution)
        if (temperature <= utils.argv.max_allowed_temperature):
            if (best_distribution
                    == None) or (sum(best_distribution) < sum(distribution)):
                best_distribution = distribution
                best_distribution_temperature = temperature
                utils.info(
                    2, "Better Random Trial: Total=" +
                    str(sum(best_distribution)) + "; Distribution=" +
                    str(best_distribution) + "; Temperature= " +
                    str(temperature))

    return [best_distribution, best_distribution_temperature]
Example #24
0
def load_board(filepath):
    
    f = open(filepath)
    lines = f.readlines()
    f.close()
    
    head = lines[0]
    lines = lines[1:]
    
    nrows_area, ncols_area = [int(s.strip()) for s in head.split()]
    board = Board(Layout(nrows_area, ncols_area))
    
    row = 0
    for line in lines:
        line = line.strip()
        col = 0
        for ch in line:
            try:
                value = int(ch)
                if value:
                    board = board.set_value((row, col), value)
                col += 1
            except ValueError:
                pass
        row += 1
        if row == board.get_layout().get_size():
            break
    return board
Example #25
0
  def __init__(self, filename, width, height):
    json = self.read_json(filename)
    self.preferred_team = json.get("preferred_team", "Cubs")
    self.preferred_division = json.get("preferred_division", "NL Central")
    self.rotate_games = json.get("rotate_games", False)
    self.rotate_rates = json.get("rotate_rates", DEFAULT_ROTATE_RATES)
    self.stay_on_live_preferred_team = json.get("stay_on_live_preferred_team", True)
    self.display_standings = json.get("display_standings", False)
    self.display_standings_on_offday = json.get("display_standings_on_offday", True)
    self.scroll_until_finished = json.get("scroll_until_finished", True)
    self.end_of_day = json.get("end_of_day", "00:00")
    self.display_full_team_names = json.get("display_full_team_names", True)
    self.slower_scrolling = json.get("slower_scrolling", False)
    self.debug_enabled = json.get("debug_enabled", False)

    # Get the layout info
    json = self.__get_layout(width, height)
    self.layout = Layout(json, width, height)

    # Store color information
    json = self.__get_colors("teams")
    self.team_colors = Color(json)
    json = self.__get_colors("scoreboard")
    self.scoreboard_colors = Color(json)

    #Check the rotate_rates to make sure it's valid and not silly
    self.check_rotate_rates()
    self.check_display_standings_on_offday()
def make_flame(args):
    """
    Use the arguments to make a flame file.
    """
    # Select the padding style
    pad_char = 'â–ˆ' if args.block_padding else ' '
    text = Text(args.text, pad_char)

    # Read in the font and sanitize the text
    font = Font()
    text.sanitize(font.alphabet)

    print("Making fractal for the following text:")
    print(text)

    # The Layout handles positioning each character of text
    layout = Layout(font, text)

    # The AffineFinder calculates the necessary transformation
    # matricies. It returns XForm Objects
    finder = AffineFinder(layout.bounding_box)
    xforms = list(finder.find_xforms(layout.geometry))

    print("This fractal will use {} xforms + final xform".format(len(xforms)))

    writer = FlameWriter()
    writer.write(args.fname, args.flame_name, xforms)
Example #27
0
    def start(self):
        self.layout = Layout(LEVEL_ONE_GRID_FOLDER)

        self._init_pygame()

        self._load_sprites()

        self._fill_limit_cells()

        clock = pygame.time.Clock()        

        while self.status:
            # Limit frame speed to 60 FPS.
            time_passed = clock.tick(60)

            # Handle key events.
            for event in pygame.event.get():
                self._on_event(event)

            self._on_render()

            # Update all of the needed sprites
            self._on_loop()


        # Close app.
        self._on_cleanup()
Example #28
0
    def __init__(self, audio_input):
        self.layout = Layout()
        self.audio_input = audio_input
        if self.use_redis:
            self.redis = redis.StrictRedis()
        self.fc_client = opc.Client(self.FADECANDY_SERVER)

        # create a list of all visualizations, add new ones here
        self.create_viz_list()

        # event loop: read config, run current viz and save layout
        self.audio_input.register_read_listener(
            self.config_reader
        )
        self.audio_input.register_read_listener(
            self.current_viz
        )
        self.audio_input.register_read_listener(
            self.layout_handler
        )
        self.audio_input.register_read_listener(
            self.print_stats
        )

        # use first visualization as the initial one
        self.activate_viz(0)
Example #29
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
            'cluster',
            help='the cluster to connect to.')
    parser.add_argument(
            '-c', '--config', default=DEFAULT_CONFIG,
            help='the config file to use (default "%s").' % DEFAULT_CONFIG)
    parser.add_argument(
           '-v', '--verbose', action='store_true', default=False,
            help='increases log verbosity.')
    args = parser.parse_args()

    if args.verbose:
        logging.basicConfig(level=logging.DEBUG)

    config = Config(path=args.config).cluster(args.cluster)
    logging.debug('Cluster config: %s', config)

    layout = Layout(config)
    logging.debug('Layout: %s', layout)

    window = Window(config)
    logging.debug('Window: %s', window)

    applescript = AppleScript(config, layout, window)
    applescript.launch()
    def add_circular_arc_perturbed(self, n, cx, cy, delta_theta, r0, r1,
                                   perturb_r0, perturb_r1):
        r = (cx**2 + cy**2)**0.5
        t = degrees(atan2(cy, cx))
        x, y = self.circular_arc(n, r, delta_theta)
        x, y = Layout.rotate_coords(x, y, t)
        # Linear scaling
        # scale = perturb_r0 + (perturb_r1 - perturb_r0) * ((r - r0) / (r1 - r0))
        # Log scaling
        a = r1 - r
        b = r - r0
        f = b / (a + b)
        scale = perturb_r1**f * perturb_r0**(1 - f)
        # print(r0, r1, perturb_r0, perturb_r1, r, scale)

        for i in range(len(x)):
            t = np.random.rand() * 2 * np.pi
            rt = np.random.rand() * scale
            x[i] += rt * cos(t)
            y[i] += rt * sin(t)
        self.layouts[self._get_key('circular_arc_p')] = {
            'x': x,
            'y': y,
            'cx': cx,
            'cy': cy
        }
Example #31
0
def get_layout(layout_type='vstack',
               Left=0,
               Height=20,
               Top=0,
               Width=20,
               TopMargin=6,
               RightMargin=6,
               BottomMargin=6,
               LeftMargin=6):

    lc_type = layout_type.lower()
    if lc_type == 'vstack':
        return VStackPanel(**key_word_args(LAYOUT_PARAML, locals()))
    elif lc_type == 'hstack':
        return HStackPanel(**key_word_args(LAYOUT_PARAML, locals()))
    elif lc_type == 'grid':
        return GridPanel(**key_word_args(LAYOUT_PARAML, locals()))
    elif lc_type == 'canvas':
        return Layout(**key_word_args(LAYOUT_PARAML, locals()))
    else:
        print '=' * 30, 'WARNING', '=' * 30
        print '  bad layout_type in call to get_layout, Illegal layout_type = "%s"' % layout_type
        print '  Using Vertical Stack layout by default = "vstack"'
        print '=' * 30, 'WARNING', '=' * 30
        return VStackPanel(**key_word_args(LAYOUT_PARAML, locals()))
def generateLayout(gameData):
    height = gameData.mazeHeight
    length = gameData.mazeLength
    posPacman = gameData.posPacman
    posGhost = gameData.posGhost
    listFood = gameData.listFood
    listCapsule = gameData.listCapsule

    layoutText = [None] * (2 + height)
    wall = "%" * (length + 2)
    layoutText[0] = wall
    layoutText[height + 1] = wall

    for x in range(1, (height + 1)):
        row = "%"

        for k in range(1, (length + 1)):
            if k == posPacman:
                row += "P"
            elif k == posGhost:
                row += "G"
            elif k in listFood:
                row += "."
            elif k in listCapsule:
                row += "o"
            else:
                row += " "

        row += "%"
        layoutText[x] = row

    return Layout(layoutText)
Example #33
0
    def _getSettingsAsDict():
        """
        Returns the settings as a dictionary.
        Possible keys:
        *- "DEBUG_MODE" , True or False
        *- "DISPLAY_TYPE" , the type of the display
        *- "MrX_TYPE" , Mr.X type of instance : Keyboard, ..
        *- "COPS_TYPE" , Cop type of instance : Keyboard, ..
        *- "LAYOUT_FILENAME", the path of the layout file name (.txt)
        *- "MAX_NUM_MOVES" , the max number of moves of Mr.X for one game
        *- "INITIAL_MrX_POSITION" , an integer or the string "random"
        *- "INITIAL_COPS_POSITION" , a list (size = "NUMBER_OF_COPS" ) of integer or the 
                                    string "random" separated by commas (the order matters)
        *- "NOT_HIDDEN_MOVES" , the numbers of not hidden moves : a list of integers separated by commas.
        *- "MrX_TICKETS" , format: <TicketType>=<int> ; <TicketType>=<int>; ... 
        *- "COPS_TICKETS" , format: <TicketType>=<int> ; <TicketType>=<int>; ...
         ...
        """
        # initialize setting dictionary
        if len(Settings.settings) == 0:
            Settings._loadSettings(SETTINGS_FILE_NAME)

        # initialize the layout
        if Settings.layout is None:
            Settings.layout = Layout(Settings.settings["LAYOUT_FILENAME"])

        #if Settings.positions is None:
        #    Settings._assignPositions()

        return Settings.settings
Example #34
0
    def initializeLayout(self):
        def getv(r, v1, v2):
            return numpy.array(v1) * (1 - r) + numpy.array(v2) * r

        oml0 = self.oml0
        Ms = self.Ms
        Js = self.Js

        edges = []
        edges.append([0, 0, 0, 1])
        edges.append([0, 0, 1, 0])
        edges.append([0, 1, 1, 1])
        edges.append([1, 0, 1, 1])

        skinIndices = self.getSkinIndices()
        for s in range(len(skinIndices)):
            for f in skinIndices[s]:
                for k in range(Js[f].shape[0]):
                    C11 = oml0.C[Ms[f][Js[f][k, 0], Js[f][k, 1]], :2]
                    C12 = oml0.C[Ms[f][Js[f][k, 0], Js[f][k, 3]], :2]
                    C21 = oml0.C[Ms[f][Js[f][k, 2], Js[f][k, 1]], :2]
                    C22 = oml0.C[Ms[f][Js[f][k, 2], Js[f][k, 3]], :2]
                    edges.append([C11[0], C11[1], C12[0], C12[1]])
                    edges.append([C11[0], C11[1], C21[0], C21[1]])
                    edges.append([C12[0], C12[1], C22[0], C22[1]])
                    edges.append([C21[0], C21[1], C22[0], C22[1]])
        for m in self.keys:
            member = self.members[m]
            for i in range(member.nmem):
                if member.nmem == 1:
                    ii = 0
                else:
                    ii = i / (member.nmem - 1)
                A = getv(ii, member.A1, member.A2)
                B = getv(ii, member.B1, member.B2)
                C = getv(ii, member.C1, member.C2)
                D = getv(ii, member.D1, member.D2)
                for j in range(member.ndiv):
                    if (B[2] == 0 and C[2] == 0) or (B[2] == 1 and C[2] == 1):
                        V0 = getv(j / member.ndiv, B, C)
                        V1 = getv((j + 1) / member.ndiv, B, C)
                        edges.append([V0[0], V0[1], V1[0], V1[1]])
                    if (A[2] == 0 and D[2] == 0) or (A[2] == 1 and D[2] == 1):
                        V0 = getv(j / member.ndiv, A, D)
                        V1 = getv((j + 1) / member.ndiv, A, D)
                        edges.append([V0[0], V0[1], V1[0], V1[1]])
        self.layout = Layout(6, self.getAR(), 1, numpy.array(edges))
Example #35
0
 def getLayout():
     """
     Returns the layout (Layout in layout.py).
     """
     if Settings.layout is None:
         Settings.layout = Layout(
             Settings._getSettingsAsDict()["LAYOUT_FILENAME"])
     return Settings.layout
Example #36
0
def load_layout(infile='-'):
    import fileinput
    from layout import Layout

    buffer = []
    for line in fileinput.input():
        buffer.append(line.strip())

    return Layout(buffer)
Example #37
0
def main():
    clock = pygame.time.Clock()
    board = Board(100, 100)
    board.randomFill(30)

    conway = Conway(board)
    layout = Layout(board, conway)

    while True:  # main game loop
        for event in pygame.event.get():
            handleEvent(layout, event)

        if (not conway.running):
            handleEvent(layout, pygame.event.wait())
        else:
            conway.next()
            layout.update(force=True)
        pygame.display.update()
        clock.tick(10)
Example #38
0
 def __init__(self, _layout_filename):
     assert os.path.exists(
         _layout_filename
     ), '_layout file: %s does not exist!' % _layout_filename
     with open(_layout_filename) as f:
         self._layout = Layout([line.strip() for line in f])
     self._query_count = 0
     self._query_limit = self._layout.width * self._layout.height
     self._bonus_count = 0
     self._action_count = 0
Example #39
0
    def __init__(self, main, x, y, width, height=0):
        Window.__init__(self, main, x, y, width, height)
        self.grid_size = 10
        self.grid_visible = True
        self.selected_stamp = None
        self.snap_to_grid = False
        self.keep_current_ratio = False
        self.keep_original_ratio = False

        self.layout = Layout(self.main.shape_window.shape)
        self.colors = [pygame.Color('white')] * 10
Example #40
0
    def createFromExisting(cls, source, name, port, debug=None, info=None, error=None):
        """
        Create a TouchOSC LayoutServer from an existing TouchOSC Layout file.

        @type source: filename or fileobject
        @param source: Path to an existing .touchosc file, or
            TouchOSC index.xml file (from unzipping .touchosc file)
        @rtype: Layout
        @return: An instance containing the layout
        """
        layout = Layout.createFromExisting(source)

        return LayoutServer(layout, name, port, debug, info, error)
Example #41
0
    def __init__(self, keys=None, theme=None):
        """ initilizes the gui """

        import __builtin__

        __builtin__.gui = self

        self.node = aspect2d

        self.id = "root"

        self.dragWidget = None
        self.dragPos = Vec2(0, 0)
        self.dragFun = None
        self.dragSnap = False
        self.lastDragMoue = Vec2(0, 0)
        self.hoveringOver = None

        self.parent = False
        self.children = []
        self.idToFrame = {}

        self.pos = Vec2(0, 0)
        self.windowsize = 800, 600
        self.size = Vec2(*self.windowsize)

        self.mouse = Vec2(0, 0)
        self.node.setBin("fixed", 2)
        self.node.setDepthWrite(False)
        self.node.setDepthTest(False)

        if not keys:
            self.keys = Keys()
        else:
            self.keys = keys

        if not theme:
            self.theme = Theme()
        else:
            self.theme = theme
        self.layout = Layout()
        self.drawer = Drawer()

        task(self._doMouse, -10)

        self._reSize()

        task(self._doDrag, 10)
        task(self._reSize, 20)
        task(self._layout, 30)
        task(self._draw, 40)
Example #42
0
    def initializeLayout(self):
        def getv(r, v1, v2):
            return numpy.array(v1) * (1 - r) + numpy.array(v2) * r

        oml0 = self.oml0
        Ms = self.Ms
        Js = self.Js

        edges = []
        edges.append([0, 0, 0, 1])
        edges.append([0, 0, 1, 0])
        edges.append([0, 1, 1, 1])
        edges.append([1, 0, 1, 1])

        skinIndices = self.getSkinIndices()
        for s in range(len(skinIndices)):
            for f in skinIndices[s]:
                for k in range(Js[f].shape[0]):
                    C11 = oml0.C[Ms[f][Js[f][k, 0], Js[f][k, 1]], :2]
                    C12 = oml0.C[Ms[f][Js[f][k, 0], Js[f][k, 3]], :2]
                    C21 = oml0.C[Ms[f][Js[f][k, 2], Js[f][k, 1]], :2]
                    C22 = oml0.C[Ms[f][Js[f][k, 2], Js[f][k, 3]], :2]
                    edges.append([C11[0], C11[1], C12[0], C12[1]])
                    edges.append([C11[0], C11[1], C21[0], C21[1]])
                    edges.append([C12[0], C12[1], C22[0], C22[1]])
                    edges.append([C21[0], C21[1], C22[0], C22[1]])
        for m in self.keys:
            member = self.members[m]
            for i in range(member.nmem):
                if member.nmem == 1:
                    ii = 0
                else:
                    ii = i / (member.nmem - 1)
                A = getv(ii, member.A1, member.A2)
                B = getv(ii, member.B1, member.B2)
                C = getv(ii, member.C1, member.C2)
                D = getv(ii, member.D1, member.D2)
                for j in range(member.ndiv):
                    if (B[2] == 0 and C[2] == 0) or (B[2] == 1 and C[2] == 1):
                        V0 = getv(j / member.ndiv, B, C)
                        V1 = getv((j + 1) / member.ndiv, B, C)
                        edges.append([V0[0], V0[1], V1[0], V1[1]])
                    if (A[2] == 0 and D[2] == 0) or (A[2] == 1 and D[2] == 1):
                        V0 = getv(j / member.ndiv, A, D)
                        V1 = getv((j + 1) / member.ndiv, A, D)
                        edges.append([V0[0], V0[1], V1[0], V1[1]])
        self.layout = Layout(6, self.getAR(), 1, numpy.array(edges))
Example #43
0
    def __init__(self):
        super().__init__()

        self.initUI()

        self.keyboard_state = {'North' : False, 'South' : False, 'West' : False, 'East' : False, 'Stop' : False}

        self.agents = [HumanAgent(0), StopAgent(1)]
        self.layout = Layout()
        self.layout.load_from_file("test.lay")
        self.colors = {Tile.Empty: QBrush(QColor(26,26,26)),
                       Tile.Wall: QBrush(QColor(12,12,225)),
                       Tile.Start: QBrush(QColor(255,255,0))}

        self.game = PacmanGame(self.layout)
        self.current_game_state = self.game.get_initial_game_state()

        self.timer = QBasicTimer()

        self.timer.start(500, self)
Example #44
0
    def __init__(self, size, *args, **kw):
        Widget.__init__(self, *args, **kw)
        self._size = MovingValue(Point, final=Point(size))
        self.nodes = set()
        self.edges = set()
        self.node_widgets = Dict()
        self.edge_widgets = Dict()
        self.sorted_widgets = SortedItems(self.node_widgets)

        self.layout = Layout()
        
        self.selected_widget_index = None
        self._update_index()

        self._node_link_start_pos = None
        self._node_link_source_node = None
        self._node_link_color = None
        
        self._register_keys()
        self._save_next_display_update = False
Example #45
0
        self.decamins = decamins
        self.mins = mins

    def display_time(self):
        h, m = time.localtime()[3:5]  # sure? check
        self.hours.change_state(h)
        self.decamins.change_state(m / 10) # dovrebbe cambiare la divisione
        # tra 2.7 e 3 passando da int a float... ocjio
        self.mins.change_state(m % 10)

    def test_time(self, h, m):
        self.hours.change_state(h)
        self.decamins.change_state(m / 10)
        self.mins.change_state(m % 10)


if __name__ == "__main__":
    l = Layout(screen)
    c = Clock(l.balls, l.triangle, l.penthagon)
    while True:
        c.display_time()
        l.draw()
        time.sleep(20)




# non mi piace molto l'organizzazione,
# meglio da clock aggiungere gli elementi al layout forse

# cioè?
Example #46
0
	def __init__( self ):

		Layout.__init__( self )

		self.image = []
Example #47
0
class GraphWidget(Widget):
    bg_color=(0,0,0)
    activated_bg_color=(10,10,20)

    key_create_node = Key(pygame.KMOD_CTRL, pygame.K_a)
    key_delete_node = Key(pygame.KMOD_CTRL, pygame.K_d)
    key_next_node = Key(0, pygame.K_TAB)
    key_prev_node = Key(pygame.KMOD_SHIFT, pygame.K_TAB)
    key_select_node_right = Key(0, pygame.K_RIGHT)
    key_select_node_left = Key(0, pygame.K_LEFT)
    key_select_node_up = Key(0, pygame.K_UP)
    key_select_node_down = Key(0, pygame.K_DOWN)
    key_connect = Key(pygame.KMOD_CTRL, pygame.K_RETURN)
    key_disconnect = Key(pygame.KMOD_CTRL, pygame.K_BACKSPACE)
    key_cycle_layout = Key(pygame.KMOD_CTRL, pygame.K_k)
    #key_export_dot = Key(pygame.KMOD_CTRL, pygame.K_)
    key_export_snapshot = Key(pygame.KMOD_CTRL, pygame.K_x)

    key_save = Key(pygame.KMOD_CTRL, pygame.K_s)
    key_load = Key(pygame.KMOD_CTRL, pygame.K_l)
    
    def __init__(self, size, *args, **kw):
        Widget.__init__(self, *args, **kw)
        self._size = MovingValue(Point, final=Point(size))
        self.nodes = set()
        self.edges = set()
        self.node_widgets = Dict()
        self.edge_widgets = Dict()
        self.sorted_widgets = SortedItems(self.node_widgets)

        self.layout = Layout()
        
        self.selected_widget_index = None
        self._update_index()

        self._node_link_start_pos = None
        self._node_link_source_node = None
        self._node_link_color = None
        
        self._register_keys()
        self._save_next_display_update = False
        
    def __getstate__(self):
        d = Widget.__getstate__(self)
        del d['parenting_keymap']
        return d
    def __setstate__(self, d):
        Widget.__setstate__(self, d)
        self._register_keys()

    def _register_keys(self):
        self.parenting_keymap = Keymap()
        r = self.keymap.register_key
        r(self.key_create_node, keydown_noarg(self._create_new_node))
        r(self.key_cycle_layout, keydown_noarg(self._cycle_layout_engine))
        r(self.key_save, keydown_noarg(self._save))
        r(self.key_load, keydown_noarg(self._load))
        r(self.key_export_snapshot, keydown_noarg(self._export_snapshot))
        self._set_next_keymap()

    def get_size(self):
        return tuple(self._size.current)
    def set_size(self, p):
        self._size.final = p 
    size = property(get_size, set_size)
    
    def _node_connect(self, e):
        for node in e.source, e.target:
            if node not in self.nodes:
                self.add_node(node)
        if e not in self.edges:
            self.add_edge(e)
    def _node_disconnect(self, e):
        self.remove_edge(e)

    def update_edges_lines(self, widget, node):
        center = Point(widget.final_rect().center)
        for edge in node.connections['in']:
            edge_w = self.edge_widgets[edge]
            edge_w.line.final[-1] = center.copy()
            edge_w.line.reset()
        for edge in node.connections['out']:
            edge_w = self.edge_widgets[edge]
            edge_w.line.final[0] = center.copy()
            edge_w.line.reset()
        
    def _node_widget_loc_pos_set(self, widget, node, new_pos):
        self.update_edges_lines(widget, node)
    def _node_widget_loc_size_set(self, widget, node, new_size):
        self.update_edges_lines(widget, node)
        
    def add_edge(self, edge):
        edge.obs.add_observer(self, '_edge_')
        self.edges.add(edge)
        if edge.source not in self.node_widgets:
            self.add_node(edge.source)
            
        source = self.node_widgets[edge.source].final_rect().center
        if edge.target not in self.node_widgets:
            self.add_node(edge.target)
            
        target = self.node_widgets[edge.target].final_rect().center
        w = EdgeWidget(edge, partial(self.node_widgets.get),
                       MovingLine(list, [Point(source), Point(target)]))
        self.edge_widgets[edge] = w
        self.update_layout()
    def remove_edge(self, edge):
        edge.obs.remove_observer(self)
        del self.edge_widgets[edge]
        self.edges.remove(edge)
        self.update_layout()

    def add_node(self, node):
        if node in self.nodes:
            return
        self.nodes.add(node)
        w = NodeWidget(node)
        self.node_widgets[node] = w
        node.obs.add_observer(self, '_node_')
        w.obs_loc.add_observer(self, '_node_widget_loc_', w, node)
        loop.loop.mouse_map.push_area(w.mouse_area, partial(self._widget_mouse_event, node, w))
        # They might be adding a node that is connected to some other,
        # yet-to-be added nodes
        for edge in node.iter_all_connections():
            self.add_edge(edge)
        self.update_layout()
        return w
    def remove_node(self, node):
        node.disconnect_all()
        w = self.node_widgets[node]
        loop.loop.mouse_map.remove_area(w.mouse_area)
        w.obs_loc.remove_observer(self)
        node.obs.remove_observer(self)
        del self.node_widgets[node]
        self.nodes.remove(node)
        self._update_index()
        if self._node_link_source_node:
            self._node_link_source_node = None
        self.update_layout()
        return w

    def generate_groups(self):
        groups = {'0':[]}
        for node in self.nodes:
            groups['0'].append(node)
        return groups

    def update_layout(self):
        groups = self.generate_groups()
        self.layout.update(groups, self.size, self.node_widgets, self.edge_widgets)
        
    def update(self):
        if self.node_widgets:
            import math
            # todo rewrite this shitty code
            sizes = {}
            slots = {}
            slot_places = {}
            average = 0
            num = len(self.node_widgets)
            for w in self.node_widgets.values():
                size = w.reset_max_text_size()
                sizes[w] = size
            for w, size in sizes.iteritems():
                dist = int(round(math.log(size + 1)/2.))
                slot = dist 
                slots.setdefault(slot, size)
                slots[slot] = min(slots[slot],size)
                
                slot_places[w] = slot

            for w,slot in slot_places.iteritems():
                size = sizes[w]
                new_max_size = slots[slot]
                if new_max_size < size:
                    w.reset_max_text_size(new_max_size)
                w.update()

##             for w in self.node_widgets.values():
##                 w.reset_max_text_size()
##                 w.update()
        for w in self.edge_widgets.itervalues():
            w.update()
        self._size.update()
        
        
    def _draw(self, surface, pos):
        for w in self.edge_widgets.values():
            p = Point(pos)
            w._draw(surface, pos)
        for w in self.node_widgets.values():
            # for our children, pos is the parent's pos offset
            # because of how NodeWidget works.
            w._draw(surface, pos)

        if self._node_link_start_pos is not None:
            n,w = self.selected()
            if w is not None:
                start_pos = self._node_link_start_pos()
                end_pos = self._node_link_end_pos()
                draw.line(surface, self._node_link_color, start_pos, end_pos)

        if self._save_next_display_update:
            self._save_next_display_update = None
            draw.save(surface.subsurface(pygame.Rect(pos, self.size)), self._save_next_display_update)

    def selected(self):
        if self.selected_widget_index is None:
            return None, None
        return self.sorted_widgets[self.selected_widget_index]
    
    def _set_next_keymap(self):
        self.keymap.set_next_keymap(self.parenting_keymap)
        if self.selected_widget_index is not None:
            self.parenting_keymap.set_next_keymap(self.selected()[1].keymap)
            r = self.parenting_keymap.register_key
            r(self.key_delete_node, keydown_noarg(self._delete_selected_node))
            r(self.key_next_node, keydown_noarg(self._next_node))
            r(self.key_prev_node, keydown_noarg(self._prev_node))
            r(self.key_select_node_right, keydown_noarg(self._select_node_right))
            r(self.key_select_node_left, keydown_noarg(self._select_node_left))
            r(self.key_select_node_up, keydown_noarg(self._select_node_up))
            r(self.key_select_node_down, keydown_noarg(self._select_node_down))
            if self.key_connect not in self.parenting_keymap:
                r(self.key_connect, keydown_noarg(self._start_connect))
            if self.key_disconnect not in self.parenting_keymap:
                r(self.key_disconnect, keydown_noarg(self._start_disconnect))
        else:
            ur = self.parenting_keymap.unregister_key
            ur(self.key_next_node)
            ur(self.key_prev_node)
            ur(self.key_select_node_right)
            ur(self.key_select_node_left)
            ur(self.key_select_node_up)
            ur(self.key_select_node_down)
            ur(self.key_delete_node)
            ur(self.key_connect)
            ur(self.key_disconnect)
            self.parenting_keymap.set_next_keymap(self.focus_keymap)
    
    def _set_index(self, index):
        if self.selected_widget_index != index:
            self.selected_widget_index = index
        self._update_index()

    def _update_index(self):
        if not self.node_widgets:
            self.selected_widget_index = None
        elif self.selected_widget_index is not None:
            self.selected_widget_index %= len(self.sorted_widgets)
            self._set_next_keymap()
            
    def _find_widget_index(self, w):
        for i, (node, widget) in enumerate(self.sorted_widgets):
            if w == widget:
                return i
            
    def _add_index(self, amount):
        if self.selected_widget_index is None:
            index = 0
        else:
            index = self.selected_widget_index
            l = len(self.sorted_widgets)
            index += amount
            index %= l
        self._set_index(index)


    def _next_node(self):
        '''Next node'''
        self._add_index(1)
    def _prev_node(self):
        '''Previous node'''
        self._add_index(-1)

    def _select_node_right(self):
        '''Select the next node to the right'''
        def dist(pos1, pos2):
            if pos1[0] < pos2[0]:
                return None
            return pos1[0] - pos2[0]
        self._select_node_dir(dist)
        
    def _select_node_left(self):
        '''Select the next node to the left'''
        def dist(pos1, pos2):
            if pos1[0] > pos2[0]:
                return None
            return pos2[0] - pos1[0]
        self._select_node_dir(dist)

    def _select_node_up(self):
        '''Select the next node above'''
        def dist(pos1, pos2):
            if pos1[1] > pos2[1]:
                return None
            return pos2[1] - pos1[1]
        self._select_node_dir(dist)

    def _select_node_down(self):
        '''Select the next node below'''
        def dist(pos1, pos2):
            if pos1[1] < pos2[1]:
                return None
            return pos1[1] - pos2[1]
        self._select_node_dir(dist)

    def _select_node_dir(self, distance_between):
        closest_right = None
        min_dist = None
        n, w = self.selected()
        if not w:
            return
        for widget in self.node_widgets.itervalues():
            if widget == w:
                continue
            dist = distance_between(widget.pos, w.pos)
            if dist is None:
                continue
            if closest_right is None or dist < min_dist:
                closest_right = widget
                min_dist = dist
                
        if closest_right is not None:
            i = self._find_widget_index(closest_right)
            self._set_index(i)
            
    def _create_new_node(self):
        '''Create new node'''
        n = Graph.Node()
        w = self.add_node(n)
        self._set_index(self._find_widget_index(w))
        
    def _delete_selected_node(self):
        '''Delete selected node'''
        n, w = self.sorted_widgets[self.selected_widget_index]
        self._add_index(1)
        self.remove_node(n)

    def _node_linking_started(self, key, start_func, connect_func, color, doc):
        r = self.parenting_keymap.register_key
        ur = self.parenting_keymap.unregister_key
        start_node, start_node_widget = self.selected()
        assert start_node is not None
        def _end_connect():
            ur(key)
            r(key, keydown_noarg(start_func))

            end_node, end_node_widget = self.sorted_widgets[self.selected_widget_index]
            self._node_link_func(start_node, end_node)
            self._node_link_start_pos = None
            self._node_link_end_pos = None
        _end_connect.__doc__ = doc
        
        def _start_pos():
            return start_node_widget.rect().center
        def _end_pos():
            n, w = self.selected()
            if w is None:
                return None
            return w.rect().center

        ur(key)
        r(key, keydown_noarg(_end_connect))
        self._node_link_start_pos = _start_pos
        self._node_link_end_pos = _end_pos
        self._node_link_color = color
        self._node_link_func = connect_func
        
    def _connect_func(self, node1, node2):
        node1.connect_node(node2)
    def _disconnect_func(self, node1, node2):
        node1.disconnect_node(node2)
        
    def _start_connect(self):
        '''Sets the source node to connect'''
        self._node_linking_started(self.key_connect, self._start_connect, self._connect_func, (0,255,0), "Sets the target node to connect")

    def _start_disconnect(self):
        '''Sets the source node to disconnect'''
        self._node_linking_started(self.key_disconnect, self._start_disconnect, self._disconnect_func, (255,0,0), "Sets the target node to disconnect")

    def _widget_mouse_event(self, node, widget, event):
        #print event
        connect_mod = pygame.key.get_mods() & pygame.KMOD_SHIFT 
        #disconnect_mod = pygame.key.get_modes() & pygame.KMOD_SHIFT 
        if event.type == pygame.MOUSEBUTTONDOWN:
            i = self._find_widget_index(widget)
            self._set_index(i)
            if connect_mod and self._node_link_start_pos is None:
                def _start_pos():
                    return widget.rect().center
                self._node_link_source_node = node
                self._node_link_start_pos = _start_pos
                self._node_link_end_pos = pygame.mouse.get_pos
                self._node_link_color = (0,255,0)
                self._node_link_func = self._connect_func
        elif event.type == pygame.MOUSEBUTTONUP:
            if self._node_link_source_node is not None:
                self._node_link_start_pos = None
                self._node_link_end_pos = None
                self._node_link_func(self._node_link_source_node, node)
                self._node_link_source_node = None
                self._node_link_color = None
                
        
    def _cycle_layout_engine(self):
        '''Change to the next layout engine'''
        self.layout.cycle_layout_engines()
        self.update_layout()

    def _save(self):
        '''Save'''
        import pickle
        f=open('save.pkl', 'wb')
        pickle.dump(self.nodes,f,2)

    def _load(self):
        '''Load'''
        import pickle
        f=open('save.pkl', 'rb')
        nodes = pickle.load(f)
        for node in tuple(self.nodes):
            self.remove_node(node)
        self._set_next_keymap()
        for node in nodes:
            # TODO if we are loading nodes in addition to existing nodes,
            # make sure ID's are re-allocated to prevent collisions.
            node.id = Graph.persistent_id(node)
            for edge in node.iter_all_connections():
                edge.id = Graph.persistent_id(edge)
        for node in nodes:
            self.add_node(node)
            

    def _export_dot(self):
        '''Export the graph to a .dot file'''
        d = Graph.generate_dot(self.generate_groups())
        print d
        open('save.dot', 'wb').write(d)

    def _export_snapshot(self):
        '''Export the graph to a snapshot image'''
        self._save_next_display_update = 'snapshot.bmp'
Example #48
0
class LayoutWindow(Window):
    LINE_COLOR = pygame.Color('white')
    SELECT_COLOR = pygame.Color('yellow')
    BASE_COLOR = pygame.Color('light blue')
    def __init__(self, main, x, y, width, height=0):
        Window.__init__(self, main, x, y, width, height)
        self.grid_size = 10
        self.grid_visible = True
        self.selected_stamp = None
        self.snap_to_grid = False
        self.keep_current_ratio = False
        self.keep_original_ratio = False

        self.layout = Layout(self.main.shape_window.shape)
        self.colors = [pygame.Color('white')] * 10

    def setDirty(self):
        self.dirty = True
        self.main.fractal_window.setDirty()

    def updateSurface(self):
        self.fillBgd()
        if self.grid_visible:
            self.drawGrid()

        offset_x = self.rect.width / 2
        offset_y = self.rect.height / 2

        color = self.SELECT_COLOR
        # Draw the hightlight under the lines
        if self.selected_stamp:
            stamp = self.selected_stamp
            if stamp == self.layout.getBaseStamp():
                color = self.BASE_COLOR

            rect = self.main.shape_window.shape.bounds.copy()
            rect.width *= stamp.scale[0]
            rect.height *= stamp.scale[1]
            width_greater_than_zero = rect.width > 0
            height_greater_than_zero = rect.height > 0
            rect.width = abs(rect.width)
            rect.height = abs(rect.height)
            # give the lines some room
            rect.width += 3
            rect.height += 3
            half_width = rect.width / 2
            half_height = rect.height / 2
            rect.center = (half_width, half_height)
            if rect.width > 0 and rect.height > 0:
                temp = pygame.Surface((rect.width, rect.height), pygame.SRCALPHA)
                pygame.draw.rect(temp, color, rect, 1)

                control_size = (stamp.control_size, stamp.control_size)
                rot_size = stamp.control_size / 2

                if width_greater_than_zero:
                    if height_greater_than_zero:
                        #s1 r1
                        #r2 s2
                        scale_pos1 = (0, 0)
                        scale_pos2 = (rect.width - control_size[0],
                                      rect.height - control_size[1])
                        rot_pos1 = (rect.width - control_size[0] + rot_size, rot_size)
                        rot_pos2 = (rot_size, rect.height - control_size[1] + rot_size)
                    else:
                        #r2 s2
                        #s1 r1
                        scale_pos1 = (0, rect.height - control_size[1])
                        scale_pos2 = (rect.width - control_size[0], 0)
                        rot_pos1 = (rect.width - control_size[0] + rot_size,
                                    rect.height - control_size[1] + rot_size)
                        rot_pos2 = (rot_size, rot_size)
                else:
                    if height_greater_than_zero:
                        #r1 s1
                        #s2 r2
                        scale_pos1 = (rect.width - control_size[0], 0)
                        scale_pos2 = (0, rect.height - control_size[1])
                        rot_pos1 = (rot_size, rot_size)
                        rot_pos2 = (rect.width - control_size[0] + rot_size,
                                    rect.height - control_size[1] + rot_size)
                    else:
                        #s2 r2
                        #r1 s1
                        scale_pos1 = (rect.width - control_size[0],
                                      rect.height - control_size[1])
                        scale_pos2 = (0, 0)
                        rot_pos1 = (rot_size, rect.height - control_size[1] + rot_size)
                        rot_pos2 = (rect.width - control_size[0] + rot_size, rot_size)

                scale_rect1 = pygame.Rect(scale_pos1, control_size)
                scale_rect2 = pygame.Rect(scale_pos2, control_size)
                pygame.draw.rect(temp, color, scale_rect1, 1)
                pygame.draw.rect(temp, color, scale_rect2, 1)
                pygame.draw.circle(temp, color, rot_pos1, rot_size, 1)
                pygame.draw.circle(temp, color, rot_pos2,rot_size, 1)
                                
                temp = pygame.transform.rotate(temp, stamp.angle)
                self.surface.blit(temp, ((self.surface.get_width() - temp.get_width()) / 2 + stamp.pos.x,
                                         (self.surface.get_height() - temp.get_height()) / 2 + stamp.pos.y))

        lines = self.main.shape_window.shape.getLines()
        shape_size = self.main.shape_window.shape.bounds.size
        for stamp in self.layout.getStamps():
            color = self.LINE_COLOR
            if stamp == self.layout.getBaseStamp():
                color = self.BASE_COLOR
            for line in lines:
                p1 = stamp.coords().applyCoords(line.point1)
                p2 = stamp.coords().applyCoords(line.point2)
                pygame.draw.line(self.surface, color,
                                 (p1.x + offset_x, p1.y + offset_y),
                                 (p2.x + offset_x, p2.y + offset_y))

        # Draw info over lines
        coords_str = "(,)"
        angle_str = "*"
        scale_str = "w: , h: "
        if self.selected_stamp:
            coords_str = "(%d, %d)" % (self.selected_stamp.pos.x, self.selected_stamp.pos.y)
            angle_str = "%.2f*" % (self.selected_stamp.angle)
            scale_str = "w: %.3f, h: %.3f" % (self.selected_stamp.scale)
            
        coords_text = self.main.plain_font.render(coords_str, 1,
                                                  self.main.TEXT_COLOR)

        
        angle_text = self.main.plain_font.render(angle_str, 1,
                                                self.main.TEXT_COLOR)

        
        scale_text = self.main.plain_font.render(scale_str, 1,
                                                self.main.TEXT_COLOR)
        
        self.surface.blit(coords_text, (0, 0))
        self.surface.blit(angle_text, (0, 20))
        self.surface.blit(scale_text, (0, 40))

##        ### Mouse position relative to rotated box for debuging
##        if len(self.layout.getStamps()) > 0:
##            p = self.localPoint(Point(pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1]))
##            p.x -= self.layout.getBaseStamp().pos.x
##            p.y -= self.layout.getBaseStamp().pos.y
##            p = Point.rotate(p, -self.layout.getBaseStamp().angle)
##            p.x += self.layout.getBaseStamp().pos.x
##            p.y += self.layout.getBaseStamp().pos.y
##            pygame.draw.circle(self.surface, pygame.Color('white'), (int(p.x+offset_x), int(p.y+offset_y)), 2)
##            self.setDirty()
        
    def handleLeftMouseDown(self, global_point):
        if not self.rect.collidepoint(global_point.x, global_point.y): return
        point = self.localPoint(global_point)
        print "layout display left down ", point.x, point.y
        if not self.selected_stamp:
            if self.snap_to_grid:
                point = self.snapToGrid(point)
            self.layout.newStamp(point)
            self.selected_stamp = self.layout.getStamp(point)
        self.layout.grabStamp(self.selected_stamp)
        self.setDirty()

    def handleRightMouseDown(self, global_point):
        if not self.rect.collidepoint(global_point.x, global_point.y): return
        point = self.localPoint(global_point)
        print "layout display right down ", point.x, point.y
        if len(self.layout.stamps) > 0:
            self.layout.removeStamp(self.selected_stamp)
            self.selected_stamp = None
            self.setDirty()

    def handleLeftMouseUp(self, global_point):
        if not self.rect.collidepoint(global_point.x, global_point.y): return
        point = self.localPoint(global_point)
        print "layout display left up ", point.x, point.y
        self.layout.releaseStamp()

    def handleRightMouseUp(self, global_point):
        if not self.rect.collidepoint(global_point.x, global_point.y): return
        point = self.localPoint(global_point)
        print "layout display right up ", point.x, point.y

    def handleMouseMove(self, global_point, rel):
        if not self.rect.collidepoint(global_point.x, global_point.y): return
        point = self.localPoint(global_point)
        print "layout display mouse move ", point.x, point.y, ":", rel.x, rel.y
        prev = self.selected_stamp
        self.selected_stamp = self.layout.getStamp(point, prev)

        if self.snap_to_grid:
            point = self.snapToGrid(point)

        ratio = None
        if self.keep_current_ratio and self.selected_stamp:
            ratio = self.selected_stamp.scale[1] / self.selected_stamp.scale[0]
        elif self.keep_original_ratio:
            ratio = 1
        print ratio

        if (self.layout.updateStamp(
                point, rel, self.snap_to_grid, ratio) or
                self.selected_stamp != prev):
            self.setDirty()
Example #49
0
class VizContainer(object):
    REDIS_CONF_DEF_KEY = 'prmd:active_viz_config_def'
    REDIS_CONF_CHANGED_KEY = 'prmd:config_changed'
    REDIS_CONF_VALUE_KEY = 'prmd:config_value'
    REDIS_VIZ_LIST = 'prmd:viz_list'
    REDIS_ACTIVE_VIZ = 'prmd:active_viz'

    active_viz = None
    use_redis = True

    FADECANDY_SERVER = 'localhost:7890'

    LEFT = FlatViz.LEFT_BEACON
    RIGHT = FlatViz.RIGHT_BEACON

    global_config = {
        'left_on': True,
        'left_color': (147 / 255.0, 0 / 255.0, 255 / 255.0),
        'left_lum': 30,
        'left_rows': [1, 1, 1, 1, 1, 1, 1, 1, 1],
        'left_sides': [1, 1, 1, 1],
        'left_spectrum': [1] * 20,

        'right_on': True,
        'right_color': (147 / 255.0, 0 / 255.0, 255 / 255.0),
        'right_lum': 30,
        'right_rows': [1, 1, 1, 1, 1, 1, 1, 1, 1],
        'right_sides': [1, 1, 1, 1],
        'right_spectrum': [1] * 20,
    }

    def __init__(self, audio_input):
        self.layout = Layout()
        self.audio_input = audio_input
        if self.use_redis:
            self.redis = redis.StrictRedis()
        self.fc_client = opc.Client(self.FADECANDY_SERVER)

        # create a list of all visualizations, add new ones here
        self.create_viz_list()

        # event loop: read config, run current viz and save layout
        self.audio_input.register_read_listener(
            self.config_reader
        )
        self.audio_input.register_read_listener(
            self.current_viz
        )
        self.audio_input.register_read_listener(
            self.layout_handler
        )
        self.audio_input.register_read_listener(
            self.print_stats
        )

        # use first visualization as the initial one
        self.activate_viz(0)

    def create_viz_list(self):
        self.visualizations = [
            CustomViz(self),
            FlatViz(self)
        ]
        if self.use_redis:
            self.redis.delete(self.REDIS_VIZ_LIST)
            self.redis.rpush(
                self.REDIS_VIZ_LIST, *[v.name for v in self.visualizations]
            )

    def get_conf(self, name):
        return self.global_config.get(name, None)

    def config_reader(self, data, time_diff=None):
        if not self.use_redis:
            return
        changed = self.redis.getset(self.REDIS_CONF_CHANGED_KEY, "0")
        if changed == "1":
            config = json.loads(self.redis.get(self.REDIS_CONF_VALUE_KEY))
            for key in config['global']:
                if '_rows' in key or '_sides' in key:
                    for update in config['global'][key]:
                        config['global'][key] = self.global_config[key]
                        config['global'][key][update[0]] = update[1]
            self.global_config.update(config['global'])
            self.visualizations[self.active_viz].update_config(config['viz'])

    def layout_handler(self, data, time_diff=None):
        self._apply_global_config()
        self.fc_client.put_pixels(self.layout.get_output())

    def activate_viz(self, viz_index):
        self.visualizations[viz_index].active = True
        self.active_viz = viz_index

        if self.use_redis:
            config = json.dumps(self.visualizations[viz_index].config_def)
            self.redis.set(self.REDIS_CONF_DEF_KEY, config)
            self.redis.set(
                self.REDIS_ACTIVE_VIZ, self.visualizations[viz_index].name
            )

    def current_viz(self, data, time_diff=None):
        if self.active_viz is not None:
            self.visualizations[self.active_viz].visualize(
                data, time_diff=time_diff)

    def start(self):
        self.audio_input.read_loop()

    def print_stats(self, data, time_diff):
        fps = int(1 / time_diff)
        if fps < 24:
            print("############ Low FPS: %s" % fps)

    def _apply_global_config(self):
        if not self.global_config['left_on']:
            self.layout.set_beacon(self.LEFT, self.layout._off)
        if not self.global_config['right_on']:
            self.layout.set_beacon(self.RIGHT, self.layout._off)

        for i, row in enumerate(self.global_config['left_rows']):
            if not row:
                self.layout.set_row(i, self.layout._off, beacon=self.LEFT)
        for i, row in enumerate(self.global_config['right_rows']):
            if not row:
                self.layout.set_row(i, self.layout._off, beacon=self.RIGHT)

        for i, side in enumerate(self.global_config['left_sides']):
            if not side:
                self.layout.set_side(i, self.layout._off, beacon=self.LEFT)
        for i, side in enumerate(self.global_config['right_sides']):
            if not side:
                self.layout.set_side(i, self.layout._off, beacon=self.RIGHT)
Example #50
0
def main(args):
    # Initialize debuglink transport
    if args.debuglink:
        print "Starting debug connection on '%s'" % args.debuglink_path
        print "Debug connection is for unit tests only. NEVER use debug connection with real wallet!"
        debug_transport = get_transport(args.debuglink_transport, args.debuglink_path)
    else:
        debug_transport = get_transport('fake', None)

    # Initialize main transport
    transport = get_transport(args.transport, args.path)

    # Load persisted data. Create new wallet if file doesn't exist
    print "Loading wallet..."
    wallet = Wallet(args.wallet)
    print wallet.struct

    # Initialize hardware (screen, buttons)
    but = Buttons(hw=args.shield, stdin=not args.shield, pygame=not args.shield)
    buff = DisplayBuffer(DISPLAY_WIDTH, DISPLAY_HEIGHT)
    display = Display(buff, spi=args.shield, virtual=not args.shield)
    display.init()

    # Initialize layout driver
    layout = Layout(buff)

    # Startup state machine and switch it to default state
    machine = StateMachine(wallet, layout)

    #tx1 = proto.TxOutput(address='1BRMLAB7nryYgFGrG8x9SYaokb8r2ZwAsX', amount=112000000)
    #tx2 = proto.TxOutput(address='1MarekMKDKRb6PEeHeVuiCGayk9avyBGBB', amount=12340123400)
    #layout.show_transactions([tx1, tx2 ], False)

    display.refresh()

    # Main cycle
    while True:
	#d=datetime.now()
	#layout.show_message([d.strftime("%d %B %Y %H:%M:%S")],question=False)
        # Set True if device does something
        # False = device will sleep for a moment
        is_active = False

        try:
            # Read button states
            button = but.read()
        except KeyboardInterrupt:
            # User requested to close the app
            break

        # Handle debug link connection
        msg = debug_transport.read()
        if msg is not None:
            print "Received debuglink", msg.__class__.__name__, msg
            if isinstance(msg, proto.DebugLinkDecision):
                # Press the button
                button = msg.yes_no
            else:
                resp = machine.process_message(msg)
                if resp is not None:
                    print "Sending debuglink", resp.__class__.__name__, resp
                    debug_transport.write(resp)
                    is_active = True

            '''
            elif isinstance(msg, proto.DebugLinkGetState):
                # Report device state
                resp = machine.get_state(msg)
                print "Sending debuglink", resp.__class__.__name__, resp
                debug_transport.write(resp)
            else:
                raise Exception("Got unexpected object %s" % msg.__class__.__name__)
            '''

        if button is not None:
            print "Button", button
            is_active = True

            resp = machine.press_button(button)
            if resp is not None:
                print "Sending", resp
                transport.write(resp)

        '''
        if button == True:
            layout.show_transactions([tx1, tx2 ], False)
            layout.show_question_dummy()

        if button == False:
            layout.show_logo(logo)
        '''

        # Handle main connection
        msg = transport.read()
        if msg is not None:
            print "Received", msg.__class__.__name__, msg
            resp = machine.process_message(msg)
            if resp is not None:
                print "Sending", resp.__class__.__name__, resp
                transport.write(resp)
                is_active = True

        # Display scrolling
        is_active |= layout.update()

        if layout.need_refresh:
            # Update display
            display.refresh()

        if not is_active:
            # Nothing to do, sleep for a moment
            time.sleep(0.1)

    # Save wallet file
    wallet.save()

    # Close transports
    transport.close()
    debug_transport.close()
Example #51
0
 def remove_one(self, client):
     Layout.remove(self, client)
Example #52
0
from layout import Layout

l = Layout()
mn = l.metric
i = 0
while True:
    i += 1
    l.shuffle()
    if not i % 1000:
        print '\r%s' % i,
    if l.metric < mn:
        mn = l.metric
        print 'New min: %s\n%s' % (mn, l)

Example #53
0
    def __init__(self, workspace):
        Layout.__init__(self, workspace)

        self._resizing = None
        self._moving = None
Example #54
0
class Gui(Holder):
    """ 
        core of the treegui system 
        handles most of the events 
        prods other ui system such as
        layout and drawing into doing
        stuff
    """

    def __init__(self,keys=None,theme=None):
        """ initilizes the gui """
        
        import __builtin__
        __builtin__.gui = self
       
        self.node = aspect2d
        
        self.id = "root"
                
        self.dragWidget = None
        self.dragPos = Vec2(0,0)
        self.dragFun = None
        self.dragSnap = False
        self.lastDragMoue = Vec2(0,0)           
        self.hoveringOver = None
        
        self.parent = False
        self.children = []
        self.idToFrame = {}
        
        self.pos = Vec2(0,0)
        self.windowsize = 800,600
        self.size = Vec2(*self.windowsize)
        
        self.mouse = Vec2(0,0) 
        self.node.setBin("fixed",2)
        self.node.setDepthWrite(False)
        self.node.setDepthTest(False)

        if not keys:
            self.keys = Keys()
        else:
            self.keys = keys
            
        if not theme:
            self.theme = Theme()
        else:
            self.theme = theme
        self.layout = Layout()
        self.drawer = Drawer()
        
        task(self._doMouse,-10)
        
        self._reSize()
        
        task(self._doDrag,10)        
        task(self._reSize,20)        
        task(self._layout,30)
        task(self._draw,40)
    
    def byId(self,name):
        if name in self.idToFrame:
            return self.idToFrame[name]
      
    def _layout(self):
        """ prods layout to do its thing """
        # compute children's real positions
        self.layout.do()
        
    def _draw(self):
        """ prods drawer to do its thing """
        self.drawer.draw(self.children)
    
    def _reSize(self):
        """ resize the window via panda3d internal events"""
        self.windowsize = base.win.getXSize(),base.win.getYSize()
        self.size = Vec2(*self.windowsize)
        self.aspect  = float(self.windowsize[0]) / float(self.windowsize[1])         
        self.node.setScale(2./base.win.getXSize(), 1, -2./base.win.getYSize())
        self.node.setPos(-1, 0, 1)
        self.node.reparentTo(render2d)    
        self._x = 0
        self._y = 0
        self._width = self.size[0]
        self._height = self.size[1]
        
    
    def baseMouseEvent(self,key):
        """ acts like user clicked mouse with key """
        md = base.win.getPointer( 0 )
        self.mouseX = md.getX()
        self.mouseY = md.getY()
        m = self.mouseEvent(key,self.mouseX,self.mouseY)        
        return m
          
    def _doMouse(self):
        """ treegui's low level mouse interface """ 
        used = self.baseMouseEvent("hover")
        if not used:
            if gui.hoveringOver and gui.hoveringOver.onOut:
                gui.hoveringOver.onOut()
            gui.hoveringOver = None
        
        
    def drag(self,widget,dragSnap=False):
        """ drags a widget """ 
        if not self.dragWidget :
            self.dragWidget = widget
            self.dragSnap = dragSnap
            self.dragPosX = widget._x-gui.mouseX
            self.dragPosY = widget._y-gui.mouseY
            widget.parent.toFront(widget)
    
    def _doDrag(self):
        """ task that does dragging at low level """
        if self.dragWidget:
            self.dragWidget.x = self.dragPosX+gui.mouseX           
            self.dragWidget.y = self.dragPosY+gui.mouseY

            if self.dragWidget.onDrag:
                self.dragWidget.onDrag()

            if self.dragSnap:
                def close(a,b):
                    return abs(a-b) < 15
        
                if close(self.dragWidget.x,0): 
                    self.dragWidget.x = "left"
                     
                elif close(
                    self.dragWidget.x + self.dragWidget._width,
                    self.dragWidget.parent._width): 
                        self.dragWidget.x = "right"
        
                if close(self.dragWidget.y,0): 
                    self.dragWidget.y = "top"
                    
                elif close(
                    self.dragWidget.y + self.dragWidget._height,
                    self.dragWidget.parent._height): 
                        self.dragWidget.y = "bottom"
                
    def focusOn(self,focus):
        if self.keys.focus:
            self.keys.focus.onUnFocus()
        focus.onFocus()
        self.keys.focus = focus
        return focus
    
    def focusNext(self,focus):

        i = focus.parent.children.index(focus)
        i -= 1   
        if i == -1 : i = len(focus.parent.children) - 1
        newFocus = focus.parent.children[i]
        
        while not newFocus.control and newFocus != focus:
            i = newFocus.parent.children.index(newFocus)
            i -= 1   
            if i == -1 : i = len(focus.parent.children) - 1
            newFocus = focus.parent.children[i]
            print "new",newFocus
    
        return self.focusOn(newFocus)        
                
    def toggle(self):
        if self.node.isHidden():
            self.node.show()
        else:
            self.node.hide()      
Example #55
0
class Component2(object):
    """ Base class for Wing, Body, and Junction components. """

    def __init__(self):
        self.Ps = []
        self.Ks = []
        self.oml0 = []

    def createSurfaces(self, Ks, nu, nv, du, dv, d):
        Ps = []
        for j in range(len(nv)):
            for i in range(len(nu)):
                u1 = (sum(nu[:i]) - i) / (sum(nu) - len(nu))
                u2 = (sum(nu[: i + 1]) - i - 1) / (sum(nu) - len(nu))
                v1 = (sum(nv[:j]) - j) / (sum(nv) - len(nv))
                v2 = (sum(nv[: j + 1]) - j - 1) / (sum(nv) - len(nv))
                P = PAMlib.createsurfaces(nu[i], nv[j], du, dv, d, u1, u2, v1, v2)
                Ps.append(P)

        K = numpy.zeros((len(nu), len(nv)), int)
        counter = 0
        if len(Ks) > 0:
            counter = numpy.max(Ks[-1]) + 1
        for j in range(len(nv)):
            for i in range(len(nu)):
                K[i, j] = counter
                counter += 1
        return Ps, K

    def createInterface(self, n, edge1, edge2, swap=False):
        P = PAMlib.createinterface(n, edge1.shape[0], edge1, edge2)
        if swap:
            P = numpy.swapaxes(P, 0, 1)
        return P

    def translatePoints(self, dx, dy, dz):
        for k in range(len(self.Ps)):
            self.Ps[k][:, :, 0] += dx
            self.Ps[k][:, :, 1] += dy
            self.Ps[k][:, :, 2] += dz

    def updateQs(self):
        Qs = self.Qs
        Ns = self.Ns
        oml0 = self.oml0

        for f in range(len(Ns)):
            PAMlib.updateqs(oml0.nQ, Ns[f].shape[0], Ns[f].shape[1], Ns[f], Qs[f], oml0.Q)

    def initializeDOFs(self):
        oml0 = self.oml0
        Ks = self.Ks

        Qs = []
        Ns = []

        for f in range(len(Ks)):
            ni = self.getni(f, 0)
            nj = self.getni(f, 1)
            Qs.append(numpy.zeros((sum(ni) + 1, sum(nj) + 1, 3), complex))
            Ns.append(numpy.zeros((sum(ni) + 1, sum(nj) + 1, 5), int))
            Ns[f][:, :, :] = -1
            for j in range(Ks[f].shape[1]):
                for i in range(Ks[f].shape[0]):
                    surf = Ks[f][i, j]
                    if surf != -1:
                        for v in range(nj[j] + 1):
                            jj = sum(nj[:j]) + v
                            for u in range(ni[i] + 1):
                                ii = sum(ni[:i]) + u
                                uType = self.classifyC(u, ii, ni[i] + 1, Ns[f].shape[0])
                                vType = self.classifyC(v, jj, nj[j] + 1, Ns[f].shape[1])
                                isInteriorDOF = uType == 2 and vType == 2
                                if isInteriorDOF or self.isExteriorDOF(f, uType, vType, i, j):
                                    Ns[f][ii, jj, 0] = oml0.getIndex(surf, u, v, 2)
                                    Ns[f][ii, jj, 1] = i
                                    Ns[f][ii, jj, 2] = u
                                    Ns[f][ii, jj, 3] = j
                                    Ns[f][ii, jj, 4] = v
        self.Qs = Qs
        self.Ns = Ns

    def classifyC(self, u, i, lenu, leni):
        if i == 0:
            return 0
        elif i == leni - 1:
            return -1
        elif u == 0:
            return 1
        elif u == lenu - 1:
            return 1
        else:
            return 2

    def computeDims(self, aircraft):
        ndims = int(numpy.max(abs(self.faces)))
        oml0 = self.oml0
        Ks = self.Ks
        dims = []
        for d in range(ndims):
            dims.append([])
        for f in range(self.faces.shape[0]):
            for k in range(2):
                d = abs(self.faces[f, k]) - 1
                dims[d] = numpy.zeros(Ks[f].shape[k], int)
        for f in range(self.faces.shape[0]):
            for i in range(Ks[f].shape[0]):
                for j in range(Ks[f].shape[1]):
                    surf = Ks[f][i, j]
                    if not surf == -1:
                        for k in range(2):
                            edge = oml0.surf_edge[surf, k, 0]
                            group = oml0.edge_group[abs(edge) - 1] - 1
                            m = oml0.group_m[group] - 1
                            d = abs(self.faces[f, k]) - 1
                            if k == 0:
                                index = i
                            else:
                                index = j
                            if self.faces[f, k] > 0:
                                dims[d][index] = int(m)
                            else:
                                dims[d][-index - 1] = int(m)
        self.dims = dims

    def getni(self, f, a):
        d = abs(self.faces[f, a]) - 1
        if self.faces[f, a] > 0:
            return self.dims[d]
        else:
            return self.dims[d][::-1]

    def setC1(self, t, f, i=None, j=None, u=None, v=None, d=None, val=True):
        """ Set C1 continuity 
        t: {string} surface or edge C1
        f: face index
        i,j: surface index
            both given: only consider [i,j] surface
            one given: loop through and apply to all of the other index
            none given: apply to all surfaces
        u,v: edge/vert index (for surfC1)
            both given: only consider [u,v] corner/side
            one given: loop through and apply to all of the other index
            none given: apply to all corners/sides
        u,v,d: side index (for edgeC1)
        """

        if t == "surf":
            func = self.setSurfC1
        elif t == "edge":
            func = self.setEdgeC1
        if (not i == None) and (not j == None):
            func(f, i, j, u, v, d, val)
        elif not i == None:
            for j in range(self.Ks[f].shape[1]):
                func(f, i, j, u, v, d, val)
        elif not j == None:
            for i in range(self.Ks[f].shape[0]):
                func(f, i, j, u, v, d, val)
        else:
            for j in range(self.Ks[f].shape[1]):
                for i in range(self.Ks[f].shape[0]):
                    func(f, i, j, u, v, d, val)

    def setSurfC1(self, f, i, j, u, v, d, val):
        oml0 = self.oml0
        surf = self.Ks[f][i, j]
        if not surf == -1:
            if u == None and v == None:
                oml0.surf_c1[surf, :, :] = val
            elif u == None:
                oml0.surf_c1[surf, :, v] = val
            elif v == None:
                oml0.surf_c1[surf, u, :] = val
            else:
                oml0.surf_c1[surf, u, v] = val

    def setEdgeC1(self, f, i, j, u, v, d, val):
        oml0 = self.oml0
        surf = self.Ks[f][i, j]
        if not surf == -1:
            if u == None:
                edge = oml0.surf_edge[surf, 0, v]
            else:
                edge = oml0.surf_edge[surf, 1, u]
            if d == None:
                oml0.edge_c1[abs(edge) - 1, :] = val
            elif edge > 0:
                oml0.edge_c1[abs(edge) - 1, d] = val
            else:
                oml0.edge_c1[abs(edge) - 1, 1 - abs(d)] = val

    def setCornerC1(self, f, i=0, j=0, val=True):
        self.setC1("edge", f, i=i, j=j, u=i, d=j, val=val)
        self.setC1("edge", f, i=i, j=j, v=j, d=i, val=val)

    def check(self, uType, vType, u=None, v=None):
        if u == None:
            uVal = uType == 2
        else:
            uVal = uType == u
        if v == None:
            vVal = vType == 2
        else:
            vVal = vType == v
        return uVal and vVal

    def computeMs(self):
        oml0 = self.oml0
        Ks = self.Ks

        Ms = []
        for f in range(len(Ks)):
            ni = self.getni(f, 0)
            nj = self.getni(f, 1)
            Ms.append(numpy.zeros((sum(ni) + 1, sum(nj) + 1), int))
            Ms[f][:, :] = -1
            for j in range(Ks[f].shape[1]):
                for i in range(Ks[f].shape[0]):
                    surf = Ks[f][i, j]
                    if surf != -1:
                        for v in range(nj[j] + 1):
                            jj = sum(nj[:j]) + v
                            for u in range(ni[i] + 1):
                                ii = sum(ni[:i]) + u
                                Ms[f][ii, jj] = oml0.getIndex(surf, u, v, 1)
        self.Ms = Ms

    def findJunctions(self):
        oml0 = self.oml0
        Ks = self.Ks

        Js = []
        for f in range(len(Ks)):
            ni = self.getni(f, 0)
            nj = self.getni(f, 1)
            k0 = Ks[f].shape[0]
            k1 = Ks[f].shape[1]
            SPs = []
            EPs = []
            for j in range(k1):
                for i in range(k0):
                    if Ks[f][i, j] == -1:
                        SPs.append([i, j])
                        EPs.append([i, j])
                        if (i > 0 and Ks[f][i - 1, j] == -1) or (j > 0 and Ks[f][i, j - 1] == -1):
                            SPs.pop()
                        if (i < k0 - 1 and Ks[f][i + 1, j] == -1) or (j < k1 - 1 and Ks[f][i, j + 1] == -1):
                            EPs.pop()
            J = numpy.zeros((len(SPs), 4), int)
            for s in range(len(SPs)):
                SP = SPs[s]
                for e in range(len(EPs)):
                    EP = EPs[e]
                    if SP[0] <= EP[0] and SP[1] <= EP[1]:
                        if numpy.linalg.norm(1 + Ks[f][SP[0] : EP[0] + 1, SP[1] : EP[1] + 1]) < 1e-14:
                            J[s, :] = [sum(ni[: SP[0]]), sum(nj[: SP[1]]), sum(ni[: EP[0] + 1]), sum(nj[: EP[1] + 1])]
            Js.append(J)
        self.Js = Js

    def flattenGeometry(self):
        oml0 = self.oml0
        Ms = self.Ms
        for f in range(len(Ms)):
            ni = Ms[f].shape[0]
            nj = Ms[f].shape[1]
            for i in range(ni):
                for j in range(nj):
                    oml0.C[Ms[f][i, j], :] = self.getFlattenedC(f, i, j, ni, nj)
        oml0.computePointsC()

    def initializeLayout(self):
        def getv(r, v1, v2):
            return numpy.array(v1) * (1 - r) + numpy.array(v2) * r

        oml0 = self.oml0
        Ms = self.Ms
        Js = self.Js

        edges = []
        edges.append([0, 0, 0, 1])
        edges.append([0, 0, 1, 0])
        edges.append([0, 1, 1, 1])
        edges.append([1, 0, 1, 1])

        skinIndices = self.getSkinIndices()
        for s in range(len(skinIndices)):
            for f in skinIndices[s]:
                for k in range(Js[f].shape[0]):
                    C11 = oml0.C[Ms[f][Js[f][k, 0], Js[f][k, 1]], :2]
                    C12 = oml0.C[Ms[f][Js[f][k, 0], Js[f][k, 3]], :2]
                    C21 = oml0.C[Ms[f][Js[f][k, 2], Js[f][k, 1]], :2]
                    C22 = oml0.C[Ms[f][Js[f][k, 2], Js[f][k, 3]], :2]
                    edges.append([C11[0], C11[1], C12[0], C12[1]])
                    edges.append([C11[0], C11[1], C21[0], C21[1]])
                    edges.append([C12[0], C12[1], C22[0], C22[1]])
                    edges.append([C21[0], C21[1], C22[0], C22[1]])
        for m in self.keys:
            member = self.members[m]
            for i in range(member.nmem):
                if member.nmem == 1:
                    ii = 0
                else:
                    ii = i / (member.nmem - 1)
                A = getv(ii, member.A1, member.A2)
                B = getv(ii, member.B1, member.B2)
                C = getv(ii, member.C1, member.C2)
                D = getv(ii, member.D1, member.D2)
                for j in range(member.ndiv):
                    if (B[2] == 0 and C[2] == 0) or (B[2] == 1 and C[2] == 1):
                        V0 = getv(j / member.ndiv, B, C)
                        V1 = getv((j + 1) / member.ndiv, B, C)
                        edges.append([V0[0], V0[1], V1[0], V1[1]])
                    if (A[2] == 0 and D[2] == 0) or (A[2] == 1 and D[2] == 1):
                        V0 = getv(j / member.ndiv, A, D)
                        V1 = getv((j + 1) / member.ndiv, A, D)
                        edges.append([V0[0], V0[1], V1[0], V1[1]])
        self.layout = Layout(6, self.getAR(), 1, numpy.array(edges))

    def findJunctionQuadsAndEdges(self):
        oml0 = self.oml0
        Ms = self.Ms
        Js = self.Js

        C = numpy.zeros((4, 2))
        ctd = numpy.zeros(2)

        nquad = self.layout.nquad
        nedge = self.layout.nedge
        edges = self.layout.edges
        verts = self.layout.verts
        poly_vert = self.layout.poly_vert

        skinIndices = self.getSkinIndices()

        JQs = []
        JEs = []
        quad_indices = []
        for s in range(len(skinIndices)):
            JQ = []
            for f in skinIndices[s]:
                for q in range(nquad):
                    ctd[:] = 0
                    for k in range(4):
                        ctd[:] += 0.25 * verts[poly_vert[q, k] - 1, :]
                    for k in range(Js[f].shape[0]):
                        C[0, :] = oml0.C[Ms[f][Js[f][k, 0], Js[f][k, 1]], :2]
                        C[1, :] = oml0.C[Ms[f][Js[f][k, 0], Js[f][k, 3]], :2]
                        C[2, :] = oml0.C[Ms[f][Js[f][k, 2], Js[f][k, 1]], :2]
                        C[3, :] = oml0.C[Ms[f][Js[f][k, 2], Js[f][k, 3]], :2]
                        if (
                            min(C[:, 0]) < ctd[0]
                            and ctd[0] < max(C[:, 0])
                            and min(C[:, 1]) < ctd[1]
                            and ctd[1] < max(C[:, 1])
                        ):
                            JQ.append(q + 1)
            if JQ == []:
                JQ.append(-1)
            JQs.append(JQ)

            JE = []
            for f in skinIndices[s]:
                for e in range(nedge):
                    ctd[:] = 0
                    for k in range(2):
                        ctd[:] += 0.5 * verts[edges[e, k] - 1, :]
                    for k in range(Js[f].shape[0]):
                        C[0, :] = oml0.C[Ms[f][Js[f][k, 0], Js[f][k, 1]], :2]
                        C[1, :] = oml0.C[Ms[f][Js[f][k, 0], Js[f][k, 3]], :2]
                        C[2, :] = oml0.C[Ms[f][Js[f][k, 2], Js[f][k, 1]], :2]
                        C[3, :] = oml0.C[Ms[f][Js[f][k, 2], Js[f][k, 3]], :2]
                        if (
                            min(C[:, 0]) < ctd[0]
                            and ctd[0] < max(C[:, 0])
                            and min(C[:, 1]) < ctd[1]
                            and ctd[1] < max(C[:, 1])
                        ):
                            JEs.append(e + 1)
            JEs.append(JE)

            quad_indices.append(self.layout.getQuadIndices(JQ))

        if len(quad_indices) == 1:
            quad_indices.append(quad_indices[0])

        self.JQs = JQs
        self.JEs = JEs
        self.quad_indices = numpy.array(quad_indices, order="F").T

    def projectSkins(self):
        oml0 = self.oml0
        Ms = self.Ms
        Js = self.Js
        skinIndices = self.getSkinIndices()

        C = numpy.zeros((4, 2), order="F")
        Bs = []
        Ss = []
        quad_indices = []
        for s in range(len(skinIndices)):
            Ps = []
            P, S = self.layout.extractFlattened(self.JQs[s], max(self.quad_indices[:, s]))
            Ps.append(P)
            Ss.append(S)
            for f in skinIndices[s]:
                for k in range(Js[f].shape[0]):
                    C[0, :] = oml0.C[Ms[f][Js[f][k, 0], Js[f][k, 1]], :2]
                    C[1, :] = oml0.C[Ms[f][Js[f][k, 0], Js[f][k, 3]], :2]
                    C[2, :] = oml0.C[Ms[f][Js[f][k, 2], Js[f][k, 1]], :2]
                    C[3, :] = oml0.C[Ms[f][Js[f][k, 2], Js[f][k, 3]], :2]
                    P = self.layout.extractEdges(self.JQs[s], min(C[:, 0]), max(C[:, 0]), min(C[:, 1]), max(C[:, 1]))
                    Ps.append(P)
            P = numpy.vstack(Ps)

            surfindices = []
            for f in skinIndices[s]:
                surfindices.append(self.Ks[f].flatten())
            surfs = numpy.unique(numpy.hstack(surfindices))
            if surfs[0] == -1:
                surfs = numpy.delete(surfs, 0)
            Q = numpy.zeros((P.shape[0], 3))
            Q[:, 2] = 1.0
            ss, u, v = oml0.computeProjection(P, surfs=surfs, Q=Q)
            Bs.append(oml0.computeBases(ss, u, v))

        B = oml0.vstackSparse(Bs)

        BM = B.dot(oml0.M)
        P = BM.dot(oml0.Q)

        As, S = self.computeStructure(P)
        Ss.append(S)
        A = oml0.vstackSparse(As)

        ABM = A.dot(BM)
        S = numpy.vstack(Ss)

        self.strABM = ABM
        self.strS = S

    def computeStructure(self, P):
        oml0 = self.oml0
        Ms = self.Ms
        Js = self.Js
        layout = self.layout
        skinIndices = self.getSkinIndices()

        C = numpy.zeros((4, 2), order="F")
        As = []
        Jns = []
        Jus = []
        col = 0
        for s in range(len(skinIndices)):
            n = max(self.quad_indices[:, s]) * self.layout.n ** 2
            Aa = numpy.ones(n)
            Ai = numpy.linspace(0, n - 1, n)
            Aj = numpy.linspace(0, n - 1, n) + col
            As.append(scipy.sparse.csr_matrix((Aa, (Ai, Aj)), shape=(n, P.shape[0])))
            Jn = []
            Ju = []
            col += n
            for f in skinIndices[s]:
                for k in range(Js[f].shape[0]):
                    C[0, :] = oml0.C[Ms[f][Js[f][k, 0], Js[f][k, 1]], :2]
                    C[1, :] = oml0.C[Ms[f][Js[f][k, 0], Js[f][k, 3]], :2]
                    C[2, :] = oml0.C[Ms[f][Js[f][k, 2], Js[f][k, 1]], :2]
                    C[3, :] = oml0.C[Ms[f][Js[f][k, 2], Js[f][k, 3]], :2]
                    nu1, nu2, nv1, nv2 = layout.countJunctionEdges(
                        self.JQs[s], min(C[:, 0]), max(C[:, 0]), min(C[:, 1]), max(C[:, 1])
                    )
                    Jn.append([nu1, nu2, nv1, nv2])
                    Ju.append([min(C[:, 0]), max(C[:, 0]), min(C[:, 1]), max(C[:, 1])])
                    nP = layout.n * (nu1 + nu2 + nv1 + nv2)
                    col += nP
            if Jn == []:
                Jn.append([-1, -1, -1, -1])
                Ju.append([-1, -1, -1, -1])
            Jns.append(numpy.array(Jn, int, order="F"))
            Jus.append(numpy.array(Ju, order="F"))

        nM = len(self.keys)
        members = numpy.zeros((nM, 34), order="F")
        for i in range(nM):
            member = self.members[self.keys[i]]
            members[i, :4] = [member.domain, member.shape, member.nmem, member.ndiv]
            members[i, 4:16] = member.A1 + member.B1 + member.C1 + member.D1
            members[i, 16:28] = member.A2 + member.B2 + member.C2 + member.D2
            members[i, 28:] = [member.tx, member.ty, member.rx, member.ry, member.n1, member.n2]

        nP, nS = PAMlib.countinternalnodes(self.layout.n, nM, members)
        P2, M, S = PAMlib.computeinternalnodes(nP, nS, self.layout.n, nM, members)
        nA = PAMlib.countannz(nP, layout.nvert, layout.nquad, layout.verts, layout.poly_vert, self.quad_indices, P2, M)
        if len(skinIndices) == 1:
            Aa, Ai, Aj = PAMlib.assembleamtx(
                nA,
                self.layout.n,
                nP,
                Jns[0].shape[0],
                Jns[0].shape[0],
                self.layout.nvert,
                self.layout.nquad,
                Jns[0],
                Jns[0],
                Jus[0],
                Jus[0],
                self.quad_indices,
                self.layout.verts,
                self.layout.poly_vert,
                P2,
                M,
            )
        else:
            Aa, Ai, Aj = PAMlib.assembleamtx(
                nA,
                self.layout.n,
                nP,
                Jns[0].shape[0],
                Jns[1].shape[0],
                self.layout.nvert,
                self.layout.nquad,
                Jns[0],
                Jns[1],
                Jus[0],
                Jus[1],
                self.quad_indices,
                self.layout.verts,
                self.layout.poly_vert,
                P2,
                M,
            )
        As.append(scipy.sparse.csr_matrix((Aa, (Ai, Aj)), shape=(max(Ai) + 1, P.shape[0])))

        return As, S

    def buildStructure(self):
        self.computeMs()
        self.findJunctions()
        self.flattenGeometry()
        self.initializeLayout()
        self.findJunctionQuadsAndEdges()
        self.projectSkins()

    def addMembers(
        self,
        name,
        domain,
        shape,
        nmem,
        ndiv,
        A1=None,
        B1=None,
        C1=None,
        D1=None,
        A2=None,
        B2=None,
        C2=None,
        D2=None,
        tx=0.5,
        ty=0.5,
        rx=1.0,
        ry=1.0,
        n1=5,
        n2=5,
    ):

        if A2 == None:
            A2 = [-1, -1, -1]
            B2 = [-1, -1, -1]
            C2 = [-1, -1, -1]
            D2 = [-1, -1, -1]
        if B1 == None:
            B1 = [-1, -1, -1]
            B1[:2] = A1[:2]
            B1[2] = C1[2]
        if D1 == None:
            D1 = [-1, -1, -1]
            D1[:2] = C1[:2]
            D1[2] = A1[2]
        if B2 == None:
            B2 = [-1, -1, -1]
            B2[:2] = A2[:2]
            B2[2] = C2[2]
        if D2 == None:
            D2 = [-1, -1, -1]
            D2[:2] = C2[:2]
            D2[2] = A2[2]
        self.members[name] = Member(domain, shape, nmem, ndiv, A1, B1, C1, D1, A2, B2, C2, D2, tx, ty, rx, ry, n1, n2)
        self.keys.append(name)
Example #56
0
class Example(QWidget):
    def __init__(self):
        super().__init__()

        self.initUI()

        self.keyboard_state = {'North' : False, 'South' : False, 'West' : False, 'East' : False, 'Stop' : False}

        self.agents = [HumanAgent(0), StopAgent(1)]
        self.layout = Layout()
        self.layout.load_from_file("test.lay")
        self.colors = {Tile.Empty: QBrush(QColor(26,26,26)),
                       Tile.Wall: QBrush(QColor(12,12,225)),
                       Tile.Start: QBrush(QColor(255,255,0))}

        self.game = PacmanGame(self.layout)
        self.current_game_state = self.game.get_initial_game_state()

        self.timer = QBasicTimer()

        self.timer.start(500, self)

    def timerEvent(self, event):

        for i in range(2):
            agent = self.agents[i]
            move = agent.make_decision(self.current_game_state, self.game, self.keyboard_state)
            assert move in self.game.get_legal_moves(self.current_game_state)
            self.current_game_state = self.game.apply_move(self.current_game_state, move, i)


        #move = self.pacman_agent.make_decision(self.current_game_state, self.game, self.keyboard_state)

        # assert that returned move is valid

        #self.current_game_state = self.game.apply_move(self.current_game_state, move, 0)

        self.repaint()

    def initUI(self):
        self.setGeometry(300, 300, 280, 170)
        self.setWindowTitle('Draw text')
        self.show()

    def keyPressEvent(self, event: QKeyEvent):
        if event.key() == 0x01000013:
            self.keyboard_state['North'] = True
        elif event.key() == 0x01000015:
            self.keyboard_state['South'] = True
        elif event.key() == 0x01000012:
            self.keyboard_state['West'] = True
        elif event.key() == 0x01000014:
            self.keyboard_state['East'] = True

    def keyReleaseEvent(self, event : QKeyEvent):
        if event.key() == 0x01000013:
            self.keyboard_state['North'] = False
        elif event.key() == 0x01000015:
            self.keyboard_state['South'] = False
        elif event.key() == 0x01000012:
            self.keyboard_state['West'] = False
        elif event.key() == 0x01000014:
            self.keyboard_state['East'] = False


    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)
        qp.setPen (QPen(QColor(0,0,0,0)))
        ysize, xsize = self.layout.shape
        canvas = self.contentsRect()
        for y in range(ysize):
            for x in range(xsize):
                qp.setBrush(self.colors[self.layout.grid[y][x]])
                qp.drawRect(TILE_SIZE * x, TILE_SIZE * y, TILE_SIZE, TILE_SIZE)
                #Color(rgb=self.colors[self.layout.grid[y][x]])
                #Rectangle(pos=(TILE_SIZE * x, TILE_SIZE * y), size=(TILE_SIZE, TILE_SIZE))

        pac_x = self.current_game_state.agents[0].position[0] * TILE_SIZE
        pac_y = self.current_game_state.agents[0].position[1] * TILE_SIZE
        qp.setBrush(QBrush(QColor(255,255,0)))
        qp.drawEllipse(pac_x, pac_y, TILE_SIZE, TILE_SIZE)

        for g in self.current_game_state.agents[1:]:
            g_x = g.position[0] * TILE_SIZE
            g_y = g.position[1] * TILE_SIZE
            qp.setBrush(QBrush(QColor(255,0,0)))
            qp.drawEllipse(g_x, g_y, TILE_SIZE, TILE_SIZE)

        for y in range(ysize):
            for x in range(xsize):
                if self.current_game_state.food[y][x]:
                    qp.setBrush(QBrush(QColor(255,255,255)))
                    qp.drawEllipse(x * TILE_SIZE + TILE_SIZE / 2,
                                 y * TILE_SIZE + TILE_SIZE / 2,
                            TILE_SIZE / 4, TILE_SIZE / 4)

        qp.end()


    def drawText(self, event, qp):
        qp.setPen(QColor(168, 34, 3))
        qp.setFont(QFont('Decorative', 10))
        qp.drawText(event.rect(), Qt.AlignCenter, self.text)
Example #57
0
def main(args):
    monkeypatch_google_protobuf_text_format()

    # Initialize debuglink transport
    if args.debuglink:
        print "Starting debug connection on '%s'" % args.debuglink_path
        print "Debug connection is for unit tests only. NEVER use debug connection with real wallet!"
        debug_transport = get_transport(args.debuglink_transport, args.debuglink_path)
    else:
        debug_transport = get_transport('fake', None)

    # Initialize main transport
    transport = get_transport(args.transport, args.path)

    # Load persisted data. Create new wallet if file doesn't exist
    print "Loading wallet..."
    storage = Storage(args.wallet, bootloader_mode=args.bootloader_mode)
    # storage.struct.settings.label = 'Slushova penezenka'
    print storage.struct

    # Initialize hardware (screen, buttons)
    but = Buttons(hw=args.shield, stdin=not args.shield, pygame=not args.shield)
    buff = DisplayBuffer(DISPLAY_WIDTH, DISPLAY_HEIGHT)
    display = Display(buff, spi=args.shield, virtual=not args.shield)
    display.init()

    # Initialize layout driver
    layout = Layout(buff, display)

    # Process exponential backoff if there was unsuccesfull PIN attempts
    if storage.get_pin_delay():
        delay = storage.get_pin_delay()
        print "Waiting %s seconds until boot up" % delay
        layout.show_pin_backoff_progress(delay)

    # Startup state machine and switch it to default state
    machine = StateMachine(storage, layout)

    display.refresh()

    # Main cycle
    while True:
        try:
            # Read button states
            button = but.read()
        except KeyboardInterrupt:
            # User requested to close the app
            break

        # Set is_active=True if device does something
        # False = device will sleep for a moment to prevent CPU load
        # Set button=None to use event only for rendering
        # and hide it against state machine
        (is_active, button) = layout.update(button)

        # Handle debug link connection
        msg = debug_transport.read()
        if msg is not None:
            print "Received debuglink", msg.__class__.__name__, msg
            if isinstance(msg, proto.DebugLinkDecision):
                # Press the button
                button = msg.yes_no
            else:
                resp = machine.process_debug_message(msg)
                if resp is not None:
                    print "Sending debuglink", resp.__class__.__name__, resp
                    debug_transport.write(resp)
                    is_active = True

        if button is not None:
            print "Button", button
            is_active = True

            resp = machine.press_button(button)
            if resp is not None:
                print "Sending", resp
                transport.write(resp)

        # Handle main connection
        msg = transport.read()
        if msg is not None:
            print "Received", msg.__class__.__name__, msg
            resp = machine.process_message(msg)
            if resp is not None:
                print "Sending", resp.__class__.__name__, resp
                transport.write(resp)
                is_active = True

        if not is_active:
            # Nothing to do, sleep for a moment
            time.sleep(0.05)

    # Close transports
    transport.close()
    debug_transport.close()
Example #58
0
class Game:

    def __init__(self):
        self.status          = True
        self.size            = (WIDTH, HEIGHT)
        self.caption         = CAPTION
        self.dirty_rects     = pygame.sprite.Group()
        self.limit_cells     = []
        self.block_locations = []

    def start(self):
        self.layout = Layout(LEVEL_ONE_GRID_FOLDER)

        self._init_pygame()

        self._load_sprites()

        self._fill_limit_cells()

        clock = pygame.time.Clock()        

        while self.status:
            # Limit frame speed to 60 FPS.
            time_passed = clock.tick(60)

            # Handle key events.
            for event in pygame.event.get():
                self._on_event(event)

            self._on_render()

            # Update all of the needed sprites
            self._on_loop()


        # Close app.
        self._on_cleanup()

    def _init_pygame(self):
        pygame.init()
        self.screen = pygame.display.set_mode(self.size)
        pygame.display.set_caption(self.caption)

    def _on_event(self, event):
        if (event.type == pygame.QUIT) or (event.type == pygame.KEYDOWN and
            event.key == K_ESCAPE):
            self.status = False

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                self.packman.changespeed(-PACKMAN_STEP, 0)
            elif event.key == pygame.K_RIGHT:
                self.packman.changespeed(PACKMAN_STEP, 0)
            elif event.key == pygame.K_UP:
                self.packman.changespeed(0, -PACKMAN_STEP)
            elif event.key == pygame.K_DOWN:
                self.packman.changespeed(0, PACKMAN_STEP)
 
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                self.packman.changespeed(PACKMAN_STEP, 0)
            elif event.key == pygame.K_RIGHT:
                self.packman.changespeed(-PACKMAN_STEP, 0)
            elif event.key == pygame.K_UP:
                self.packman.changespeed(0, PACKMAN_STEP)
            elif event.key == pygame.K_DOWN:
                self.packman.changespeed(0, -PACKMAN_STEP)
        

    def _on_loop(self):
        self.screen.fill(BLACK)

        self.dirty_rects.update()
        self.dirty_rects.draw(self.screen)

        pygame.sprite.spritecollide(self.packman, self.ghosts, False)

        pygame.display.flip()

    def _on_render(self):
        pos = self.packman.pos
        for ghost in self.ghosts:
            ghost.packman_pos = pos
            ghost.draw(self.screen)

    def _on_cleanup(self):
        pygame.quit()

    def _load_sprites(self):

        self._load_walls()

        self._load_pellets()

        self._load_packman()

        self._load_ghosts()

    def _load_packman(self):
        self.packman = Packman(400, 320)
        self.packman.blocks = self.blocks
        self.packman.pellets = self.pellets
        self.dirty_rects.add(self.packman)
        
    def _load_ghosts(self):
        self.ghosts = pygame.sprite.Group()
        for x in [340, 370, 400, 430]:
            ghost = Blinky(x, 290, self.packman.pos)
            ghost.blocks = self.blocks

            self.ghosts.add(ghost)
            self.dirty_rects.add(ghost)



    def _load_walls(self):
        self.blocks = pygame.sprite.Group()
        blocks_layout = self.layout.read_layout(BLOCKS_LAYOUT_FILE)

        for line in blocks_layout:
            block = Block(int(line[0]),
                          int(line[1]),
                          int(line[2]),
                          int(line[3]))

            self.limit_cells.append((block.rect.topleft, block.rect.bottomright))

            self.blocks.add(block)
            self.dirty_rects.add(block)

    def _load_pellets(self):
        self.pellets = pygame.sprite.Group()
        pellets_layout = self.layout.read_layout(PELLETS_LAYOUT_FILE)

        for line in pellets_layout:
            pellet = Pellet(int(line[0]),
                            int(line[1]),
                            int(line[2]))

            self.pellets.add(pellet)
            self.dirty_rects.add(pellet)

    def _fill_limit_cells(self):
        for pair in self.limit_cells:
            self._fill_limit_cell(pair)

    def _fill_limit_cell(self, pair):
        #include the border cases
        for x in range(pair[0][0], pair[1][0] + 1):
            for y in range(pair[0][1], pair[1][1] + 1): 
                self.block_locations.append((x,y))
Example #59
0
def main(args):
    # Initialize main transport
    transport = get_transport(args.transport, args.path)

    # Initialize hardware (screen, buttons)
    but = Buttons(hw=args.shield, stdin=not args.shield, pygame=not args.shield)
    buff = DisplayBuffer(DISPLAY_WIDTH, DISPLAY_HEIGHT)
    display = Display(buff, spi=args.shield, virtual=not args.shield)
    display.init()

    # Initialize layout driver
    layout = Layout(buff)

    # Startup state machine and switch it to default state
    machine = StateMachine(args.keyfile, layout)

    display.refresh()

    # Main cycle
    while True:
        # Set True if device does something
        # False = device will sleep for a moment
        is_active = False

        try:
            # Read button states
            button = but.read()
        except KeyboardInterrupt:
            # User requested to close the app
            break

        if button is not None:
            print "Button", button
            is_active = True

            resp = machine.press_button(button)
            if resp is not None:
                print "Sending", resp
                transport.write(resp)

        # Handle main connection
        msg = transport.read()
        if msg is not None:
            print "Received", msg.__class__.__name__  # , msg
            resp = machine.process_message(msg)
            if resp is not None:
                print "Sending", resp.__class__.__name__, resp
                transport.write(resp)
                is_active = True

        # Display scrolling
        is_active |= layout.update()

        if layout.need_refresh:
            # Update display
            display.refresh()

        if not is_active:
            # Nothing to do, sleep for a moment
            time.sleep(0.1)

    # Close transports
    transport.close()