コード例 #1
0
ファイル: StartGame.py プロジェクト: Vapekreng/SR_old
    def print(self, lighted=False):

        # Подсветка текущей позиции
        current_bgcolor = get_bgcolor(lighted)
        terminal.bkcolor(current_bgcolor)

        # Сначала левую часть
        x = 0
        y = self.height
        text = self.left_text
        terminal.printf(x, y, text)

        # Потом правую
        x = self.right_text_start_position
        y = self.height
        text = self.right_text
        terminal.printf(x, y, text)

        # Возвращаем подсветку, как было
        terminal.bkcolor(bgcolor)

        # Стираем старую подсказку и печатаем новую
        self.clear_hint()
        self.print_hint()

        # И обновляем экран
        terminal.refresh()
コード例 #2
0
ファイル: render_camera.py プロジェクト: Kavekha/NoGoNoMa
def render_entities_camera():
    start = time.perf_counter()

    current_map = World.fetch('current_map')
    min_x, max_x, min_y, max_y = get_screen_bounds()
    map_width = current_map.width
    map_height = current_map.height

    subjects = World.get_components(PositionComponent, RenderableComponent)
    for entity, (position, renderable) in subjects:
        hidden = World.get_entity_component(entity, HiddenComponent)
        idx = current_map.xy_idx(position.x, position.y)
        terminal.layer(renderable.render_order.value)
        if current_map.visible_tiles[idx] and not hidden:
            entity_screen_x = position.x - min_x
            entity_screen_y = position.y - min_y
            if 0 <= entity_screen_x <= map_width and 0 <= entity_screen_y <= map_height:
                if Interface.mode == GraphicalModes.ASCII:
                    terminal.printf(
                        entity_screen_x * Interface.zoom,
                        entity_screen_y * Interface.zoom,
                        f'[color={renderable.fg}]{renderable.glyph}[/color]')
                elif Interface.mode == GraphicalModes.TILES:
                    terminal.color(f'{renderable.fg}')
                    terminal.put(entity_screen_x * Interface.zoom,
                                 entity_screen_y * Interface.zoom,
                                 Interface.get_code(renderable.sprite))
                else:
                    print(
                        f'render camera: graphical mode {Interface.mode} not implemented.'
                    )
                    raise NotImplementedError

    delta_time = (time.perf_counter() - start) * 1000
    print(f'delta time: for render entities : {delta_time}')
コード例 #3
0
    def run(self):
        self.load()
        self.boot()

        thread_runner = Service.get('engine.thread_runner')
        thread_runner.start()

        # scene_graph = Service.get('engine.scene_graph')
        message_bus = Service.get('engine.message_bus')

        try:
            from bearlibterminal import terminal

            terminal.open()
            terminal.printf(2, 2, "Test!")
            terminal.refresh()

            event = terminal.read()
            while event != terminal.TK_CLOSE:
                message_bus.emit('term.event',
                                 event,
                                 source='engine.main_window')
                terminal.refresh()
                event = terminal.read()

            terminal.close()
        except:
            from traceback import print_exc

            print("=== Exception Occured ===")
            print_exc()
