示例#1
0
    def fill(self, color, rect=None, special_flags=0):
        """..."""
        sfc = self.surface
        fmt = sfc.format.contents
        color = Color(*color)
        pixel = sdl2.SDL_MapRGBA(fmt, color.r, color.g, color.b, color.a)

        if rect is not None:
            sdl_rect = to_sdl_rect(rect)

            if sdl_rect.x < 0:
                sdl_rect.w = sdl_rect.w + sdl_rect.x
                sdl_rect.x = 0

            if sdl_rect.y < 0:
                sdl_rect.w = sdl_rect.h + sdl_rect.y
                sdl_rect.y = 0

            if sdl_rect.w <= 0 or sdl_rect.h <= 0:
                return Rect(0, 0, 0, 0)

            err = sdl2.SDL_FillRect(self.surface, sdl_rect, pixel)

            if err:
                raise sdl2.SDLError()

            return Rect(sdl_rect.x, sdl_rect.y, sdl_rect.w, sdl_rect.h)

        else:
            err = sdl2.SDL_FillRect(self.surface, None, pixel)

            if err:
                raise sdl2.SDLError()

            return Rect(0, 0, self.w, self.h)
示例#2
0
    def get_rect(self, **kwargs):
        """Get the rectangular area of the sprite.

        Returns a new rectangle covering the sprite area. This rectangle will
        have the sprite's x, y, width and height.

        You can pass keyword argument values to this function. These named
        values will be applied to the attributes of the Rect before it is
        returned. An example would be ‘mysurf.get_rect(center=(100,100))’
        to create a rectangle for the Surface centered at a given position.

        Usage:
            get_rect()

        Returns:
            Rect
        """
        frame_rect = self.frame_rect
        if frame_rect is not None:
            r = Rect(*[getattr(frame_rect, v) for v in ("x", "y", "w", "h")])
        else:
            r = Rect(self.position, self.size)
        for k, v in kwargs.items():
            setattr(r, k, v)
        return r
    def __init__(self, **kwargs):
        """..."""
        super().__init__(**kwargs)
        from_g = self.manager.factory.from_gradient
        from_c = self.manager.factory.from_color

        self.sprites = [
            from_g(rect=Rect(64, 64, 200, 200),
                   mode="h",
                   color_end=(255, 0, 0, 31),
                   color_start=(255, 255, 255, 127)),
            from_g(rect=Rect(214, 64, 200, 200),
                   mode="v",
                   color_end=(0, 255, 0, 31),
                   color_start=(255, 255, 255, 127)),
            from_g(rect=Rect(214, 214, 200, 200),
                   mode="h",
                   color_end=(255, 255, 255, 127),
                   color_start=(0, 0, 255, 31)),
            from_g(rect=Rect(64, 214, 200, 200),
                   mode="v",
                   color_end=(255, 255, 255, 127),
                   color_start=(255, 255, 0, 31)),
            from_c(rect=Rect(0, 0, 128, 128), color=(0, 0, 127, 127)),
            from_c(rect=Rect(350, 0, 128, 128), color=(127, 127, 0, 127)),
            from_c(rect=Rect(350, 350, 128, 128), color=(127, 0, 0, 127)),
            from_c(rect=Rect(0, 350, 128, 128), color=(0, 127, 0, 127))
        ]
    def __init__(self, **kwargs):
        """..."""
        super().__init__(**kwargs)
        from_color = self.manager.factory.from_color

        self.sprites = []
        self.sprites.append(
            from_color(rect=Rect(150, 150, 200, 200),
                       color=(255, 255, 255, 127)))
        self.sprites.append(
            from_color(rect=Rect(0, 0, 200, 200), color=(255, 0, 0, 127)))
        self.sprites.append(
            from_color(rect=Rect(0, 150, 200, 200), color=(0, 255, 0, 127)))
        self.sprites.append(
            from_color(rect=Rect(150, 0, 200, 200), color=(0, 0, 255, 127)))
示例#5
0
    def __init__(self, **kwargs):
        """..."""
        super().__init__(**kwargs)
        from_color = self.manager.factory.from_color

        colors = [(255, 0, 0, 0), (0, 0, 255, 0), (0, 0, 255, 0)]

        rect_a = Rect(10, 10, 100, 100)
        rect_b = Rect(400, 400, 100, 100)
        rect_c = rect_a.gap(rect_b)

        self.sprites = {
            from_color(color=c, rect=r)
            for c, r in zip(colors, [rect_a, rect_b, rect_c])
        }
