Beispiel #1
0
    def __init__(self, pageList):
        self._group = displayio.Group(max_size=99)

        #Our button collection
        self.buttons = []
        self.pageList = pageList

        btnUpper = Button(x=0,
                          y=0,
                          width=240,
                          height=40,
                          style=Button.ROUNDRECT,
                          outline_color=0xdddddd,
                          fill_color=None,
                          label_color=0xdddddd,
                          label_font=terminalio.FONT,
                          label="TOP",
                          selected_fill=0xdddddd)
        self.buttons.append(btnUpper)
        self._group.append(btnUpper)

        btnMid = Button(x=0,
                        y=40,
                        width=240,
                        height=50,
                        style=Button.ROUNDRECT,
                        outline_color=0xdddddd,
                        fill_color=None,
                        label_color=0xdddddd,
                        label_font=terminalio.FONT,
                        label="MID",
                        selected_fill=0xdddddd)
        btnMid.selected = True
        self.buttons.append(btnMid)
        self._group.append(btnMid)

        btnLow = Button(x=0,
                        y=90,
                        width=240,
                        height=40,
                        style=Button.ROUNDRECT,
                        outline_color=0xdddddd,
                        fill_color=None,
                        label_color=0xdddddd,
                        label_font=terminalio.FONT,
                        label="LOW",
                        selected_fill=0xdddddd)
        self.buttons.append(btnLow)
        self._group.append(btnLow)
Beispiel #2
0
def create_buttons(width=320, height=40, offset=10):
    """
    Based on code from:
        https://learn.adafruit.com/pyportal-neopixel-color-oicker
    """
    buttons = []

    x = offset
    y = offset + int(height * 1.5)

    for text_label, color in color_labels.items():
        button = Button(
            x=x,
            y=y,
            width=width,
            height=height,
            style=Button.SHADOWROUNDRECT,
            fill_color=color,
            outline_color=0x222222,
            name=text_label,
            label=text_label,
            label_font=arial_font,
            label_color=0xFFFFFF,
        )
        buttons.append(button)
        y += 40
    return buttons
def create_buttons(size=60, offset=10):
    """Create buttons based on colors and positions

    Based on code from:
        https://learn.adafruit.com/pyportal-neopixel-color-oicker
    """
    color_labels = [
        ("red", (255, 0, 0)),
        ("yellow", (255, 170, 0)),
        ("green", (0, 255, 0)),
    ]

    buttons = []
    x = offset
    y = offset

    for label, color in color_labels:
        button = Button(x=x,
                        y=y,
                        width=size,
                        height=size,
                        style=Button.SHADOWROUNDRECT,
                        fill_color=color,
                        outline_color=0x222222,
                        name=label)
        buttons.append(button)
        x += 80
    return buttons
Beispiel #4
0
    def _create_button(self, label):
        """Create a button instance with automatic calculation of the
        correct position and the button size.

        Arguments:
            label {string} -- Button label (can contain \n)

        Returns:
            adafruit_button.Button -- Button instance
        """
        button_x = (
            len(self.buttons) * self.button_width + ButtonController.BUTTON_PADDING
        )

        return Button(
            x=button_x,
            y=self.button_y,
            width=self.button_width - 2 * ButtonController.BUTTON_PADDING,
            height=self.button_height - 2 * ButtonController.BUTTON_PADDING,
            label=label,
            label_font=self.font,
            label_color=0xD7C6E0,
            fill_color=0x601D83,
            selected_fill=0xD7C6E0,
            selected_label=0x601D83,
            style=Button.ROUNDRECT,
        )
    def __init__(self, *menu_items):
        self.menu_items = menu_items
        self.current_index = 0
        self.buttons = []

        self.menu_group = displayio.Group(max_size=len(self.menu_items) + 1)

        display_height = 120
        step = int(display_height / (len(self.menu_items) + 1))

        title = Button(
            x=1,
            y=0,
            width=159,
            height=step,
            label_color=0xFFFFFF,
            fill_color=0x000,
            label="Microsoft PyBadge v1.0",
            label_font=terminalio.FONT,
        )
        self.menu_group.append(title.group)

        for index, menu_item in enumerate(self.menu_items, start=1):
            button = Button(
                style=Button.ROUNDRECT,
                x=1,
                y=index * step,
                width=159,
                height=step,
                label_color=0xFFFF,
                outline_color=0x767676,
                fill_color=0x5C5B5C,
                selected_fill=0x5A5A5A,
                selected_outline=0xFF00FF,
                selected_label=0xFFFF00,
                label=menu_item.label,
                label_font=terminalio.FONT,
            )
            if index - 1 == self.current_index:
                button.selected = True
            self.menu_group.append(button.group)
            self.buttons.append(button)
Beispiel #6
0
 def _makeButton(self, x, y, text, width=None, height=None):
     button = Button(x=x,
                     y=y,
                     width=self._key_width if width is None else width,
                     height=self._key_width if height is None else height,
                     label=text,
                     label_font=self._keycap_font,
                     label_color=self._keycap_fg,
                     fill_color=self._keycap_bg,
                     style=Button.ROUNDRECT)
     return button
