示例#1
0
 def __init__(self,
              text,
              x=0,
              y=0,
              width=200,
              height=200,
              font=config.DEFAULT_FONT_PATH,
              size=config.DEFAULT_FONT_SIZE,
              rgb=(255, 255, 255)):
     #Glyph variables
     Sprite.__init__(self, x, y)
     self.x = x
     self.y = y
     self.entries = {}
     Macros['red'] = ('color', (255, 0, 0))
     self.font = pygame.font.Font(font, size)
     self.args = {
         'bkg': (30, 30, 30),
         'color': (255, 255, 255),
         'font': self.font,
         'spacing': 0
     }
     height = self.heightCalculation(text)
     self.glyph = Glyph(Rect(x + 10, y + 6, width, height),
                        ncols=1,
                        **self.args)
     self.entries['0'] = text
     self.glyph.input(self.entries['0'])
     self.glyph.update()
     #Draw background and border
     self.drawBox()
     #Process input for link processing
     self.process_input = True
示例#2
0
def createText(text, rect, justify = None, font = 'defaultFont', color = 'black'):
    text = "{" + font + "; " + "{" + color + "; " + text + "}}"
    glyph = Glyph(rect)
    glyph.input(text, justify)
    glyph.update()
    
    return glyph
示例#3
0
    def get_glyph(self, font, char_code, font_size, font_width, font_height):
        """
        find glyph, create it if not found
        """
        if font is None:
            font = self.default_font

        elif isinstance(font, Font):
            font = font
        else:
            font = self._scene.find_font(font)

        for glyph in self._glyphs:
            if glyph.char_code == char_code and \
                    glyph.font == font and \
                    glyph.font_size == font_size and \
                    glyph.width == font_width and \
                    glyph.height == font_height:
                return glyph

        glyph = Glyph(font, char_code, font_size, font_width, font_height)
        logger.debug(glyph)
        self._glyphs.append(glyph)
        glyph.object_index = len(self._glyphs) - 1
        return glyph
示例#4
0
文件: example.py 项目: LukeMS/glyph
    def __init__(self):
        self.glyph = Glyph(CLIP, ncols=2, **DEFAULT)

        Macros['b'] = ('font', Font(P_BOLD, 8))
        Macros['big'] = ('font', Font(P_REG, 16))
        Macros['BIG'] = ('font', Font(P_BOLD, 16))
        Macros['red'] = ('color', RED)
        Macros['green'] = ('color', GREEN)
        Macros['bkg_blu'] = ('bkg', BLUE)
        Macros['red_pot'] = REDPOT

        self.editor = Editor(EDITOR_CLIP, **DEFAULT)
        self.editor_info = Glyph(EDITOR_INFO_CLIP, **DEFAULT)
示例#5
0
 def get_glyph(self):
     type = random.choice(list(GLYPHS.keys()))
     angle = random.choice([0, 1, 2, 3])
     self.glyph = Glyph(type, angle)
     self.glyph.rect.topleft = self.spawn_pos
     self.used = False
     self.dirty = True
示例#6
0
 def get_glyph(self):
     ## create glyph
     type = G.next_glyph.glyph.type
     angle = G.next_glyph.glyph.angle
     self.glyph = Glyph(type, angle)
     self.glyph.rect.topleft = self.spawn_pos
     ## offset horizontal 'I'
     if self.glyph.rect.width // G.cell_w == 4:
         self.glyph.rect.left -= G.cell_w
     ## set flags
     G.next_glyph.used = True
     self.dirty = True
     ## check collision on spawn
     if self.collision(0, 0, 0):
         G.state = 'finished'
         G.message.set_text('game over', 'press enter')
         G.highscores.add(G.score)
示例#7
0
文件: world.py 项目: tartley/pyong
    def add(self, item, position):
        item.itemid = World._next_id
        self.items[World._next_id] = item
        World._next_id += 1

        item.physics = PhysicsItem(item)
        self.physics.add(item.physics, position, item.static)

        item.glyph = Glyph.from_item(item)
示例#8
0
def map_print(user, maps):
    FONT = Font("silkscreen.ttf", 16)
    DEFAULT = {
        'bkg': (0, 0, 0),
        'color': (250, 250, 250),
        'font': FONT,
        'spacing': 0,  #FONT.get_linesize(),
    }
    x = user.position[1]
    y = user.position[2]
    px = user.position[3]
    py = user.position[4]
    maps[y][x] = " "
    maps[py][px] = "+"
    conector = ""
    maps_impreso = []

    for linea in maps:

        imprimir = conector.join(linea)

        maps_impreso.append(imprimir)

    maps_impreso = conector.join(maps_impreso)
    glyph = Glyph(Rect(0, 0, 600, 600), ncols=1, **DEFAULT)
    glyph.input(maps_impreso, justify='justified')
    glyph.update()

    return (glyph)