示例#6
0
def rectangle(surface, rect, color, sdlgfx=None):
    """Draw rectangle with blending.

    Args:
        surface (SDL_RENDERER, SDL_TEXTURE): The renderer or texture (created
        with the SDL_TEXTUREACCESS_TARGET flag) to draw on.
        x1 (int): X coordinate of the first point (i.e. top right) of the
        rectangle.
        y1 (int): Y coordinate of the first point (i.e. top right) of the
        rectangle.
        x2 (int): X coordinate of the second point (i.e. bottom left) of the
        rectangle.
        y2 (int): Y coordinate of the second point (i.e. bottom left) of the
        rectangle.
        color (Color or 4-tuple with ints between 0-255): RGBA color

    Raises:
        SDLError
    """
    sdlgfx = sdlgfx_tex if (sdlgfx is None or sdlgfx == "tex") else sdlgfx_sfc
    c = Color(*color)
    if not isinstance(rect, Rect):
        rect = Rect(rect)
    if sdlgfx.rectangleRGBA(surface, rect.x, rect.y, rect.x + rect.w,
                            rect.y + rect.h, c.r, c.g, c.b, c.a):
        raise SDLError("sdlgfx.rectangleRGBA failure")
示例#7
0
    def __init__(self, **kwargs):
        """..."""
        super().__init__(**kwargs)
        w = 128
        h = 64
        rect = Rect(0, 0, w, h)
        sdlrenderer = self.manager.renderer.sdlrenderer
        factory = self.manager.factory
        #     def from_color(self, *, rect, color, bpp=32, masks=None):

        self.sprite = factory.from_new_texture(w, h)
        texture = self.sprite.texture

        with factory.new_render_target(texture):
            gfxdraw.rounded_box(sdlrenderer, rect, 15, (255, 0, 0, 255))
            gfxdraw.pixel(sdlrenderer, 8, 8, (255, 255, 255, 255))
            gfxdraw.filled_polygon(sdlrenderer,
                                   color=(255, 255, 255, 255),
                                   points=(rect.midtop, rect.midright,
                                           rect.midbottom, rect.midleft))
            gfxdraw.bezier(sdlrenderer,
                           color=(0, 0, 255, 255),
                           steps=5,
                           points=(rect.midtop, rect.midright, rect.midbottom))

            gfxdraw.thick_line(sdlrenderer, *rect.bottomleft, *rect.topright,
                               5, (0, 255, 0, 127))
示例#8
0
    def create_buttons(self):
        """Create the button sprites."""
        sdlrenderer = self.sdlrenderer
        new_render_target = self.factory.new_render_target
        from_new_texture = self.factory.from_new_texture

        rad = self.radius
        size = self.size
        rect = Rect(0, 0, *size)
        color = self.regular_color

        # e.g. regular_color, regular_color_mod
        for state in self.states:
            sprite = from_new_texture(*size)
            sprite_color = getattr(self, "%s_color" % state) or color
            color_mod = getattr(self, "%s_color_mod" % state)
            alpha_mod = getattr(self, "%s_alpha_mod" % state)
            with new_render_target(sprite.texture):
                gfxdraw.rounded_box(sdlrenderer, rect, rad, sprite_color)
            sprite.set_color_mod(color_mod)
            sprite.set_alpha_mod(alpha_mod)

            sprite.position = self.topleft

            self.sprites[state] = [sprite]
示例#9
0
    def create_map(self):
        """..."""
        from_tileset = self.manager.factory.from_tileset
        size = self.tile_size

        cols = self.width // size
        rows = self.height // size

        for c in range(cols):
            for r in range(rows):
                pos = var = 1
                if r == 0:
                    var = 0
                elif r == rows - 1:
                    var = 2
                if c == 0:
                    pos = 0
                elif c == cols - 1:
                    pos = 2

                sprite = from_tileset(tile="ui_window",
                                      pos=pos,
                                      var=var,
                                      rect=Rect(c * size + self.x,
                                                r * size + self.y, size, size))
                self.tiles.add(sprite)
示例#10
0
 def change_feature(self, *, pos=None, template=None):
     """..."""
     if pos:
         self._rect = Rect((pos), (TILE_W, TILE_H))
     if template:
         self.name = template
         self.set_template(template)
示例#11
0
 def __init__(self, **kwargs):
     """..."""
     super().__init__(**kwargs)
     from_gradient = self.manager.factory.from_gradient
     self.sprite = from_gradient(color_start=(10, 36, 106, 0),
                                 color_end=(166, 202, 240, 0),
                                 rect=Rect(0, 0, 320, 240),
                                 mode="v")