def add_button(row, col, label, width=1, color=WHITE, text_color=BLACK):
    pos = button_grid(row, col)
    new_button = Button(x=pos.x,
                        y=pos.y,
                        width=BUTTON_WIDTH * width + BUTTON_MARGIN *
                        (width - 1),
                        height=BUTTON_HEIGHT,
                        label=label,
                        label_font=font,
                        label_color=text_color,
                        fill_color=color,
                        style=Button.ROUNDRECT)
    buttons.append(new_button)
    return new_button
Beispiel #8
0
 def addButton(self, x, y, w, h, label, callback, **kwargs):
     btn = Button(x=x,
                  y=y,
                  width=w,
                  height=h,
                  label=label,
                  label_font=font,
                  selected_fill=0x008800)
     self.buttons.append({
         "button": btn,
         "callback": callback,
         "enabled": False
     })
     for b in self.buttons:
         bt = b["button"]
         bid = id(bt)
     return btn
Beispiel #9
0
def create_back_button():
    back_button = Button(
        x=10,
        y=200,
        width=80,
        height=40,
        style=Button.SHADOWROUNDRECT,
        fill_color=(0, 0, 0),
        outline_color=0x222222,
        name="back",
        label="back",
        label_font=arial_font,
        label_color=0xFFFFFF,
    )

    buttons.append(back_button)
    back_button_group.append(back_button.group)
    pyportal.splash.append(back_button_group)
    back_button_group.hidden = True
 def _add_button_by_pixels(self,
                           x,
                           y,
                           label,
                           width=1,
                           height=1,
                           color=myconstants.WHITE,
                           text_color=myconstants.BLACK):
     new_button = Button(
         x=x,
         y=y,
         width=BUTTON_WIDTH * width + BUTTON_MARGIN * (width - 1),
         height=BUTTON_HEIGHT * height + BUTTON_MARGIN * (height - 1),
         label=label,
         label_font=self._font,
         label_color=text_color,
         fill_color=color,
         style=Button.ROUNDRECT)
     self._buttons.append(new_button)
     return new_button
 def add_button(self,
                row,
                col,
                label,
                width=1,
                color=LIGHT_GRAY,
                text_color=BLACK):
     pos = self.button_grid(row, col)
     new_button = Button(x=pos.x,
                         y=pos.y,
                         width=self.BUTTON_WIDTH * width +
                         self.BUTTON_MARGIN * (width - 1),
                         height=self.BUTTON_HEIGHT,
                         label=label,
                         label_font=font,
                         label_color=text_color,
                         fill_color=color,
                         style=Button.SHADOWRECT)
     self.buttons.append(new_button)
     return new_button
Beispiel #12
0
    def load_game(self, game_directory):
        """Load a game.

        :param game_directory: where the game files are stored
        """
        self._gamedirectory = game_directory
        self._text_font = terminalio.FONT
        # Button Attributes
        btn_left = 10
        btn_right = btn_left + 180
        btn_mid = btn_left + 90
        button_y = 195
        button_width = 120
        button_height = 40
        if board.DISPLAY.height < 200:
            button_y /= 2
            button_y += 10
            button_width /= 2
            button_height /= 2
            btn_right /= 2
            btn_mid /= 2
        self._left_button = Button(x=int(btn_left),
                                   y=int(button_y),
                                   width=int(button_width),
                                   height=int(button_height),
                                   label="Left",
                                   label_font=self._text_font,
                                   style=Button.SHADOWROUNDRECT)
        self._right_button = Button(x=int(btn_right),
                                    y=int(button_y),
                                    width=int(button_width),
                                    height=int(button_height),
                                    label="Right",
                                    label_font=self._text_font,
                                    style=Button.SHADOWROUNDRECT)
        self._middle_button = Button(x=int(btn_mid),
                                     y=int(button_y),
                                     width=int(button_width),
                                     height=int(button_height),
                                     label="Middle",
                                     label_font=self._text_font,
                                     style=Button.SHADOWROUNDRECT)
        self._gamefilename = game_directory + "/cyoa.json"
        try:
            game_file = open(self._gamefilename, "r")
        except OSError:
            raise OSError("Could not open game file " + self._gamefilename)
        self._game = json.load(game_file)
        game_file.close()
    def load_game(self, game_directory):
        """Load a game.

        :param game_directory: where the game files are stored

        """
        self._gamedirectory = game_directory

        self._text_font = bitmap_font.load_font(game_directory +
                                                "/fonts/Arial-Bold-12.bdf")
        #self._text_font = fontio.BuiltinFont
        try:
            glyphs = b'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-!,. "\'?!'
            print("Preloading font glyphs:", glyphs)
            self._text_font.load_glyphs(glyphs)
        except AttributeError:
            pass  # normal for built in font

        self._left_button = Button(x=10,
                                   y=195,
                                   width=120,
                                   height=40,
                                   label="Left",
                                   label_font=self._text_font,
                                   style=Button.SHADOWROUNDRECT)
        self._right_button = Button(x=190,
                                    y=195,
                                    width=120,
                                    height=40,
                                    label="Right",
                                    label_font=self._text_font,
                                    style=Button.SHADOWROUNDRECT)
        self._middle_button = Button(x=100,
                                     y=195,
                                     width=120,
                                     height=40,
                                     label="Middle",
                                     label_font=self._text_font,
                                     style=Button.SHADOWROUNDRECT)

        self._gamefilename = game_directory + "/cyoa.json"
        try:
            game_file = open(self._gamefilename, "r")
        except OSError:
            raise OSError("Could not open game file " + self._gamefilename)
        self._game = json.load(game_file)
        game_file.close()