示例#9
0
 def read(self, dirname):
     files = os.listdir(dirname)
     for file in files:
         curr_dir = os.path.dirname(os.path.realpath(__file__))
         filename = os.path.join(curr_dir, dirname, file)
         with open(filename) as f:
             text = f.read()
             d = eval(text)
             for k, v in d.iteritems():
                 self.glyphs[k] = Glyph(data=v.split('\n')[1:-1])
                 w = self.glyphs[k].size[0]
                 h = self.glyphs[k].size[1]
                 self.size = max(self.size[0], w), max(self.size[1], h)
示例#10
0
    def glyphs(self):
        if not hasattr(self, "__glyphs"):
            from fonts import fonts
            from shapely.wkb import loads
            from glyph import Glyph

            self.__glyphs = {}
            for glyphRow in fonts.sql.getGlyphs(getFontTableName(self.name)):
                name, unicodeCode, geomWKB = glyphRow
                geom = loads(geomWKB, hex=True)
                self.__glyphs[name] = Glyph(name, unicodeCode, geom)

        return self.__glyphs
示例#11
0
    def __init__(self, svgFileName, charsToBeLoaded=None):
        self.name = changeFileExtension(extractFileName(svgFileName), "")

        self.glyphs = {}
        self.defaults = Container({
            "width": 556,
            "height": None,
            "x": None,
            "y": None
        })

        log.openSection("Reading glyphs from %s" % svgFileName, log.DEBUG)
        svgData = open(svgFileName, "r").read().replace('\n', '')

        self.letters = u""
        startPos = 0
        while startPos < len(svgData):
            startPos = svgData.find('<glyph', startPos)
            if startPos >= 0:
                endPos = svgData.find("/>", startPos) + 2
                if endPos >= 0:
                    tag = svgData[startPos:endPos]
                    glyph = Glyph(tag, self)

                    if isinstance(glyph.unicode, list):
                        unicodes = glyph.unicode
                    else:
                        unicodes = [glyph.unicode]
                    for unicode in unicodes:
                        if not charsToBeLoaded or unicode in charsToBeLoaded:
                            self.letters += unicode
                            self.glyphs[unicode] = glyph
                    startPos = endPos
                else:
                    log.error("Unclosed glyph tag at %d" % startPos)
                    break
            else:
                break

        self.letters = "".join(sorted(self.letters))

        if charsToBeLoaded and len(charsToBeLoaded) <> len(self.glyphs.keys()):
            log.openSection("Not all characters found!", log.WARNING)
            log.warning("%d characters to be loaded, %d found" %
                        (len(charsToBeLoaded), len(self.glyphs.keys())))

            log.closeSection(level=log.WARNING)
        log.closeSection("%d glyphs found" % len(self.glyphs.keys()),
                         level=log.DEBUG)
示例#12
0
 def __init__(self,text,x=0,y=0,width=200,height=200,font=config.DEFAULT_FONT_PATH,size=config.DEFAULT_FONT_SIZE, rgb=(255,255,255)):
     #Glyph variables
     Sprite.__init__(self,x,y)
     self.x=x
     self.y=y
     self.entries={}
     Macros['red'] = ('color', (255, 0, 0))
     self.font = pygame.font.Font(font, size)
     self.args={'bkg'       : (30, 30, 30),'color'     : (255, 255, 255),'font'      : self.font,'spacing'   : 0}
     height=self.heightCalculation(text)
     self.glyph = Glyph(Rect(x+10, y+6, width, height), ncols=1, **self.args)
     self.entries['0']=text
     self.glyph.input(self.entries['0'])
     self.glyph.update()
     #Draw background and border
     self.drawBox()
     #Process input for link processing
     self.process_input=True