示例#12
0
 def create_layers(self):
     """..."""
     nav_rect = Rect(
         0,  # left
         0,  # top
         self.width,  # width
         self.height // 4)  # height
     self.nav_layer = LayerNavigator(parent=self, rect=nav_rect)
     self.insert_layer(self.nav_layer)
     # print(nav_rect.bottom)
     desc_rect = Rect(
         0,  # left
         nav_rect.bottom,  # top
         self.width,  # width
         self.height - nav_rect.height)  # height
     self.desc_layer = LayerDescription(parent=self, rect=desc_rect)
     self.insert_layer(self.desc_layer)
示例#13
0
 def fog(self):
     """..."""
     if not self._fog_cache:
         self._fog_cache = self.parent.manager.factory.from_color(
             color=(0, 63, 7, 191),
             rect=Rect((0, 0),
                       (self.parent.tile_width, self.parent.tile_height)))
     return self._fog_cache
示例#14
0
    def __init__(self, **kwargs):
        """..."""
        super().__init__(**kwargs)
        rect = Rect(50, 50, 200, 50)
        color = (255, 0, 0, 255)
        surface = self.factory.create_surface(rect.w, rect.h)
        gfxdraw.hlineRGBA(surface, 0, 50, 25, color, sdlgfx="sfc")

        self.sprite = self.factory.from_surface(surface)
示例#15
0
    def create_layers(self):
        """..."""
        bg = Layer(parent=self)
        bg.create_gradient_surface(color_start=(0, 0, 0, 0),
                                   color_end=(0, 31, 0, 0),
                                   mode="h")
        stats_rect = Rect(
            0,  # left
            0,  # top
            int(self.width * 0.30),  # width
            self.height)  # height

        desc_rect = Rect(
            stats_rect.right,  # left
            0,  # top
            self.width - stats_rect.width,  # width
            self.height)  # height
        self.desc_layer = Description(parent=self, rect=desc_rect)
        self.stats_layer = Stats(parent=self, rect=stats_rect)
        self.insert_layer(bg, self.desc_layer, self.stats_layer)
示例#16
0
    def set_gap(self):
        """..."""
        menu_layer = self.parent.menu_layer

        header_rect = menu_layer.head_title_obj
        items_rect = menu_layer.body_rect
        x = min(header_rect.x, items_rect.x)
        y = header_rect.bottom + 1
        w = max(header_rect.right, items_rect.right) - x
        h = items_rect.y - 1 - y
        self.gap = Rect(x, y, w, h)
        self.wait = time.get_time()
示例#17
0
 def __init__(self, **kwargs):
     """..."""
     super().__init__(**kwargs)
     frame = base_layers.Layer(parent=self)
     frame.create_gradient_surface()
     gui = gui_layer.GUILayer(parent=self)
     rect = Rect(0, 0, 150, 30)
     rect.bottomright = (self.width, self.height)
     gui.create_textbox(rect=rect,
                        command=print_on_enter,
                        disable_on_execute=False)
     self.insert_layer(frame, gui)
示例#18
0
    def __init__(self,
                 *,
                 text,
                 rect,
                 fonts,
                 manager,
                 font_path='.',
                 style=None):
        """Initialization.

        Args:
            text: the text that will be rendered;
            font_path: location that will be searched for the required fonts;
            style: a default style to be used;
            rect: a Rect object (pass in a subarea if you don't want
            to use all of the screen when rendering).
        """
        if isinstance(text, bytes):
            self.text = text.decode('utf-8')
        elif isinstance(text, str):
            self.text = text

        self.fonts = fonts
        self.manager = manager

        Style.set_default(style)

        self.screen_rect = Rect(rect)

        self.anchor_x = self.screen_rect.x
        self.anchor_y = self.screen_rect.y

        # print('parsing text')
        self.parse_text()
        # print('done parsing')
        # print('rendering surfaces')
        self.render_surfaces()
        # print('done rendering surfaces')

        return

        self.print_stats()
        # self.screenshot('sftext.png')
        _y = None
        for p in self.parsed:
            if p['rect'].y == _y:
                print(p, end="")
            else:
                print()
                print(p, end="")
                _y = p['rect'].y
示例#19
0
    def __init__(self, parent, name, alpha=90):
        """..."""
        self.max_width = 160
        super().__init__(parent=parent, rect=Rect(16, 16, self.max_width, 26))

        self.color_table = LBPercentTable(
            default_to_first=True,
            table=(
                (0, (223, 0, 0, 192)),  # red
                (25, (*get_color("yellow")[:3], 176)),
                (50, (*get_color("lime")[:3], 160)),
                (75, (*get_color("green")[:3], 144))))
        self.previous_value = None
        self.previous_max = None
示例#20
0
 def __init__(self, *, name, scene, pos, **kwargs):
     """..."""
     [
         setattr(v, 'owner', self) for v in kwargs.values()
         if hasattr(v, 'owner')
     ]
     self.name = name
     self.set_template(name)
     self.__dict__.update(kwargs)
     self._rect = Rect(pos, (TILE_W, TILE_H))
     self.scene = scene
     self.default_ai = self.ai
     self.default_color = self.color
     if self.scene:
         self.scene.add_obj(obj=self, pos=pos)
示例#21
0
    def blit(self, source, dest, area=None, special_flags=0):
        """..."""
        sdl2.SDL_SetSurfaceBlendMode(source.surface, sdl2.SDL_BLENDMODE_BLEND)

        dest_rect = to_sdl_rect(dest)

        area_rect = to_sdl_rect(area) if area is not None else None

        err = sdl2.SDL_BlitSurface(source.surface, area_rect, self.surface,
                                   dest_rect)
        if err:
            raise sdl2.SDLError()

        dirty = Rect(dest[0], dest[1], source.w, source.h)
        return dirty.clip(self.get_rect())
    def __init__(self, **kwargs):
        """..."""
        super().__init__(**kwargs)
        w = 256
        h = 128
        rect = Rect(0, 0, w, h)
        sdlrenderer = self.manager.renderer.sdlrenderer
        factory = self.manager.factory

        button = factory.from_new_texture(w, h)
        button_tex = button.texture
        with factory.new_render_target(button_tex):
            draw_button(sdlrenderer, rect, 16, (95, 95, 95, 255))
        button.move(8, 8)

        self.create_gradient_surface()
        self.sprite = button
示例#23
0
 def on_update(self):
     """..."""
     _map = self.map_gen.map
     font_render = self.font.render
     batch = [font_render(chr(tile.id),
                          color=tile.color,
                          rect=Rect((4 + self.w * x, y * self.h), (0, 0)))
              for (x, y), tile_group in _map.items()
              for tile in tile_group.get_all()
              if tile]
     self.manager.spriterenderer.render(sprites=batch)
     return
     for (x, y), tile_group in _map.items():
         for tile in tile_group.get_all():
             if not tile:
                 continue
             char = chr(tile.id)
             color = tile.color
             img = self.font.render(char, True, color)
             self.screen.blit(img, (4 + self.w * x, y * self.h))
示例#24
0
    def render_sprites(self):
        """..."""
        def position(i):
            return (4, i * self.font_h + 4)

        def valid(pos):
            x, y = pos
            scr_w, scr_h = self.width, self.height
            return x < scr_w and y < scr_h

        if self.sprites and self.previous_text == self.text:
            return
        text = self.get_text()
        render = self.font.render

        self.sprites = [render(t, rect=Rect(position(i), (0, 0)))
                        for i, t in enumerate(text)
                        if t and valid(position(i))]

        self.previous_text = self.text
示例#25
0
def box(surface, rect, color, sdlgfx=None):
    """Draw a filled rectangle with blending.

    Args:
        surface (SDL_RENDERER, SDL_TEXTURE): The renderer or texture (created
        with the SDL_TEXTUREACCESS_TARGET flag) to draw on.
        rect (Rect): A rectangle representing the area to be draw.
        rad (int): The radius of the corner arc.
        color (Color or 4-tuple with ints between 0-255): RGBA color

    Raises:
        SDLError
    """
    sdlgfx = sdlgfx_tex if (sdlgfx is None or sdlgfx == "tex") else sdlgfx_sfc
    c = Color(*color)
    if not isinstance(rect, Rect):
        rect = Rect(rect)
    if sdlgfx.boxRGBA(surface, rect.x, rect.y, rect.x + rect.w,
                      rect.y + rect.h, c.r, c.g, c.b, c.a):
        raise SDLError("sdlgfx.boxRGBA failure")
示例#26
0
def rounded_rectangle(surface, rect, rad, color, sdlgfx=None):
    """Draw rounded-corner rectangle with blending.

    Args:
        surface (SDL_RENDERER, SDL_TEXTURE): The renderer or texture (created
        with the SDL_TEXTUREACCESS_TARGET flag) to draw on.
        rect (Rect): A rectangle representing the area to be draw.
        rad (int): The radius of the corner arc.
        color (Color or 4-tuple with ints between 0-255): RGBA color

    Raises:
        SDLError
    """
    sdlgfx = sdlgfx_tex if (sdlgfx is None or sdlgfx == "tex") else sdlgfx_sfc
    c = Color(*color)
    if not isinstance(rect, Rect):
        rect = Rect(rect)
    if sdlgfx.roundedRectangleRGBA(surface, rect.right - 1, rect.top + 1,
                                   rect.left + 1, rect.bottom - 1, rad, c.r,
                                   c.g, c.b, c.a):
        raise SDLError("sdlgfx.rectangleRGBA failure")
示例#27
0
    def __init__(self, **kwargs):
        """..."""
        super().__init__(**kwargs)
        fonts = self.manager.fonts
        font_name = "caladea-regular.ttf"
        text_color = (255, 31, 63)
        size = 16
        string = "Lorem Ipsum"

        self.text = fonts.render(string, font_name, size, text_color)
        pos = self.text.position
        self.text.position = pos[0] + 8, pos[1] + 8
        w, h = fonts.text_size(string, font_name, size)

        self.text2 = fonts.render(string, font_name, 24, text_color)
        pos = self.text2.position
        self.text.position = pos[0] + w * 2, pos[1] + h * 2

        bg_color = (63, 0, 127)
        bg_sprite = self.factory.from_color(color=bg_color,
                                            rect=Rect(0, 0, w + 16, h + 16))
        self.bg_sprite = bg_sprite
示例#28
0
    def list(self):
        """..."""
        current_key = self.keys[self.current_key_index]
        current_item = self.current_level[current_key]

        document = ("{style}\\" * 2)
        for i in range(len(self.abs_position)):
            level = self.abs_position[i].capitalize()
            if i > 0:
                document += "\\"
            document += level

        str_keys = []
        for i, key in enumerate(self.keys):

            if isinstance(self.current_level[key], dict):
                s = "[{}]".format(key.capitalize())
            else:
                s = key.capitalize()

            if key == current_key:
                s = "{style}{underline True}" + YELLOW + s.upper() + "{style}"

            str_keys.append(s)

        document += "\n[ {} ]".format(", ".join(s for s in str_keys))

        self.create_text(document)

        if isinstance(current_item, dict):
            self.parent.desc_layer.content = self.db['Help']
        else:
            self.parent.desc_layer.content = current_item
        # self.height = self.sftext.sum_height()
        # self.y = 0
        header_rect = Rect(self)
        header_rect.y = 0
        header_rect.height = self.sftext.sum_height()
        self.parent.desc_layer.create_text(header_rect=header_rect)
示例#29
0
    def create_main(self):
        """..."""
        factory = self.manager.factory
        head_rect = self.head_rect
        main_font = self.main_font

        w = head_rect.width
        h = int(self.h * 0.7) - head_rect.height - 16

        x = head_rect.x
        y = head_rect.bottom + 8

        main_rect = Rect(x, y, w, h)
        self.main_surface = factory.from_gradient(rect=main_rect)

        main_font_w, main_font_h = main_font.get_size("healing potion potion")
        main_item_h = int(main_font_h * 1.2)
        main_item_w = int(main_font_w * 1.1)
        self.rows = main_rect.height // (main_item_h + 1)
        self.cols = main_rect.width // main_item_w

        total_width = main_item_w * self.cols
        self.tab_x = int(main_rect.width - total_width)
示例#30
0
    def create_head(self):
        """..."""
        factory = self.manager.factory
        head_font = self.head_font

        h = self.head_font.height * 2
        w = int(self.w * 0.9)
        x, y = int(self.w * 0.05), int(self.h * 0.05)

        head_rect = head_rect = Rect(x, y, w, h)
        self.head_surface = factory.from_gradient(rect=head_rect)

        head_title_sfc = head_font.render("< Inventory >")
        head_title_obj = head_title_sfc.get_rect()
        head_title_obj.center = head_rect.center
        head_title_sfc.set_rect(head_title_obj)

        head_title_shadow_sfc = head_font.render("< Inventory >",
                                                 color=get_color("black"))
        head_title_shadow_sfc.set_rect(head_title_obj.move(2, 2))

        self.head_rect = head_rect
        self.head_title_sfc = head_title_sfc
        self.head_title_shadow_sfc = head_title_shadow_sfc