コード例 #4
0
    def draw_status(self):
        """Отображение состояния игрока."""
        nutration_max = int(self.nutrition // 10 + 1)
        hp_max = int(self.hp // 10 + 1)

        if hp_max > 10:
            hp_max = 10
        if nutration_max > 10:
            nutration_max = 10

        terminal.clear_area(2, 3, 10, 1)
        for x in range(hp_max):
            terminal.color(color["healf"])
            terminal.put(x + 2, 3, chars["block"])

        terminal.clear_area(2, 5, 10, 1)
        for x in range(nutration_max):
            terminal.color(color["nutrition"])
            terminal.put(x + 2, 5, chars["block"])

        terminal.color(color["white"])
        terminal.clear_area(1, 7, 14, 1)
        terminal.printf(
            1, 7, "Вес: " + str(self.inventory.sum_weight) + "/" +
            str(self.inventory.weight))

        terminal.color(color["white"])
コード例 #5
0
ファイル: render_functions.py プロジェクト: ostcrom/roguelike
def ui_print(terminal, x, y, h, w, text_string):

    terminal.layer(UI_LAYER)
    terminal.clear_area(dialog_pos_x, dialog_pos_y, dialog_width,
                        dialog_height)
    terminal.printf(dialog_pos_x, dialog_pos_y, ml.get_scroll_back())
    terminal.refresh()
コード例 #6
0
 def draw(self):
     """
     Draw the entity to the terminal
     """
     terminal.printf(x=self.x,
                     y=self.y,
                     s=f'[color={self.color}]{self.char}[/color]')
コード例 #7
0
ファイル: Map.py プロジェクト: Vapekreng/SR_old
def run_game():
    terminal.clear()
    TestMap = Maps()
    Hero = Mobs(19, 10, 0, '455', '@', 'human')
    # TODO: Перекинуть добавку моба в класс мобов
    TestMap.add_mob(Hero)
    aos = AreaOfSight.AoS(Hero, TestMap)
    TestMap.draw(aos.get())
    time = 0
    terminal.printf(0, 0, 'time=' + str(time))
    terminal.refresh()
    # TODO: Обработчик нажатий клавиш, мэйн луп, настройка клавиатуры через меню
    while True:
        key = terminal.read()
        while key not in Config.comand.values():
            key=terminal.read()
        if key == Config.comand['close'] or key == Config.comand['esc']:
            break
        time+=TestMap.move_mob(Hero, key)
        aos = AreaOfSight.AoS(Hero, TestMap)
        TestMap.draw(aos.get())
        terminal.printf(0, 0, 'time=' + str(time))
        terminal.refresh()
    terminal.clear()
    terminal.refresh()
コード例 #8
0
def print_agent(agent):
    """ Prints the given agent on the terminal window.

    Parameters
    ----------
    agent : Agent
        The agent to print to the terminal.
    """

    # Chooses colour based on agent state, e.g. running away

    if agent.run_away:
        colour = "#ff0000"
    elif agent.movement_mode == MoveModes.PATHFIND:
        colour = "#00ff00"
    else:
        colour = "#ffffff"

    for i in range(21):
        for j in range(21):
            if agent.body[j + i * 21] != ' ':
                if agent.body[j + i * 21] != '.':
                    terminal.printf(
                        agent.drawing_location[0] + j, agent.drawing_location[1] + i, "[color={}]{}[/color]".format(colour, agent.body[j + i * 21]))
    try:
        terminal.printf(agent.goal[0]-1, agent.goal[1], "[color={}]({})[color]".format(colour, agent.g_id))
    # TODO this should be changed to a less broad exception class, what exception are we expecting this to cause?
    except Exception:
        pass
コード例 #9
0
ファイル: enemy.py プロジェクト: dfryta/frederico
    def draw(self):
        # Draw enemy
        if self.world.is_currently_visible(self.position_x, self.position_y):
            if self.world.player.is_able_to_see(self.position_x,
                                                self.position_y):
                terminal.layer(vars.UNIT_LAYER)
                terminal.put(
                    self.world.calculate_draw_x_coordinate(self.position_x),
                    self.world.calculate_draw_y_coordinate(self.position_y),
                    0xE000 + self.image)
                terminal.layer(vars.EFFECTS_LAYER)
                if self.alerted:
                    terminal.put(
                        self.world.calculate_draw_x_coordinate(
                            self.position_x),
                        self.world.calculate_draw_y_coordinate(
                            self.position_y), 0xE000 + self.alert_image)

        if self.took_damage:
            terminal.layer(vars.EFFECTS_LAYER)
            terminal.put(
                self.world.calculate_draw_x_coordinate(self.position_x),
                self.world.calculate_draw_y_coordinate(self.position_y),
                0xE549)
            terminal.layer(vars.LABEL_ON_EFFECTS_LAYER)
            terminal.printf(
                self.world.calculate_draw_x_coordinate(self.position_x),
                self.world.calculate_draw_y_coordinate(self.position_y),
                "[color=crimson]{0}".format(self.took_damage))
            # Reset took damage meter
            self.took_damage = 0
コード例 #10
0
ファイル: render_camera.py プロジェクト: Kavekha/NoGoNoMa
def render_debug_map(gmap):
    player = World.fetch('player')
    player_pos = World.get_entity_component(player, PositionComponent)

    center_x = Interface.map_screen_width // 2
    center_y = Interface.map_screen_height // 2
    player_pos.x = center_x
    player_pos.y = center_y

    min_x, max_x, min_y, max_y = get_screen_bounds()

    map_width = gmap.width - 1
    map_height = gmap.height - 1

    y = 0
    for ty in range(min_y, max_y):
        x = 0
        for tx in range(min_x, max_x):
            if 0 <= tx <= map_width and 0 <= ty <= map_height:
                idx = gmap.xy_idx(tx, ty)
                if gmap.revealed_tiles[idx]:
                    glyph, sprite, char_color = get_tile_glyph(idx, gmap)
                    draw_tile(tx,
                              ty,
                              glyph,
                              sprite,
                              char_color,
                              render_order=Layers.MAP)
            elif config.SHOW_BOUNDARIES:
                if Interface.mode == GraphicalModes.ASCII or Interface.mode == GraphicalModes.TILES:
                    terminal.printf(x, y, f'[color=gray]-[/color]')
                else:
                    print(
                        f'render camera: graphical mode {Interface.mode} not implemented.'
                    )
                    raise NotImplementedError
            x += (1 * Interface.zoom)
        y += (1 * Interface.zoom)

    draw_tile(0, 0, 'X', 'map/wall1.png', 'pink', render_order=Layers.MAP)
    draw_tile(gmap.width - 1,
              0,
              'X',
              'map/wall1.png',
              'pink',
              render_order=Layers.MAP)
    draw_tile(0,
              gmap.height - 1,
              'X',
              'map/wall1.png',
              'pink',
              render_order=Layers.MAP)
    draw_tile(gmap.width - 1,
              gmap.height - 1,
              'X',
              'map/wall1.png',
              'pink',
              render_order=Layers.MAP)

    terminal.refresh()
コード例 #11
0
ファイル: game.py プロジェクト: ltouroumov/yarl
    def run(self):
        self.load()
        self.boot()

        thread_runner = Service.get('engine.thread_runner')
        thread_runner.start()

        # scene_graph = Service.get('engine.scene_graph')
        message_bus = Service.get('engine.message_bus')

        try:
            from bearlibterminal import terminal

            terminal.open()
            terminal.printf(2, 2, "Test!")
            terminal.refresh()

            event = terminal.read()
            while event != terminal.TK_CLOSE:
                message_bus.emit('term.event', event, source='engine.main_window')
                terminal.refresh()
                event = terminal.read()

            terminal.close()
        except:
            from traceback import print_exc

            print("=== Exception Occured ===")
            print_exc()
コード例 #12
0
def menu(header: str, options, width: int, screen_width: int,
         screen_height: int):
    if len(options) > 26:
        raise ValueError('Cannot have a menu with more than 26 options.')

    terminal.layer = 10

    _, header_height = terminal.measuref(header)
    height = len(options) + header_height

    x = int((screen_width / 2) - (width / 2))
    y = int((screen_height / 2) - (height / 2))

    letter_index = ord('a')

    terminal.printf(x, y, header)

    y += 1

    for option_text in options:
        text = f'({chr(letter_index)}) {option_text}'
        terminal.printf(x, y, text)

        y += 1
        letter_index += 1

    terminal.layer = 0
コード例 #13
0
def menu(
    camera_width: int, header: str, options: List[str], width: int, panel_y: int = None, camera: Camera = None
):
    if len(options) > 26:
        raise ValueError("Cannot have a menu with more than 26 options.")

    # Calculate total height for the header (after auto-wrap) and one line per option
    wrapped_header = textwrap.wrap(text=header, width=width * 2)
    height = len(options) + len(wrapped_header)
    if panel_y is None:
        panel_y = 2
    panel = Menu(
        position=Point(x=2, y=panel_y),
        width=camera_width * 2,
        height=height,
        header=wrapped_header,
        options=options,
    )

    if camera:
        camera.clear_view()

    for i, text_line in enumerate(panel.header):
        blt.printf(x=panel.x, y=panel.y + i * 2, s=f"{text_line}")

    letter_index = ord("a")
    for i, option_text in enumerate(options):
        text = f"({chr(letter_index + i)}) {option_text}"
        blt.puts(
            x=panel.x, y=panel.options_y + i * 2, s=f"{text}", align=blt.TK_ALIGN_LEFT
        )
コード例 #14
0
ファイル: menu_controls.py プロジェクト: Vapekreng/SR_old
 def _print_left_part(self, index):
     x0, y0 = _LEFT_COLUMN_START_POSITION
     x = x0
     y = y0 + index
     text = self.buttons[index]['comand']
     localized_text = localization.current_localization.translate(text)
     terminal.printf(x, y, localized_text)
コード例 #15
0
def render_bar(x, y, width, name, value, max_value, color_fg, color_bg,
               color_text):
    # Calculate current bar width.
    bar_width = int(float(value) / max_value * width)

    # Make sure there is always some bar showing even if value is super low.
    if bar_width < 1 and bar_width > 0:
        bar_width = 1

    # Draw background of the bar to the width given.
    terminal.color(terminal.color_from_argb(*color_bg))
    terminal.font('bar')
    for i in range(width):
        terminal.put(x + i, y, '▄')

    # Draw the foreground to the width calculated earlier.
    terminal.color(terminal.color_from_argb(*color_fg))
    for i in range(bar_width):
        terminal.put(x + i, y, '▄')

    # Draw text in the center of the bar.
    terminal.font('text')
    terminal.color(terminal.color_from_argb(*color_text))
    bar_text = name + ': %s/%s' % (value, max_value)
    center_x = int(x + (width / 2 - len(bar_text)))
    terminal.printf(center_x, y + 4, bar_text)

    # Reset font back to normal.
    terminal.font('main')
コード例 #16
0
def print_status(status_string=None, history=[]):
    """Пишет в статус.
    
    Статус тот который с боку.
    """
    if status_string is not None:
        status_string = status_string.capitalize()
        while len(status_string) > 12:
            # Дробилка
            # FIXME неправильно дробит строку, а именно через ж#@!
            status_string = status_string[::-1]
            history.append(status_string[12::-1])
            status_string = status_string[:12:-1]
        history.append(status_string)

    for hist in history:
        if len(hist) < 1:
            history.remove(hist)
    history.reverse()
    terminal.clear_area(65, 1, 13, 48)
    for i in range(48):
        try:
            terminal.printf(66, i + 1, history[i])
        except IndexError:
            break
    history.reverse()
コード例 #17
0
def render_bar(
    x: int,
    y: int,
    total_width: int,
    name: str,
    value: int,
    maximum: int,
    bar_color: Colors,
    back_color: Colors,
):
    bar_width = int(float(value) / maximum * total_width)

    blt.composition = True
    bk_color = blt.color_from_argb(*back_color.argb)
    bar_color = blt.color_from_argb(*bar_color.argb)
    bar_text = format(
        f"[font=bar_font][spacing=2x2]{name}: {value:02}/{maximum:02}[/font]",
        f"^{total_width}",
    )

    bar = " " * total_width
    blt.printf(x, y, s=f"[font=bar][bkcolor={bk_color}]{bar}")
    blt.printf(x, y, s=f"[font=bar][bkcolor={bar_color}]{bar[:bar_width]}")

    blt.puts(x=int(x + total_width / 2),
             y=y,
             s=bar_text,
             align=blt.TK_ALIGN_CENTER)
コード例 #18
0
def print_level(levels, level_n):
    """Отображает уровень."""
    level = levels[level_n].level
    start = levels[level_n].start
    end = levels[level_n].end

    dx, dy = 15, 0
    for y in range(50):
        for x in range(50):
            terminal.layer(0)
            if level[x][y].block:
                terminal.bkcolor(color["wall"])
                terminal.put(dx, dy, ' ')
            else:
                terminal.bkcolor(color["flor"])
                terminal.put(dx, dy, '.')

            terminal.layer(2)
            terminal.bkcolor(color["flor"])
            if len(level[x][y].item_on_me) > 0:
                for item in level[x][y].item_on_me:
                    terminal.put(dx, dy, item.char)
            dx += 1
        dx = 15
        dy += 1
    terminal.layer(1)
    terminal.bkcolor(color["flor"])
    terminal.printf(start.x1 + 15, start.y1, '>')
    terminal.printf(end.x1 + 15, end.y1, '<')
    terminal.layer(0)

    terminal.bkcolor(color["black"])
コード例 #19
0
def print_charset(point):
    terminal.printf(10, 10, "test")
    height = int(terminal_size[1])
    width = int(terminal_size[0])
    for y in range(0, height):
        for x in range(0, width):
            terminal.put(x, y, point)
            point += 1
コード例 #20
0
ファイル: menu_main.py プロジェクト: Vapekreng/SR_old
 def _print_button(self, position):
     text = self.button_names[position]
     x = self.init_coord_x
     y = self.init_coord_y + position
     if self.position == position:
         terminal.color(TERMINAL_COLOR_LIGHTED)
     terminal.printf(x, y, text)
     terminal.color(TERMINAL_COLOR_NORMAL)
コード例 #21
0
ファイル: button.py プロジェクト: JohnBCoding/Etheria-Python
    def draw(self):
        terminal.font('text')
        if not self.selected:
            terminal.color(terminal.color_from_argb(*self.color))
        else:
            terminal.color(terminal.color_from_argb(*self.selected_color))

        terminal.printf(self.x1, self.y1, self.text, terminal.TK_ALIGN_DEFAULT)
コード例 #22
0
ファイル: menu_controls.py プロジェクト: Vapekreng/SR_old
 def _print_right_part(self, index):
     x0, y0 = _RIGHT_COLUMN_START_POSITION
     x = x0
     y = y0 + index
     text = self.buttons[index]['key']
     localized_text = localization.current_localization.translate(text)
     normalized_text = localized_text.center(_RIGHT_COLUMN_WIDTH)
     terminal.printf(x, y, normalized_text)
コード例 #23
0
def draw_char(x, y, char, color, layer):
    old_layer = terminal.TK_LAYER
    old_color = terminal.TK_COLOR
    terminal.layer(layer)
    terminal.color(color)
    terminal.printf(x, y, char)
    terminal.color(old_color)
    terminal.layer(old_layer)
コード例 #24
0
ファイル: blt_engine.py プロジェクト: ostcrom/roguelike
def updateui():
    ##Switch to layer 4 to update UI

    terminal.layer(3)
    terminal.clear_area(dialog_pos_x, dialog_pos_y, dialog_width,
                        dialog_height)
    terminal.printf(dialog_pos_x, dialog_pos_y, ml.get_scroll_back())
    terminal.refresh()
コード例 #25
0
def draw_bar(x: int,
             y: int,
             value: int,
             max_value: int,
             color: int = 0xFFFFFFFF) -> None:
    terminal.color(color)
    terminal.printf(x, y, "=" * int(20 * value / max_value))
    terminal.color(0xFFFFFFFF)
コード例 #26
0
ファイル: menu_controls.py プロジェクト: Vapekreng/SR_old
 def _print_invite_to_change_key(self):
     x, y = _RIGHT_COLUMN_START_POSITION
     y = y + self.position
     text = _INVITE_TO_PRINT.center(_SCREEN_WIDTH // 2)
     terminal.color(_TERMINAL_COLOR_LIGHTED)
     terminal.printf(x, y, text)
     terminal.color(_TERMINAL_COLOR_NORMAL)
     terminal.refresh()
コード例 #27
0
def print_hud(player):
    """Отоброжает ХУД."""
    terminal.layer(0)
    terminal.printf(2, 0, player.name)
    terminal.printf(2, 2, "Здоровье:")
    terminal.printf(2, 4, "Питание:")
    terminal.printf(69, 0, "Статус:")
    terminal.printf(2, 49, "Глубина:")
コード例 #28
0
ファイル: StartGame.py プロジェクト: Vapekreng/SR_old
 def print(self, lighted=False):
     current_bgcolor = get_bgcolor(lighted)
     height = self.height
     text = self.normilized_text
     terminal.bkcolor(current_bgcolor)
     terminal.printf(start_position_x, height, text)
     terminal.bkcolor(bgcolor)
     terminal.refresh()
コード例 #29
0
def render_entities():
    # this function will render all entities that are renderable,
    # have a position, and have a glyph
    for ent in var.entities:
        if ent.renderable and ent.position and ent.glyph:
            for i in range(len(ent.position.position_array)):
                x, y = ent.position.position_array[i]
                g = ent.glyph.glyph_array[i]
                terminal.printf(x, y, g)
コード例 #30
0
ファイル: main_menu.py プロジェクト: Vapekreng/SR_old
 def _print_button(self, position):
     init_text = self.button_names[position]
     normilized_text = init_text.center(self.width)
     x = self.init_coord_x
     y = self.init_coord_y + position
     if self.position == position:
         terminal.bkcolor(BG_COLOR_LIGHTED)
     terminal.printf(x, y, normilized_text)
     terminal.bkcolor(BG_COLOR_NORMAL)
コード例 #31
0
ファイル: room_viewer.py プロジェクト: Vapekreng/SR
def view_aos(titles, title_map):
    for title in titles:
        x, y = title
        icon, color = title_map[x][y].get_icon()
        terminal.color(color)
        x0 = x + room_data.MAP_HORIZONTAL_START_POSITION
        y0 = y + room_data.MAP_VERTICAL_START_POSITION
        terminal.printf(x0, y0, icon)
    terminal.refresh()
コード例 #32
0
ファイル: terminal.py プロジェクト: ltouroumov/yarl
def main():
    terminal.open()
    terminal.set("window: title='Test!', size=80x25, cellsize=16x32;")
    terminal.set("input.filter=keyboard,mouse")
    terminal.set("font: res/font.png, size=12x24, codepage=437, align=top-left")
    terminal.set("0xE000: res/meph_32x32.png, size=32x32, align=top-left")
    terminal.set("0xE100: res/meph_trees.png, size=32x32, align=top-left")

    tx = 0
    ty = 4
    page = 0xE000

    draw_page(tx, ty, page)

    terminal.refresh()

    event = terminal.read()
    while event != terminal.TK_CLOSE:
        terminal.clear()

        if event == terminal.TK_MOUSE_MOVE:
            mx = terminal.state(terminal.TK_MOUSE_X)
            my = terminal.state(terminal.TK_MOUSE_Y)

            terminal.printf(15, 0, "mx: {}, my: {}", mx, my)

            if mx >= tx and my >= ty:
                tid = page + (mx - tx) // 2 + (my - ty) * 16
                terminal.printf(0, 3, "tile: {:04x}", tid)
            else:
                terminal.printf(0, 3, "tile: XXXX")
        elif event == terminal.TK_UP:
            page += 0x0100
        elif event == terminal.TK_DOWN:
            page -= 0x0100

        terminal.printf(0, 0, "event: {}", event)
        terminal.printf(0, 2, "page: {:x}", page)

        draw_page(tx, ty, page)

        terminal.refresh()
        event = terminal.read()

    terminal.close()
コード例 #33
0
ファイル: bearlib.py プロジェクト: joekane/DeepFriedSuperNova
def test_basic_output():
    blt.set("window.title='Omni: basic output'")
    blt.clear()
    blt.color("white")

    # Wide color range
    n = blt.print_(2, 1, "[color=orange]1.[/color] Wide color range: ")
    long_word = "antidisestablishmentarianism."
    long_word_length = len(long_word)
    for i in range(long_word_length):
        factor = i / long_word_length
        red = int((1 - factor) * 255)
        green = int(factor * 255)
        blt.color(blt.color_from_argb(255, red, green, 0))
        blt.put(2 + n + i, 1, long_word[i])

    blt.color("white")

    blt.print_(2, 3, "[color=orange]2.[/color] Backgrounds: [color=black][bkcolor=gray] grey [/bkcolor] [bkcolor=red] red ")

    blt.print_(2, 5, "[color=orange]3.[/color] Unicode support: Кириллица Ελληνικά α=β²±2°")

    blt.print_(2, 7, "[color=orange]4.[/color] Tile composition: @ + [color=red]|[/color] = @[+][color=red]|[/color], a vs. ¨ a[+][color=red]¨[/color]")

    blt.printf(2, 9, "[color=orange]5.[/color] Box drawing symbols:")

    blt.print_(5, 11,
        "   ┌────────┐  \n"
        "   │!......s└─┐\n"
        "┌──┘........s.│\n"
        "│............>│\n"
        "│...........┌─┘\n"
        "│<.@..┌─────┘  \n"
        "└─────┘  ■█┘╙       \n"
    )





    blt.refresh()
    key = None
    while key not in (blt.TK_CLOSE, blt.TK_ESCAPE):
        key = blt.read()