示例#13
0
class TextBox(Sprite):
    def __init__(self,text,x=0,y=0,width=200,height=200,font=config.DEFAULT_FONT_PATH,size=config.DEFAULT_FONT_SIZE, rgb=(255,255,255)):
        #Glyph variables
        Sprite.__init__(self,x,y)
        self.x=x
        self.y=y
        self.entries={}
        Macros['red'] = ('color', (255, 0, 0))
        self.font = pygame.font.Font(font, size)
        self.args={'bkg'       : (30, 30, 30),'color'     : (255, 255, 255),'font'      : self.font,'spacing'   : 0}
        height=self.heightCalculation(text)
        self.glyph = Glyph(Rect(x+10, y+6, width, height), ncols=1, **self.args)
        self.entries['0']=text
        self.glyph.input(self.entries['0'])
        self.glyph.update()
        #Draw background and border
        self.drawBox()
        #Process input for link processing
        self.process_input=True

    def heightCalculation(self,text):
        words_per_line=6
        lines=0
        total_words = len(text.split())
        print (total_words)
        height = 16 * (total_words/words_per_line)
        if (height<16):
            height=16
        return height


    def drawBox(self):
        self.image = pygame.Surface((self.glyph.rect.width+20,self.glyph.rect.height+12))
        self.image.fill((30, 30, 30))
        pygame.draw.rect(self.image,(255,255,255),self.image.get_rect(),1)
        inner_rect=self.image.get_rect()
        inner_rect.x, inner_rect.y, inner_rect.width, inner_rect.height= inner_rect.x+4, inner_rect.y+4, inner_rect.width-8, inner_rect.height-8
        pygame.draw.rect(self.image,(255,255,255),inner_rect,1)
        self.image.blit(self.glyph.image,(10,6))
        self.rect=self.image.get_rect()
        self.rect.x,self.rect.y = self.x,self.y 
        self.spriteGroup=pygame.sprite.LayeredDirty(self)

    def addMacro(self, name, argument):
        Macros[name]=argument

    def addEntry(self, name, text):
        self.entries[name]=text

    def processInput(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            posx,posy=event.pos
            link = self.glyph.get_collisions(event.pos)
            if link:
                self.glyph.clear()
                self.glyph.input(self.entries[link], justify = 'justified') 
                self.glyph.update()
                self.drawBox()
            if self.rect.collidepoint(posx,posy):
                return True
示例#14
0
class TextBox(Sprite):
    def __init__(self,
                 text,
                 x=0,
                 y=0,
                 width=200,
                 height=200,
                 font=config.DEFAULT_FONT_PATH,
                 size=config.DEFAULT_FONT_SIZE,
                 rgb=(255, 255, 255)):
        #Glyph variables
        Sprite.__init__(self, x, y)
        self.x = x
        self.y = y
        self.entries = {}
        Macros['red'] = ('color', (255, 0, 0))
        self.font = pygame.font.Font(font, size)
        self.args = {
            'bkg': (30, 30, 30),
            'color': (255, 255, 255),
            'font': self.font,
            'spacing': 0
        }
        height = self.heightCalculation(text)
        self.glyph = Glyph(Rect(x + 10, y + 6, width, height),
                           ncols=1,
                           **self.args)
        self.entries['0'] = text
        self.glyph.input(self.entries['0'])
        self.glyph.update()
        #Draw background and border
        self.drawBox()
        #Process input for link processing
        self.process_input = True

    def heightCalculation(self, text):
        words_per_line = 6
        lines = 0
        total_words = len(text.split())
        print(total_words)
        height = 16 * (total_words / words_per_line)
        if (height < 16):
            height = 16
        return height

    def drawBox(self):
        self.image = pygame.Surface(
            (self.glyph.rect.width + 20, self.glyph.rect.height + 12))
        self.image.fill((30, 30, 30))
        pygame.draw.rect(self.image, (255, 255, 255), self.image.get_rect(), 1)
        inner_rect = self.image.get_rect()
        inner_rect.x, inner_rect.y, inner_rect.width, inner_rect.height = inner_rect.x + 4, inner_rect.y + 4, inner_rect.width - 8, inner_rect.height - 8
        pygame.draw.rect(self.image, (255, 255, 255), inner_rect, 1)
        self.image.blit(self.glyph.image, (10, 6))
        self.rect = self.image.get_rect()
        self.rect.x, self.rect.y = self.x, self.y
        self.spriteGroup = pygame.sprite.LayeredDirty(self)

    def addMacro(self, name, argument):
        Macros[name] = argument

    def addEntry(self, name, text):
        self.entries[name] = text

    def processInput(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            posx, posy = event.pos
            link = self.glyph.get_collisions(event.pos)
            if link:
                self.glyph.clear()
                self.glyph.input(self.entries[link], justify='justified')
                self.glyph.update()
                self.drawBox()
            if self.rect.collidepoint(posx, posy):
                return True
示例#15
0
class D3Display:
    def __init__(self):
        # Get origin
        origin_path = rospy.get_param("~origin_path",
                                      "")  # TODO add loading of origin
        self.recording_state = False  # TODO make a recording button

        # Display
        size = (800, 480)  # Size of WaveRacer 4inch screen
        pygame.init()
        self.display = pygame.display.set_mode(size, 0)
        self.box_font = pygame.font.SysFont('monospaced', 30)
        self.side_rect = pygame.Rect(400, 0, 800, 480)
        self.bottom_rect = pygame.Rect(0, 400, 800, 480)
        # Side box displays depth, heading, location etc.
        self.side_box = Glyph(self.side_rect, font=self.box_font)
        # Bottom box holds logs
        self.bottom_box = Glyph(self.bottom_rect, font=self.box_font)
        Macros['L'] = ('font', pygame.font.SysFont('monospaced', 50))
        Macros['M'] = ('font', pygame.font.SysFont('monospaced', 40))
        Macros['S'] = ('font', pygame.font.SysFont('monospaced', 30))
        Macros['red'] = ('color', (255, 0, 0))
        Macros['green'] = ('color', (0, 255, 0))
        Macros['blue'] = ('color', (0, 0, 255))

        # Variables
        self.H = 0.  # ???
        self.A = 0.  # ???
        self.depth = 0.  # ???
        self.gps_msg = NavSatFix()
        self.battery_state = BatteryState()
        self.R = 0.0  # ???
        self.P = 0.0  # ???

        self.cpu = 0.0  # ???
        self.hdd = 0.0  # ???
        self.upt = 0.0  # ???

        self.recording_state = False

        self.img = None
        self.log_list = []

        self.bridge = CvBridge()

        # Setup timer to update display
        screen_hz = rospy.get_param("~screen_hz", 2.0)
        rospy.Timer(rospy.Duration(screen_hz), self.screenUpdateCallback)

        # Subscribers
        compass_topic = "/navio/compass"
        gps_topic = "/navio/gps"
        log_topic = "/logs"
        img_topic = "/image_small"
        battery_topic = "/navio/ups"
        depth_topic = "/depth"
        rec_topic = '/recording'
        rospy.Subscriber(img_topic, Image, self.imgCallback)
        rospy.Subscriber(gps_topic, NavSatFix, self.gpsCallback)
        rospy.Subscriber(compass_topic, Float32, self.compassCallback)
        rospy.Subscriber(log_topic, String, self.logCallback)
        rospy.Subscriber(battery_topic, BatteryState, self.batteryCallback)
        rospy.Subscriber(depth_topic, Vector3Stamped, self.depthCallback)
        rospy.Subscriber(rec_topic, Bool, self.recCallback)

    def recCallback(self, msg):
        self.recording_state = msg.data

    def logCallback(self, msg):
        self.log_list.append(str(msg.data))

    def screenUpdateCallback(self, event):
        # Side display - location, heading, depth etc.
        dispstr = "{{L; H:\t{}\n}}".format(self.R)
        dispstr += "{{L; A:\t{}\n}}".format(self.A)
        dispstr += "{{L; D:\t{}\n}}".format(self.depth)
        dispstr += "{{S; LAT:\t{}\n}}".format(self.gps_msg.latitude)
        dispstr += "{{S; LON:\t{}\n}}".format(self.gps_msg.longitude)
        dispstr += "{{S; R:\t{}\n}}".format(self.R)
        dispstr += "{{S; P:\t{}\n}}".format(self.P)
        dispstr += "{} \n".format(1)
        dispstr += "{{S; BAT: {}\n}}".format(self.battery_state.charge)
        dispstr += "{{S; CPU: {}\n}}".format(self.cpu)
        dispstr += "{{S; HDD: {}\n}}".format(self.hdd)
        dispstr += "{{S; Uptime: {}\n}}".format(self.upt)

        dispstr += "{{L; Rec:\t{}\n}}".format(self.recording_state)

        self.side_box.clear()
        self.side_box.input(dispstr)
        self.side_box.update()
        self.display.blit(self.side_box.image, self.side_rect)

        # Bottom box - logs
        if len(self.log_list) > 0:
            if len(self.log_list) > 3:
                self.log_list = self.log_list[-3:]
            for n, log in enumerate(self.log_list):
                if n == 0:
                    # disp_logs = "Log:\t{}".format(log)
                    disp_logs = "{{S; {}\n}}".format(log.replace('/', '|'))
                else:
                    # disp_logs += "Log:\t{}".format(log)
                    disp_logs += "{{S; {}\n}}".format(log.replace('/', '|'))
            self.bottom_box.clear()
            self.bottom_box.input(disp_logs)
            self.bottom_box.update()
            self.display.blit(self.bottom_box.image, self.bottom_rect)

        # Image display
        if self.img is not None:
            surface = pygame.surfarray.make_surface(self.img)
            surface = pygame.transform.rotate(surface, -90)
            self.display.blit(surface, (0, 0))

        # update the display
        pygame.display.flip()

    def imgCallback(self, msg):
        self.img = self.bridge.imgmsg_to_cv2(msg, "passthrough")
        self.img = cv2.cvtColor(self.img, cv2.COLOR_BGR2RGB)
        self.img = cv2.resize(self.img, (400, 400))

    def compassCallback(self, msg):
        self.compass = msg.data

    def depthCallback(self, msg):
        self.depth = msg.vector.z

    def gpsCallback(self, msg):
        self.gps_msg = msg

    def batteryCallback(self, msg):
        self.battery_state = msg
示例#16
0
class ThisGlyph:
    '''
    =============================
    __init__
    =============================
    '''
    def __init__(self):
        self.spawn_pos = (G.well.rect.left + G.cell_w * (WELL_W // 2 - 1),
                          G.well.rect.top)
        self.glyph = None
        self.reinit()
        self.dirty = False
        ## actions
        self.move_left = False
        self.move_left_now = False
        self.move_right = False
        self.move_right_now = False
        self.rotate = False
        self.drop = False
        ## movement repeat control
        self._mov_left = False
        self._mov_right = False
        self._mov_time = 0
        self._delay = True

    '''
    =============================
    reinit
    =============================
    '''

    def reinit(self):
        self.cell = Cell()
        self.spawn_pos = (G.well.rect.left + G.cell_w * (WELL_W // 2 - 1),
                          G.well.rect.top)
        self.rect = pygame.Rect(0, 0, 0, 0)
        self.rect_old = pygame.Rect(0, 0, 0, 0)
        G.dirty_rects.append(self.rect)
        G.dirty_rects.append(self.rect_old)
        if self.glyph:
            self.glyph.rect.left = G.well.rect.left + self.glyph.pos_in_well[
                0] * G.cell_w
            self.glyph.rect.top = G.well.rect.top + self.glyph.pos_in_well[
                1] * G.cell_w
            self.glyph.rect.width = self.glyph.cells[
                self.glyph.angle].shape[1] * G.cell_w
            self.glyph.rect.height = self.glyph.cells[
                self.glyph.angle].shape[0] * G.cell_w

    '''
    =============================
    update
    =============================
    '''

    def update(self, dt):
        ## generate repeated movement
        self.generate_move(dt)

        # glyph guardian
        if not self.glyph: self.get_glyph()

        ## save old rect in case we'll need to erase the old glyph
        self.match_rect_to_glyph(self.rect_old)

        ## actions
        if self.drop: self.drop_glyph()
        if self.rotate: self.rorate_glyph()
        if self._mov_left: self.move_glyph_left()
        if self._mov_right: self.move_glyph_right()

        ## on tick edge or drop glyph either moves down or gets placed
        if G.tick_edge or self.drop: self.fall_or_place()

        ## update rects
        if self.dirty:
            self.match_rect_to_glyph(self.rect)
        else:
            self.rect.size = (0, 0)
            self.rect_old.size = (0, 0)

    '''
    =============================
    draw
    =============================
    '''

    def draw(self, screen):
        ## erase old glyph
        if self.rect_old.size != (0, 0):
            patch_rect = self.rect_old.copy()
            patch_rect.left -= G.well.rect.left
            patch_rect.top -= G.well.rect.top
            patch = G.well.surface.subsurface(patch_rect)
            screen.blit(patch, self.rect_old)

        if self.glyph.rect.top < 0:
            ## draw part of the glyph
            row = abs(self.glyph.rect.top) // G.cell_w
            cells = np.nditer(self.glyph.cells[self.glyph.angle][row:],
                              flags=['multi_index'])
            for cell in cells:
                if cell:
                    x = self.glyph.rect.left + cells.multi_index[
                        1] * G.cell_w + 1
                    y = cells.multi_index[0] * G.cell_w + 1
                    screen.blit(self.cell.surface, (x, y))
        else:
            ## draw full glyph
            cells = np.nditer(self.glyph.cells[self.glyph.angle],
                              flags=['multi_index'])
            for cell in cells:
                if cell:
                    x = self.glyph.rect.left + cells.multi_index[
                        1] * G.cell_w + 1
                    y = self.glyph.rect.top + cells.multi_index[
                        0] * G.cell_w + 1
                    screen.blit(self.cell.surface, (x, y))

        ## clear the dirty attribute
        self.dirty = False

    '''
    =============================
    get_glyph
    =============================
    '''

    def get_glyph(self):
        ## create glyph
        type = G.next_glyph.glyph.type
        angle = G.next_glyph.glyph.angle
        self.glyph = Glyph(type, angle)
        self.glyph.rect.topleft = self.spawn_pos
        ## offset horizontal 'I'
        if self.glyph.rect.width // G.cell_w == 4:
            self.glyph.rect.left -= G.cell_w
        ## set flags
        G.next_glyph.used = True
        self.dirty = True
        ## check collision on spawn
        if self.collision(0, 0, 0):
            G.state = 'finished'
            G.message.set_text('game over', 'press enter')
            G.highscores.add(G.score)

    '''
    =============================
    fall_or_place
    =============================
    '''

    def fall_or_place(self):
        self.drop = False
        self.dirty = True
        if self.collision(0, 1):
            ## place
            left, top, right, bot = self.get_position()
            top += 2
            bot += 2
            G.well.cells[top:bot + 1,
                         left:right + 1] |= self.glyph.cells[self.glyph.angle]
            ## get new glyph
            self.get_glyph()
        else:
            ## fall
            self.glyph.rect.top += G.cell_w

    '''
    =============================
    drop_glyph
    =============================
    '''

    def drop_glyph(self):
        i = 0
        while not self.collision(0, i):
            i += 1
        self.glyph.rect.top += (i - 1) * G.cell_w

    '''
    =============================
    move_glyph_left
    =============================
    '''

    def move_glyph_left(self):
        self._mov_left = False
        if not self.collision(-1, 0):
            self.glyph.rect.left -= G.cell_w
            self.dirty = True

    '''
    =============================
    move_glyph_right
    =============================
    '''

    def move_glyph_right(self):
        self._mov_right = False
        if not self.collision(1, 0):
            self.glyph.rect.left += G.cell_w
            self.dirty = True

    '''
    =============================
    rorate_glyph
    =============================
    '''

    def rorate_glyph(self):
        self.rotate = False

        if self.glyph.type == 'O': pass

        elif self.glyph.type == 'I':
            if self.glyph.angle in (0, 2) and not self.collision(2, -2, 1):
                self.glyph.rotate()
                self.glyph.rect.left += G.cell_w * 2
                self.glyph.rect.top -= G.cell_w * 2
                self.dirty = True
            elif self.glyph.angle in (1, 3) and not self.collision(-2, 2, 1):
                self.glyph.rotate()
                self.glyph.rect.left -= G.cell_w * 2
                self.glyph.rect.top += G.cell_w * 2
                self.dirty = True

        elif self.glyph.type in ('J', 'L', 'T'):
            if self.glyph.angle == 0 and not self.collision(0, -1, 1):
                self.glyph.rotate()
                self.glyph.rect.top -= G.cell_w
                self.dirty = True
            elif self.glyph.angle == 1 and not self.collision(0, 0, 1):
                self.glyph.rotate()
                self.dirty = True
            elif self.glyph.angle == 2 and not self.collision(1, 0, 1):
                self.glyph.rotate()
                self.glyph.rect.left += G.cell_w
                self.dirty = True
            elif self.glyph.angle == 3 and not self.collision(-1, 1, 1):
                self.glyph.rotate()
                self.glyph.rect.left -= G.cell_w
                self.glyph.rect.top += G.cell_w
                self.dirty = True

        elif self.glyph.type == 'S':
            if self.glyph.angle in (0, 2) and not self.collision(0, -1, 1):
                self.glyph.rotate()
                self.glyph.rect.top -= G.cell_w
                self.dirty = True
            elif self.glyph.angle in (1, 3) and not self.collision(0, 1, 1):
                self.glyph.rotate()
                self.glyph.rect.top += G.cell_w
                self.dirty = True

        elif self.glyph.type == 'Z':
            if self.glyph.angle in (0, 2) and not self.collision(1, -1, 1):
                self.glyph.rotate()
                self.glyph.rect.left += G.cell_w
                self.glyph.rect.top -= G.cell_w
                self.dirty = True
            elif self.glyph.angle in (1, 3) and not self.collision(-1, 1, 1):
                self.glyph.rotate()
                self.glyph.rect.left -= G.cell_w
                self.glyph.rect.top += G.cell_w
                self.dirty = True

    '''
    =============================
    generate_move
    =============================
    '''

    def generate_move(self, dt):
        if not (self.move_left or self.move_right):
            self._delay = True
            self._mov_time = 0
        else:
            if self.move_left_now:
                self.move_left_now = False
                self._mov_left = True
            elif self.move_right_now:
                self.move_right_now = False
                self._mov_right = True
            elif self._delay and self._mov_time > MOVE_DELAY:
                self._delay = False
                self._mov_time = 0
                if self.move_left: self._mov_left = True
                if self.move_right: self._mov_right = True
            elif not self._delay and self._mov_time > MOVE_INTERVAL:
                self._mov_time = 0
                if self.move_left: self._mov_left = True
                if self.move_right: self._mov_right = True
            else:
                self._mov_time += dt

    '''
    =============================
    match_rect_to_glyph
    =============================
    '''

    def match_rect_to_glyph(self, rect):
        if self.glyph.rect.top < 0:
            rect.top = 0
            rect.left = self.glyph.rect.left
            rect.height = self.glyph.rect.height + self.glyph.rect.top
            rect.width = self.glyph.rect.width
        else:
            rect.topleft = self.glyph.rect.topleft
            rect.size = self.glyph.rect.size

    '''
    =============================
    get_position
    =============================
    '''

    def get_position(self, a=None):
        if a is None: a = self.glyph.angle
        left = (self.glyph.rect.left - G.well.rect.left) // G.cell_w
        top = (self.glyph.rect.top - G.well.rect.top) // G.cell_w
        right = left + self.glyph.cells[a].shape[1] - 1
        bot = top + self.glyph.cells[a].shape[0] - 1
        return left, top, right, bot

    '''
    =============================
    collision
    =============================
    '''

    def collision(self, x, y, a=0):
        '''(x, y) is position offset, a is angle offset in [-1, 0, 1]'''
        if self.glyph.angle + a > 3: a = 0
        elif self.glyph.angle + a < 0: a = 3
        else: a += self.glyph.angle
        left, top, right, bot = self.get_position(a)
        left += x
        right += x
        top += y
        bot += y
        ## check well boundary
        if left < 0 or right > WELL_W - 1 or bot > WELL_H - 1: return True
        ## check well contents
        top += 2
        bot += 2
        return (G.well.cells[top:bot + 1, left:right + 1]
                & self.glyph.cells[a]).any()
示例#17
0
def homogenize(g):
    a, b, c, d = g, g.rotated_90, g.rotated_90.rotated_90, g.rotated_90.rotated_90.rotated_90
    a_h = a.flip_horizontal
    b_h, c_h, d_h = a_h.rotated_90, a_h.rotated_90.rotated_90, a_h.rotated_90.rotated_90.rotated_90
    a_w = a.flip_vertical
    b_w, c_w, d_w = a_w.rotated_90, a_w.rotated_90.rotated_90, a_w.rotated_90.rotated_90.rotated_90
    selection = {a, b, c, d, a_h, b_h, c_h, d_h, a_w, b_w, c_w, d_w}
    if not (a.width == b.width == c.width == d.width):
        if a.width < b.width:
            map(selection.remove, (a, c, a_h, c_h, a_w, c_w))
        else:
            map(selection.remove, (b, d, b_h, d_h, b_w, d_w))
    representative = min(selection, key=lambda glyph: glyph.score)
    selection.remove(representative)
    return representative, selection


if __name__ == "__main__":
    memo = {}
    generations = 0
    this_generation = {Glyph()}
    for i in range(generations + 1):
        print(f"Gen {i} ", end="-" * 80 + "\n")
        next_generation = {}
        for glyph in this_generation:
            rep, selection = homogenize(glyph)
            m = {'representative': rep, 'all_forms': selection | {rep}}
            for form in selection | {rep}:
                memo[form] = m
                next_generation |= form.children
示例#18
0
    def __init__(self):
        # Get origin
        origin_path = rospy.get_param("~origin_path",
                                      "")  # TODO add loading of origin
        self.recording_state = False  # TODO make a recording button

        # Display
        size = (800, 480)  # Size of WaveRacer 4inch screen
        pygame.init()
        self.display = pygame.display.set_mode(size, 0)
        self.box_font = pygame.font.SysFont('monospaced', 30)
        self.side_rect = pygame.Rect(400, 0, 800, 480)
        self.bottom_rect = pygame.Rect(0, 400, 800, 480)
        # Side box displays depth, heading, location etc.
        self.side_box = Glyph(self.side_rect, font=self.box_font)
        # Bottom box holds logs
        self.bottom_box = Glyph(self.bottom_rect, font=self.box_font)
        Macros['L'] = ('font', pygame.font.SysFont('monospaced', 50))
        Macros['M'] = ('font', pygame.font.SysFont('monospaced', 40))
        Macros['S'] = ('font', pygame.font.SysFont('monospaced', 30))
        Macros['red'] = ('color', (255, 0, 0))
        Macros['green'] = ('color', (0, 255, 0))
        Macros['blue'] = ('color', (0, 0, 255))

        # Variables
        self.H = 0.  # ???
        self.A = 0.  # ???
        self.depth = 0.  # ???
        self.gps_msg = NavSatFix()
        self.battery_state = BatteryState()
        self.R = 0.0  # ???
        self.P = 0.0  # ???

        self.cpu = 0.0  # ???
        self.hdd = 0.0  # ???
        self.upt = 0.0  # ???

        self.recording_state = False

        self.img = None
        self.log_list = []

        self.bridge = CvBridge()

        # Setup timer to update display
        screen_hz = rospy.get_param("~screen_hz", 2.0)
        rospy.Timer(rospy.Duration(screen_hz), self.screenUpdateCallback)

        # Subscribers
        compass_topic = "/navio/compass"
        gps_topic = "/navio/gps"
        log_topic = "/logs"
        img_topic = "/image_small"
        battery_topic = "/navio/ups"
        depth_topic = "/depth"
        rec_topic = '/recording'
        rospy.Subscriber(img_topic, Image, self.imgCallback)
        rospy.Subscriber(gps_topic, NavSatFix, self.gpsCallback)
        rospy.Subscriber(compass_topic, Float32, self.compassCallback)
        rospy.Subscriber(log_topic, String, self.logCallback)
        rospy.Subscriber(battery_topic, BatteryState, self.batteryCallback)
        rospy.Subscriber(depth_topic, Vector3Stamped, self.depthCallback)
        rospy.Subscriber(rec_topic, Bool, self.recCallback)
示例#19
0
 def add_chars(self, chars):
     """Create glyph objects for the added chars and add them to the font."""
     for char in chars:
         self._face.load_char(char, freetype.FT_LOAD_RENDER | freetype.FT_LOAD_TARGET_MONO)
         glyph = Glyph.from_glyph_slot(char, self._face.glyph)
         self._glyphs.append(glyph)
示例#20
0
    def layoutGlyphs(self):
        allGlyphs = []
        wordGlyphs = []

        xloc = self.x
        yloc = self.y

        metrics = Glyph(0, 0, capHeight=self.size)

        for i in range(len(self.glyphs)):
            a = self.glyphs[i]

            if i + 1 < len(self.glyphs):
                b = self.glyphs[i + 1]
            else:
                b = None

            if isinstance(a, LineBreak):
                if b and not isinstance(b, LineBreak):
                    bGlyphBounds = mergeSubPolys([b]).bounds
                    b.x = self.x
                    xloc = b.x - bGlyphBounds[0]
                else:
                    xloc = self.x

                yloc += metrics.capHeight() + a.leading

                allGlyphs += wordGlyphs
                wordGlyphs = []
                continue

            glyphBounds = mergeSubPolys([a]).bounds
            a.x = xloc
            a.y = yloc
            xShift = glyphBounds[2] - glyphBounds[0]

            if isinstance(b, Glyph):
                xShift += (kernGlyphs(a.char, b.char, a.weight(),
                                      capHeight=a.capHeight()) + a.tracking)

                if a.outlined:
                    xShift += (a.capHeight() / 15.0)

            xloc += xShift

            if isinstance(a, spaceGlyph):
                if len(wordGlyphs):
                    if xloc > self.width:
                        xloc = self.x
                        yloc += metrics.capHeight() + self.leading

                    allGlyphs += wordGlyphs
                    wordGlyphs = []
            else:
                wordGlyphs += [a]

        allGlyphs += wordGlyphs

        for g in allGlyphs:
            g.serifed = g.willBeSerifed

        return allGlyphs