Beispiel #14
0
def add_button(row,
               col,
               label,
               width=1,
               color=ORANGE,
               text_color=WHITE,
               border_color=ORANGE,
               fill=LIGHT_ORANGE):
    pos = button_grid(row, col)
    new_button = Button(x=pos.x,
                        y=pos.y,
                        width=BUTTON_WIDTH * width + BUTTON_MARGIN *
                        (width - 1),
                        height=BUTTON_HEIGHT,
                        outline_color=border_color,
                        label=label,
                        label_font=font,
                        label_color=text_color,
                        selected_fill=fill,
                        fill_color=color,
                        style=Button.RECT)
    buttons.append(new_button)
    return new_button
Beispiel #15
0
}, {
    'name': 'blue',
    'pos': (155, 155),
    'color': button_colors['blue']
}, {
    'name': 'purple',
    'pos': (225, 155),
    'color': button_colors['purple']
}]

# generate color buttons from color_btn list
for i in color_btn:
    button = Button(x=i['pos'][0],
                    y=i['pos'][1],
                    width=BUTTON_WIDTH,
                    height=BUTTON_HEIGHT,
                    name=i['name'],
                    fill_color=i['color'],
                    style=Button.ROUNDRECT)
    buttons.append(button)

# light property buttons and their properties
prop_btn = [{
    'name': 'onoff',
    'pos': (15, 15),
    'label': 'on/off'
}, {
    'name': 'up',
    'pos': (75, 15),
    'label': '+'
}, {
BUTTON_LABEL_COLOR = 0x000000
#--| Button Config |-------------------------------------------------

# Setup touchscreen (PyPortal)
ts = adafruit_touchscreen.Touchscreen(board.TOUCH_XL, board.TOUCH_XR,
                                      board.TOUCH_YD, board.TOUCH_YU,
                                      calibration=((5200, 59000), (5800, 57000)),
                                      size=(320, 240))

# Make the display context
splash = displayio.Group()
board.DISPLAY.show(splash)

# Make the button
button = Button(x=BUTTON_X, y=BUTTON_Y,
                width=BUTTON_WIDTH, height=BUTTON_HEIGHT, style=BUTTON_STYLE,
                fill_color=BUTTON_FILL_COLOR, outline_color=BUTTON_OUTLINE_COLOR,
                label="HELLO WORLD", label_font=terminalio.FONT, label_color=BUTTON_LABEL_COLOR)

# Add button to the display context
splash.append(button.group)

# Loop and look for touches
while True:
    p = ts.touch_point
    if p:
        if button.contains(p):
            button.selected = True
    else:
        button.selected = False
    _icons.append(_new_icon)
    layout.add_content(_new_icon, grid_position=(i%4, i//4), cell_size=(1, 1))

"""

layer_label = bitmap_label.Label(terminalio.FONT)
layer_label.anchor_point = (0.5, 0.0)
layer_label.anchored_position = (display.width // 2, 4)
main_group.append(layer_label)

next_layer_btn = Button(
    x=layout.x + layout._width - 12,
    y=display.height - 70,
    width=50,
    height=70,
    style=Button.RECT,
    fill_color=0x00ff99,
    label="",
    label_font=terminalio.FONT,
    label_color=0x000000,
)

main_group.append(next_layer_btn)

home_layer_btn = Button(
    x=layout.x + layout._width - 12,
    y=0,
    width=50,
    height=70,
    style=Button.RECT,
    fill_color=0xFF9900,
Beispiel #18
0
class PYOA_Graphics:
    # pylint: disable=too-many-instance-attributes
    """A choose your own adventure game framework."""
    def __init__(self) -> None:
        self.root_group = displayio.Group()
        self._display = board.DISPLAY
        self._background_group = displayio.Group()
        self.root_group.append(self._background_group)
        self._text_group = displayio.Group()
        self.root_group.append(self._text_group)
        self._button_group = displayio.Group()
        self.root_group.append(self._button_group)

        if self._display.height > 250:
            self._text_group.scale = 2
            self._button_group.scale = 2

        self._speaker_enable = DigitalInOut(board.SPEAKER_ENABLE)
        self._speaker_enable.switch_to_output(False)
        if hasattr(board, "AUDIO_OUT"):
            self.audio = audioio.AudioOut(board.AUDIO_OUT)
        elif hasattr(board, "SPEAKER"):
            self.audio = audioio.AudioOut(board.SPEAKER)
        else:
            raise AttributeError("Board does not have an audio output!")

        self._background_file = None
        self._wavfile = None

        self._display.auto_brightness = False
        self.backlight_fade(0)
        self._display.show(self.root_group)
        self.touchscreen = None
        self.mouse_cursor = None
        if hasattr(board, "TOUCH_XL"):
            self.touchscreen = adafruit_touchscreen.Touchscreen(
                board.TOUCH_XL,
                board.TOUCH_XR,
                board.TOUCH_YD,
                board.TOUCH_YU,
                calibration=((5200, 59000), (5800, 57000)),
                size=(self._display.width, self._display.height),
            )
        elif hasattr(board, "BUTTON_CLOCK"):
            self.mouse_cursor = Cursor(self._display,
                                       display_group=self.root_group,
                                       cursor_speed=8)
            self.cursor = CursorManager(self.mouse_cursor)
        else:
            raise AttributeError("PYOA requires a touchscreen or cursor.")
        self._gamedirectory = None
        self._gamefilename = None
        self._game = None
        self._text = None
        self._background_sprite = None
        self._text_font = None
        self._left_button = None
        self._right_button = None
        self._middle_button = None

    def load_game(self, game_directory: str) -> None:
        """Load a game.

        :param str game_directory: where the game files are stored
        """
        self._gamedirectory = game_directory
        self._text_font = terminalio.FONT
        # Possible Screen Sizes are:
        # 320x240 PyPortal and PyPortal Pynt
        # 160x128 PyBadge and PyGamer
        # 480x320 PyPortal Titano
        # 240x240 if we wanted to use HalloWing M4

        # Button Attributes
        btn_left = 10
        btn_right = btn_left + 180
        btn_mid = btn_left + 90
        button_y = 195
        button_width = 120
        button_height = 40
        if self._display.height < 200:
            button_y //= 2
            button_y += 10
            button_width //= 2
            button_height //= 2
            btn_right //= 2
            btn_mid //= 2
        elif self._display.height > 250:
            button_y = (button_y * 3) // 4
            button_y -= 20
            button_width = (button_width * 3) // 4
            button_height = (button_height * 3) // 4
            btn_right = (btn_right * 3) // 4
            btn_mid = (btn_right * 3) // 4
        self._left_button = Button(
            x=btn_left,
            y=button_y,
            width=button_width,
            height=button_height,
            label="Left",
            label_font=self._text_font,
            style=Button.SHADOWROUNDRECT,
        )
        self._right_button = Button(
            x=btn_right,
            y=button_y,
            width=button_width,
            height=button_height,
            label="Right",
            label_font=self._text_font,
            style=Button.SHADOWROUNDRECT,
        )
        self._middle_button = Button(
            x=btn_mid,
            y=button_y,
            width=button_width,
            height=button_height,
            label="Middle",
            label_font=self._text_font,
            style=Button.SHADOWROUNDRECT,
        )
        self._gamefilename = game_directory + "/cyoa.json"
        try:
            with open(  # pylint: disable=unspecified-encoding
                    self._gamefilename, "r") as game_file:
                self._game = json.load(game_file)
        except OSError as err:
            raise OSError("Could not open game file " +
                          self._gamefilename) from err

    def _fade_to_black(self) -> None:
        """Turn down the lights."""
        if self.mouse_cursor:
            self.mouse_cursor.is_hidden = True
        self.backlight_fade(0)
        # turn off background so we can render the text
        self.set_background(None, with_fade=False)
        self.set_text(None, None)
        for _ in range(len(self._button_group)):
            self._button_group.pop()
        if self.mouse_cursor:
            self.mouse_cursor.is_hidden = False

    def _display_buttons(self, card: Dict[str, str]) -> None:
        """Display the buttons of a card.

        :param card: The active card
        :type card: dict(str, str)
        """
        button01_text = card.get("button01_text", None)
        button02_text = card.get("button02_text", None)
        self._left_button.label = button01_text
        self._middle_button.label = button01_text
        self._right_button.label = button02_text
        if button01_text and not button02_text:
            # show only middle button
            self._button_group.append(self._middle_button)
        if button01_text and button02_text:
            self._button_group.append(self._right_button)
            self._button_group.append(self._left_button)

    def _display_background_for(self, card: Dict[str, str]) -> None:
        """If there's a background on card, display it.

        :param card: The active card
        :type card: dict(str, str)
        """
        self.set_background(card.get("background_image", None),
                            with_fade=False)

    def _display_text_for(self, card: Dict[str, str]) -> None:
        """Display the main text of a card.

        :param card: The active card
        :type card: dict(str, str)
        """
        text = card.get("text", None)
        text_color = card.get("text_color", 0x0)  # default to black
        text_background_color = card.get("text_background_color", None)
        if text:
            try:
                text_color = int(
                    text_color)  # parse the JSON string to hex int
            except ValueError:
                text_color = 0x0

            try:
                text_background_color = int(
                    text_background_color)  # parse the JSON string to hex int
            except ValueError:
                text_background_color = None
            except TypeError:
                text_background_color = None

            self.set_text(text,
                          text_color,
                          background_color=text_background_color)

    def _play_sound_for(self, card: Dict[str, str]) -> None:
        """If there's a sound, start playing it.

        :param card: The active card
        :type card: dict(str, str)
        """
        sound = card.get("sound", None)
        loop = card.get("sound_repeat", False)
        if sound:
            loop = loop == "True"
            print("Loop:", loop)
            self.play_sound(sound, wait_to_finish=False, loop=loop)

    def _wait_for_press(self, card: Dict[str, str]) -> str:
        """Wait for a button to be pressed.

        :param card: The active card
        :type card: dict(str, str)
        :return: The id of the destination card
        :rtype: str
        """
        button01_text = card.get("button01_text", None)
        button02_text = card.get("button02_text", None)
        point_touched = None
        while True:
            if self.touchscreen is not None:
                point_touched = self.touchscreen.touch_point
            else:
                self.cursor.update()
                if self.cursor.is_clicked is True:
                    point_touched = self.mouse_cursor.x, self.mouse_cursor.y
            if point_touched is not None:
                point_touched = (
                    point_touched[0] // self._button_group.scale,
                    point_touched[1] // self._button_group.scale,
                )
                print("touch: ", point_touched)
                if button01_text and not button02_text:
                    # showing only middle button
                    if self._middle_button.contains(point_touched):
                        print("Middle button")
                        return card.get("button01_goto_card_id", None)
                if button01_text and button02_text:
                    if self._left_button.contains(point_touched):
                        print("Left button")
                        return card.get("button01_goto_card_id", None)
                    if self._right_button.contains(point_touched):
                        print("Right button")
                        return card.get("button02_goto_card_id", None)
            time.sleep(0.1)

    def display_card(self, card_num: int) -> int:
        """Display and handle input on a card.

        :param int card_num: the index of the card to process
        :return: the card number of the selected card
        :rtype: int
        """
        card = self._game[card_num]
        print(card)
        print("*" * 32)
        print("****{:^24s}****".format(card["card_id"]))
        print("*" * 32)

        self._fade_to_black()
        self._display_buttons(card)
        self._display_background_for(card)
        self.backlight_fade(1.0)
        self._display_text_for(card)
        self._display.refresh(target_frames_per_second=60)

        self._play_sound_for(card)

        auto_adv = card.get("auto_advance", None)
        if auto_adv is not None:
            auto_adv = float(auto_adv)
            print("Auto advancing after %0.1f seconds" % auto_adv)
            time.sleep(auto_adv)
            return card_num + 1

        destination_card_id = self._wait_for_press(card)

        self.play_sound(None)  # stop playing any sounds
        for card_number, card_struct in enumerate(self._game):
            if card_struct.get("card_id", None) == destination_card_id:
                return card_number  # found the matching card!
        # eep if we got here something went wrong
        raise RuntimeError("Could not find card with matching 'card_id': ",
                           destination_card_id)

    def play_sound(self,
                   filename: Optional[str],
                   *,
                   wait_to_finish: bool = True,
                   loop: bool = False) -> None:
        """Play a sound

        :param filename: The filename of the sound to play. Use `None` to stop
            playing anything.
        :type filename: str or None
        :param bool wait_to_finish: Whether playing the sound should block
        :param bool loop: Whether the sound should loop
        """
        self._speaker_enable.value = False
        self.audio.stop()
        if self._wavfile:
            self._wavfile.close()
            self._wavfile = None

        if not filename:
            return  # nothing more to do, just stopped
        filename = self._gamedirectory + "/" + filename
        print("Playing sound", filename)
        self._display.refresh(target_frames_per_second=60)
        try:
            self._wavfile = open(filename, "rb")  # pylint: disable=consider-using-with
        except OSError as err:
            raise OSError("Could not locate sound file", filename) from err

        wavedata = audiocore.WaveFile(self._wavfile)
        self._speaker_enable.value = True
        self.audio.play(wavedata, loop=loop)
        if loop or not wait_to_finish:
            return
        while self.audio.playing:
            pass
        self._wavfile.close()
        self._wavfile = None
        self._speaker_enable.value = False

    def set_text(
        self,
        text: Optional[str],
        color: Optional[str],
        background_color: Optional[int] = None,
    ) -> None:
        """Display the test for a card.

        :param text: the text to display
        :type text: str or None
        :param color: the text color
        :type color: str or None
        :param background_color: the background color of the text
        :type background_color: int or None
        """
        if self._text_group:
            self._text_group.pop()
        if not text or not color:
            return  # nothing to do!
        text_wrap = 37
        if self._display.height < 130:
            text_wrap = 25
        text = self.wrap_nicely(text, text_wrap)
        text = "\n".join(text)
        print("Set text to", text, "with color", hex(color))
        text_x = 8
        text_y = 95
        if self._display.height < 130:
            text_x = 3
            text_y = 38
        elif self._display.height > 250:
            text_y = 50
        if text:
            self._text = Label(self._text_font, text=str(text))
            self._text.x = text_x
            self._text.y = text_y
            self._text.color = color
            if background_color:
                self._text.background_color = background_color
            self._text_group.append(self._text)

    def set_background(self,
                       filename: Optional[str],
                       *,
                       with_fade: bool = True) -> None:
        """The background image to a bitmap file.

        :param filename: The filename of the chosen background
        :type filename: str or None
        :param bool with_fade: If `True` fade out the backlight while loading the new background
            and fade in the backlight once completed.
        """
        print("Set background to", filename)
        if with_fade:
            self.backlight_fade(0)
        if self._background_group:
            self._background_group.pop()

        if filename:
            background = displayio.OnDiskBitmap(self._gamedirectory + "/" +
                                                filename)
            self._background_sprite = displayio.TileGrid(
                background,
                pixel_shader=background.pixel_shader,
            )
            self._background_group.append(self._background_sprite)
        if with_fade:
            self._display.refresh(target_frames_per_second=60)
            self.backlight_fade(1.0)

    def backlight_fade(self, to_light: float) -> None:
        """
        Adjust the TFT backlight. Fade from the current value to the ``to_light`` value

        :param float to_light: the desired backlight brightness between :py:const:`0.0` and
            :py:const:`1.0`.
        """
        from_light = self._display.brightness
        from_light = int(from_light * 100)
        to_light = max(0, min(100, int(to_light * 100)))
        delta = 1
        if from_light > to_light:
            delta = -1
        for val in range(from_light, to_light, delta):
            self._display.brightness = val / 100
            time.sleep(0.003)
        self._display.brightness = to_light / 100

    # return a list of lines with wordwrapping
    @staticmethod
    def wrap_nicely(string: str, max_chars: int) -> List[str]:
        """A helper that will return a list of lines with word-break wrapping.

        :param str string: The text to be wrapped.
        :param int max_chars: The maximum number of characters on a line before wrapping.
        :return: The list of lines
        :rtype: list(str)
        """
        # string = string.replace('\n', '').replace('\r', '') # strip confusing newlines
        words = string.split(" ")
        the_lines = []
        the_line = ""
        for w in words:
            if "\n" in w:
                _w1, _w2 = w.split("\n")
                the_line += " " + _w1
                the_lines.append(the_line)
                the_line = _w2
            elif len(the_line + " " + w) > max_chars:
                the_lines.append(the_line)
                the_line = "" + w
            else:
                the_line += " " + w
        if the_line:  # last line remaining
            the_lines.append(the_line)
        # remove first space from first line:
        the_lines[0] = the_lines[0][1:]
        return the_lines
Beispiel #19
0
    def load_game(self, game_directory: str) -> None:
        """Load a game.

        :param str game_directory: where the game files are stored
        """
        self._gamedirectory = game_directory
        self._text_font = terminalio.FONT
        # Possible Screen Sizes are:
        # 320x240 PyPortal and PyPortal Pynt
        # 160x128 PyBadge and PyGamer
        # 480x320 PyPortal Titano
        # 240x240 if we wanted to use HalloWing M4

        # Button Attributes
        btn_left = 10
        btn_right = btn_left + 180
        btn_mid = btn_left + 90
        button_y = 195
        button_width = 120
        button_height = 40
        if self._display.height < 200:
            button_y //= 2
            button_y += 10
            button_width //= 2
            button_height //= 2
            btn_right //= 2
            btn_mid //= 2
        elif self._display.height > 250:
            button_y = (button_y * 3) // 4
            button_y -= 20
            button_width = (button_width * 3) // 4
            button_height = (button_height * 3) // 4
            btn_right = (btn_right * 3) // 4
            btn_mid = (btn_right * 3) // 4
        self._left_button = Button(
            x=btn_left,
            y=button_y,
            width=button_width,
            height=button_height,
            label="Left",
            label_font=self._text_font,
            style=Button.SHADOWROUNDRECT,
        )
        self._right_button = Button(
            x=btn_right,
            y=button_y,
            width=button_width,
            height=button_height,
            label="Right",
            label_font=self._text_font,
            style=Button.SHADOWROUNDRECT,
        )
        self._middle_button = Button(
            x=btn_mid,
            y=button_y,
            width=button_width,
            height=button_height,
            label="Middle",
            label_font=self._text_font,
            style=Button.SHADOWROUNDRECT,
        )
        self._gamefilename = game_directory + "/cyoa.json"
        try:
            with open(  # pylint: disable=unspecified-encoding
                    self._gamefilename, "r") as game_file:
                self._game = json.load(game_file)
        except OSError as err:
            raise OSError("Could not open game file " +
                          self._gamefilename) from err
Beispiel #20
0
bg_sprite = displayio.TileGrid(color_bitmap,
                               pixel_shader=color_palette,
                               position=(0, 0))
print(bg_sprite.position)
splash.append(bg_sprite)

##########################################################################

# Load the font
font = bitmap_font.load_font(THE_FONT)

buttons = []
# Default button styling:
button_0 = Button(x=BUTTON_MARGIN,
                  y=BUTTON_MARGIN,
                  width=BUTTON_WIDTH,
                  height=BUTTON_HEIGHT,
                  label="button0",
                  label_font=font)
buttons.append(button_0)

# a button with no indicators at all
button_1 = Button(x=BUTTON_MARGIN * 2 + BUTTON_WIDTH,
                  y=BUTTON_MARGIN,
                  width=BUTTON_WIDTH,
                  height=BUTTON_HEIGHT,
                  fill_color=None,
                  outline_color=None)
buttons.append(button_1)

# various colorings
button_2 = Button(x=BUTTON_MARGIN * 3 + 2 * BUTTON_WIDTH,
Beispiel #21
0
    'pos': (250, 170),
    'size': (60, 60),
    'file': "12.wav"
})

buttons = []
for spot in spots:
    fill = outline = None
    if SHOW_BUTTONS:
        fill = None
        outline = 0x00FF00
    button = Button(x=spot['pos'][0],
                    y=spot['pos'][1],
                    width=spot['size'][0],
                    height=spot['size'][1],
                    fill_color=fill,
                    outline_color=outline,
                    label=spot['label'],
                    label_color=None,
                    name=spot['file'])
    pyportal.splash.append(button.group)
    buttons.append(button)

last_pressed = None
currently_pressed = None
while True:
    p = pyportal.touchscreen.touch_point
    if p:
        print(p)
        for b in buttons:
            if b.contains(p):
Beispiel #22
0
print("Monotonic time", mono_time)

# Add buttons to the interface
assert len(
    secrets['totp_keys']) < 6, "This code can only display 5 keys at a time"

# generate buttons
buttons = []

btn_x = 5
for i in secrets['totp_keys']:
    button = Button(name=i[0],
                    x=btn_x,
                    y=175,
                    width=60,
                    height=60,
                    label=i[0].strip(" "),
                    label_font=font,
                    label_color=BTN_TEXT_COLOR,
                    fill_color=BTN_COLOR,
                    style=Button.ROUNDRECT)
    buttons.append(button)
    # add padding btween buttons
    btn_x += 63

# append buttons to splash group
for b in buttons:
    splash.append(b.group)

# refrsh timer label
label_timer = Label(font, max_glyphs=2)
label_timer.x = (display.width // 2) // 13
Beispiel #23
0
        'pos': (260, 200),
        'size': (75, 40),
        'color': GREEN,
        'label': "A"
    },
]

keypadGroup = displayio.Group(max_size=15)

kbuttons = []
for spot in keypadSpots:
    button = Button(x=spot['pos'][0],
                    y=spot['pos'][1],
                    width=spot['size'][0],
                    height=spot['size'][1],
                    style=Button.ROUNDRECT,
                    fill_color=spot['color'],
                    outline_color=0x222222,
                    name=spot['id'],
                    label=spot['label'],
                    label_font=arial_16)
    kbuttons.append(button)
    keypadGroup.append(button.group)
    print("Adding {} to kButtons".format(spot))

preMainGroup = displayio.Group(
    max_size=5)  # if getting weird errors, increase max size
preMainGroup.append(keypadGroup)

#matchIdLabelText = Label(arial_16, text="Match ID:", color=HEX_WHITE, x=10, y=30)  #uncomment for matchid
#preMainGroup.append(matchIdLabelText)  #uncomment for matchid
Beispiel #24
0
    def load_game(self, game_directory):
        """Load a game.

        :param game_directory: where the game files are stored
        """
        self._gamedirectory = game_directory
        self._text_font = terminalio.FONT
        # Possible Screen Sizes are:
        # 320x240 PyPortal and PyPortal Pynt
        # 160x128 PyBadge and PyGamer
        # 480x320 PyPortal Titano
        # 240x240 if we wanted to use HalloWing M4

        # Button Attributes
        btn_left = 10
        btn_right = btn_left + 180
        btn_mid = btn_left + 90
        button_y = 195
        button_width = 120
        button_height = 40
        if self._display.height < 200:
            button_y /= 2
            button_y += 10
            button_width /= 2
            button_height /= 2
            btn_right /= 2
            btn_mid /= 2
        elif self._display.height > 250:
            button_y *= 0.75
            button_y -= 20
            button_width *= 0.75
            button_height *= 0.75
            btn_right *= 0.75
            btn_mid *= 0.75
        self._left_button = Button(
            x=int(btn_left),
            y=int(button_y),
            width=int(button_width),
            height=int(button_height),
            label="Left",
            label_font=self._text_font,
            style=Button.SHADOWROUNDRECT,
        )
        self._right_button = Button(
            x=int(btn_right),
            y=int(button_y),
            width=int(button_width),
            height=int(button_height),
            label="Right",
            label_font=self._text_font,
            style=Button.SHADOWROUNDRECT,
        )
        self._middle_button = Button(
            x=int(btn_mid),
            y=int(button_y),
            width=int(button_width),
            height=int(button_height),
            label="Middle",
            label_font=self._text_font,
            style=Button.SHADOWROUNDRECT,
        )
        self._gamefilename = game_directory + "/cyoa.json"
        try:
            game_file = open(self._gamefilename, "r")
        except OSError:
            raise OSError("Could not open game file " + self._gamefilename)
        self._game = json.load(game_file)
        game_file.close()
print(bg_sprite.x, bg_sprite.y)
splash.append(bg_sprite)

##########################################################################

# Load the font
font = bitmap_font.load_font(THE_FONT)

buttons = []

for i in range(8):
    button = Button(x=BUTTON_MARGIN * (i // 4 + 1) + BUTTON_WIDTH * (i // 4),
                    y=BUTTON_MARGIN * (i % 4 + 1) + BUTTON_HEIGHT * (i % 4),
                    width=BUTTON_WIDTH,
                    height=BUTTON_HEIGHT,
                    label_color=0x00FF00,
                    selected_label=0x00FF00,
                    label="%f" % values[i],
                    label_font=font,
                    style=Button.SHADOWROUNDRECT)
    buttons.append(button)
button = Button(x=BUTTON_MARGIN * (3) + BUTTON_WIDTH * (2),
                y=BUTTON_MARGIN * (1) + BUTTON_HEIGHT * (0),
                width=BUTTON_WIDTH,
                height=BUTTON_HEIGHT,
                label="<<<",
                label_font=font,
                style=Button.SHADOWROUNDRECT)
buttons.append(button)
button = Button(x=BUTTON_MARGIN * (3) + BUTTON_WIDTH * (2),
                y=BUTTON_MARGIN * (2) + BUTTON_HEIGHT * (1),
                      x=counter['pos'][0],
                      y=counter['pos'][1],
                      color=counter['color'],
                      text=counter['text'])
        texts.append(texty)
        if len(texts) > 2:
            texts.pop(0)


#create the buttons on the screen
buttons = []
for spot in spots:
    button = Button(x=spot['pos'][0],
                    y=spot['pos'][1],
                    width=spot['size'][0],
                    height=spot['size'][1],
                    style=Button.SHADOWROUNDRECT,
                    fill_color=spot['color'],
                    outline_color=0x222222,
                    name=spot['label'])
    pyportal.splash.append(button.group)
    buttons.append(button)

#initial display without popping the list
update_display()

while True:
    touch = pyportal.touchscreen.touch_point
    if touch:
        if buttons[0].contains(touch):
            HEALTH -= 1
        if buttons[1].contains(touch):
Beispiel #27
0
                               pixel_shader=color_palette)
splash.append(bg_sprite)

buttons = []
# Default button styling:
BUTTON_WIDTH = 100
BUTTON_HEIGHT = 100
BUTTON_MARGIN = 10

# Button Objects
button_1 = Button(
    x=BUTTON_MARGIN,
    y=BUTTON_MARGIN,
    width=BUTTON_WIDTH,
    height=BUTTON_HEIGHT,
    label="Button 1",
    label_font=font,
    style=Button.SHADOWROUNDRECT,
    label_color=0x505050,
    fill_color=0x9E9E9E,
    outline_color=0x464646,
)
buttons.append(button_1)

button_2 = Button(
    x=BUTTON_MARGIN,
    y=BUTTON_MARGIN * 2 + BUTTON_HEIGHT,
    width=BUTTON_WIDTH,
    height=BUTTON_HEIGHT,
    label="Button 2",
    label_font=font,
    style=Button.SHADOWROUNDRECT,
Beispiel #28
0
if display.width < 240:
    BUTTON_WIDTH = int(BUTTON_WIDTH / 2)
    BUTTON_HEIGHT = int(BUTTON_HEIGHT / 2)
    BUTTON_MARGIN = int(BUTTON_MARGIN / 2)
    LBL_HEADER[0] -= 75
    LBL_HEADER[1] -= 10
    LBL_TEXT[0] -= 70
    LBL_TEXT[1] += 55

# Create the buttons
buttons = []

button_speed_inc = Button(
    x=BUTTON_MARGIN,
    y=BUTTON_MARGIN + BUTTON_HEIGHT,
    width=BUTTON_WIDTH,
    height=BUTTON_HEIGHT,
    label="Speed+",
    label_font=font,
)
buttons.append(button_speed_inc)

button_speed_dec = Button(
    x=BUTTON_MARGIN,
    y=BUTTON_MARGIN * 4 + BUTTON_HEIGHT,
    width=BUTTON_WIDTH,
    height=BUTTON_HEIGHT,
    label="Speed-",
    label_font=font,
)
buttons.append(button_speed_dec)
    "size": (60, 60),
    "file": "12.wav"
})

buttons = []
for spot in spots:
    fill = outline = None
    if SHOW_BUTTONS:
        fill = None
        outline = 0x00FF00
    button = Button(
        x=spot["pos"][0],
        y=spot["pos"][1],
        width=spot["size"][0],
        height=spot["size"][1],
        fill_color=fill,
        outline_color=outline,
        label=spot["label"],
        label_color=None,
        name=spot["file"],
    )
    pyportal.splash.append(button.group)
    buttons.append(button)

last_pressed = None
currently_pressed = None
while True:
    p = pyportal.touchscreen.touch_point
    if p:
        print(p)
        for b in buttons:
Beispiel #30
0
                           brightness=BRIGHTNESS)  # Adjust to fit your device
ring_1.fill(GREEN)
ring_1.show()

buttons = []
font = bitmap_font.load_font("/fonts/Arial-ItalicMT-17.bdf")
font.load_glyphs(
    b'abcdefghjiklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890- ()')

# Main User Interface Buttons
button_brighter = Button(x=0,
                         y=0,
                         width=BUTTON_WIDTH,
                         height=BUTTON_HEIGHT,
                         label="<",
                         label_font=font,
                         label_color=0xff7e00,
                         fill_color=0x5c5b5c,
                         outline_color=0x767676,
                         selected_fill=0x1a1a1a,
                         selected_outline=0x2e2e2e,
                         selected_label=0x525252)
buttons.append(button_brighter)  # adding this button to the buttons group

button_dimmer = Button(x=BUTTON_WIDTH,
                       y=0,
                       width=BUTTON_WIDTH,
                       height=BUTTON_HEIGHT,
                       label=">",
                       label_font=font,
                       label_color=0xff7e00,
                       fill_color=0x5c5b5c,