diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fff3aa9..1dad804 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -40,7 +40,7 @@ jobs: source actions-ci/install.sh - name: Pip install pylint, black, & Sphinx run: | - pip install --force-reinstall pylint==1.9.2 black==19.10b0 Sphinx sphinx-rtd-theme + pip install --force-reinstall pylint black==19.10b0 Sphinx sphinx-rtd-theme - name: Library version run: git describe --dirty --always --tags - name: PyLint diff --git a/adafruit_pyoa.py b/adafruit_pyoa.py index 6f67b01..d6b66a7 100755 --- a/adafruit_pyoa.py +++ b/adafruit_pyoa.py @@ -42,7 +42,7 @@ https://github.com/adafruit/circuitpython/releases """ -#pylint: disable=too-many-instance-attributes,no-self-use,line-too-long +# pylint: disable=too-many-instance-attributes,no-self-use,line-too-long # imports import time @@ -51,7 +51,8 @@ from digitalio import DigitalInOut import displayio import adafruit_touchscreen -try: # No need for Cursor Control on the PyPortal + +try: # No need for Cursor Control on the PyPortal from adafruit_cursorcontrol.cursorcontrol import Cursor from adafruit_cursorcontrol.cursorcontrol_cursormanager import CursorManager except ImportError: @@ -64,7 +65,8 @@ __version__ = "0.0.0-auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_PYOA.git" -class PYOA_Graphics(): + +class PYOA_Graphics: """A choose your own adventure game framework.""" def __init__(self): @@ -83,12 +85,12 @@ def __init__(self): self._speaker_enable = DigitalInOut(board.SPEAKER_ENABLE) self._speaker_enable.switch_to_output(False) - if hasattr(board, 'AUDIO_OUT'): + if hasattr(board, "AUDIO_OUT"): self.audio = audioio.AudioOut(board.AUDIO_OUT) - elif hasattr(board, 'SPEAKER'): + elif hasattr(board, "SPEAKER"): self.audio = audioio.AudioOut(board.SPEAKER) else: - raise AttributeError('Board does not have an audio output!') + raise AttributeError("Board does not have an audio output!") self._background_file = None self._wavfile = None @@ -98,18 +100,22 @@ def __init__(self): 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) + 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.') + raise AttributeError("PYOA requires a touchscreen or cursor.") self._gamedirectory = None self._gamefilename = None self._game = None @@ -120,7 +126,6 @@ def __init__(self): self._right_button = None self._middle_button = None - def load_game(self, game_directory): """Load a game. @@ -136,8 +141,8 @@ def load_game(self, game_directory): # Button Attributes btn_left = 10 - btn_right = btn_left+180 - btn_mid = btn_left+90 + btn_right = btn_left + 180 + btn_mid = btn_left + 90 button_y = 195 button_width = 120 button_height = 40 @@ -149,26 +154,44 @@ def load_game(self, game_directory): btn_right /= 2 btn_mid /= 2 elif self._display.height > 250: - button_y *= .75 + button_y *= 0.75 button_y -= 20 - button_width *= .75 - button_height *= .75 - btn_right *= .75 - btn_mid *= .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" + 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) + raise OSError("Could not open game file " + self._gamefilename) self._game = json.load(game_file) game_file.close() @@ -190,8 +213,8 @@ def _display_buttons(self, card): :param card: The active card """ - button01_text = card.get('button01_text', None) - button02_text = card.get('button02_text', None) + 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 @@ -207,18 +230,18 @@ def _display_background_for(self, card): :param card: The active card """ - self.set_background(card.get('background_image', None), with_fade=False) + self.set_background(card.get("background_image", None), with_fade=False) def _display_text_for(self, card): """Display the main text of a card. :param card: The active card """ - text = card.get('text', None) - text_color = card.get('text_color', 0x0) # default to black + text = card.get("text", None) + text_color = card.get("text_color", 0x0) # default to black if text: try: - text_color = int(text_color) # parse the JSON string to hex int + text_color = int(text_color) # parse the JSON string to hex int except ValueError: text_color = 0x0 self.set_text(text, text_color) @@ -228,8 +251,8 @@ def _play_sound_for(self, card): :param card: The active card """ - sound = card.get('sound', None) - loop = card.get('sound_repeat', False) + sound = card.get("sound", None) + loop = card.get("sound_repeat", False) if sound: loop = loop == "True" print("Loop:", loop) @@ -242,8 +265,8 @@ def _wait_for_press(self, card): Return the id of the destination card. """ - button01_text = card.get('button01_text', None) - button02_text = card.get('button02_text', None) + 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: @@ -253,21 +276,23 @@ def _wait_for_press(self, card): 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) + 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) + 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) + 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) + return card.get("button02_goto_card_id", None) time.sleep(0.1) def display_card(self, card_num): @@ -277,9 +302,9 @@ def display_card(self, card_num): """ card = self._game[card_num] print(card) - print("*"*32) - print('****{:^24s}****'.format(card['card_id'])) - print("*"*32) + print("*" * 32) + print("****{:^24s}****".format(card["card_id"])) + print("*" * 32) self._fade_to_black() self._display_buttons(card) @@ -294,21 +319,23 @@ def display_card(self, card_num): self._play_sound_for(card) - auto_adv = card.get('auto_advance', None) + 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 + 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! + 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) + raise RuntimeError( + "Could not find card with matching 'card_id': ", destination_card_id + ) def play_sound(self, filename, *, wait_to_finish=True, loop=False): """Play a sound @@ -324,8 +351,8 @@ def play_sound(self, filename, *, wait_to_finish=True, loop=False): self._wavfile = None if not filename: - return # nothing more to do, just stopped - filename = self._gamedirectory+"/"+filename + return # nothing more to do, just stopped + filename = self._gamedirectory + "/" + filename print("Playing sound", filename) try: self._display.refresh(target_frames_per_second=60) @@ -357,12 +384,12 @@ def set_text(self, text, color): if self._text_group: self._text_group.pop() if not text or not color: - return # nothing to do! + 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) + text = "\n".join(text) print("Set text to", text, "with color", hex(color)) text_x = 8 text_y = 95 @@ -392,11 +419,11 @@ def set_background(self, filename, *, with_fade=True): if filename: if self._background_file: self._background_file.close() - self._background_file = open(self._gamedirectory+"/"+filename, "rb") + self._background_file = open(self._gamedirectory + "/" + filename, "rb") background = displayio.OnDiskBitmap(self._background_file) - self._background_sprite = displayio.TileGrid(background, - pixel_shader=displayio.ColorConverter(), - x=0, y=0) + self._background_sprite = displayio.TileGrid( + background, pixel_shader=displayio.ColorConverter(), x=0, y=0 + ) self._background_group.append(self._background_sprite) if with_fade: try: @@ -410,20 +437,19 @@ def backlight_fade(self, to_light): """Adjust the TFT backlight. Fade from one value to another """ from_light = self._display.brightness - from_light = int(from_light*100) + from_light = int(from_light * 100) to_light = max(0, min(1.0, to_light)) - to_light = int(to_light*100) + to_light = 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 + self._display.brightness = val / 100 time.sleep(0.003) - self._display.brightness = to_light/100 - + self._display.brightness = to_light / 100 # return a list of lines with wordwrapping - #pylint: disable=invalid-name + # pylint: disable=invalid-name @staticmethod def wrap_nicely(string, max_chars): """A helper that will return a list of lines with word-break wrapping. @@ -432,22 +458,22 @@ def wrap_nicely(string, max_chars): :param int max_chars: The maximum number of characters on a line before wrapping. """ - #string = string.replace('\n', '').replace('\r', '') # strip confusing newlines - words = string.split(' ') + # 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 + 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: + elif len(the_line + " " + w) > max_chars: the_lines.append(the_line) - the_line = ''+w + the_line = "" + w else: - the_line += ' '+w - if the_line: # last line remaining + 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:] diff --git a/docs/conf.py b/docs/conf.py index 30789fd..349c32a 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -2,7 +2,8 @@ import os import sys -sys.path.insert(0, os.path.abspath('..')) + +sys.path.insert(0, os.path.abspath("..")) # -- General configuration ------------------------------------------------ @@ -10,46 +11,64 @@ # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.intersphinx', - 'sphinx.ext.napoleon', - 'sphinx.ext.todo', + "sphinx.ext.autodoc", + "sphinx.ext.intersphinx", + "sphinx.ext.napoleon", + "sphinx.ext.todo", ] # TODO: Please Read! # Uncomment the below if you use native CircuitPython modules such as # digitalio, micropython and busio. List the modules you use. Without it, the # autodoc module docs will fail to generate with a warning. -autodoc_mock_imports = ["rtc", "supervisor", "pulseio", "audioio", "displayio", "neopixel", - "microcontroller", "adafruit_touchscreen", "adafruit_bitmap_font", - "adafruit_display_text", "adafruit_esp32spi", "secrets", - "adafruit_sdcard", "storage", "adafruit_io", "adafruit_button", "adafruit_cursorcontrol", - "terminalio"] +autodoc_mock_imports = [ + "rtc", + "supervisor", + "pulseio", + "audioio", + "displayio", + "neopixel", + "microcontroller", + "adafruit_touchscreen", + "adafruit_bitmap_font", + "adafruit_display_text", + "adafruit_esp32spi", + "secrets", + "adafruit_sdcard", + "storage", + "adafruit_io", + "adafruit_button", + "adafruit_cursorcontrol", + "terminalio", +] -intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None),'CircuitPython': ('https://circuitpython.readthedocs.io/en/latest/', None)} +intersphinx_mapping = { + "python": ("https://docs.python.org/3.4", None), + "CircuitPython": ("https://circuitpython.readthedocs.io/en/latest/", None), +} # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] -source_suffix = '.rst' +source_suffix = ".rst" # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = u'Adafruit PYOA Library' -copyright = u'2019 Adafruit' -author = u'Adafruit' +project = "Adafruit PYOA Library" +copyright = "2019 Adafruit" +author = "Adafruit" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. -version = u'1.0' +version = "1.0" # The full version, including alpha/beta/rc tags. -release = u'1.0' +release = "1.0" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -61,7 +80,7 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', '.env', 'CODE_OF_CONDUCT.md'] +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", ".env", "CODE_OF_CONDUCT.md"] # The reST default role (used for this markup: `text`) to use for all # documents. @@ -73,7 +92,7 @@ add_function_parentheses = True # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False @@ -88,59 +107,62 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # -on_rtd = os.environ.get('READTHEDOCS', None) == 'True' +on_rtd = os.environ.get("READTHEDOCS", None) == "True" if not on_rtd: # only import and set the theme if we're building docs locally try: import sphinx_rtd_theme - html_theme = 'sphinx_rtd_theme' - html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), '.'] + + html_theme = "sphinx_rtd_theme" + html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."] except: - html_theme = 'default' - html_theme_path = ['.'] + html_theme = "default" + html_theme_path = ["."] else: - html_theme_path = ['.'] + html_theme_path = ["."] # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] +html_static_path = ["_static"] # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # -html_favicon = '_static/favicon.ico' +html_favicon = "_static/favicon.ico" # Output file base name for HTML help builder. -htmlhelp_basename = 'AdafruitPyoaLibrarydoc' +htmlhelp_basename = "AdafruitPyoaLibrarydoc" # -- Options for LaTeX output --------------------------------------------- latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # - # 'papersize': 'letterpaper', - - # The font size ('10pt', '11pt' or '12pt'). - # - # 'pointsize': '10pt', - - # Additional stuff for the LaTeX preamble. - # - # 'preamble': '', - - # Latex figure (float) alignment - # - # 'figure_align': 'htbp', + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, 'AdafruitPYOALibrary.tex', u'AdafruitPYOA Library Documentation', - author, 'manual'), + ( + master_doc, + "AdafruitPYOALibrary.tex", + "AdafruitPYOA Library Documentation", + author, + "manual", + ), ] # -- Options for manual page output --------------------------------------- @@ -148,8 +170,13 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - (master_doc, 'AdafruitPYOAlibrary', u'Adafruit PYOA Library Documentation', - [author], 1) + ( + master_doc, + "AdafruitPYOAlibrary", + "Adafruit PYOA Library Documentation", + [author], + 1, + ) ] # -- Options for Texinfo output ------------------------------------------- @@ -158,7 +185,13 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'AdafruitPYOALibrary', u'Adafruit PYOA Library Documentation', - author, 'AdafruitPYOALibrary', 'One line description of project.', - 'Miscellaneous'), + ( + master_doc, + "AdafruitPYOALibrary", + "Adafruit PYOA Library Documentation", + author, + "AdafruitPYOALibrary", + "One line description of project.", + "Miscellaneous", + ), ] diff --git a/examples/pyoa_simpletest.py b/examples/pyoa_simpletest.py index 64800ce..cfe961b 100644 --- a/examples/pyoa_simpletest.py +++ b/examples/pyoa_simpletest.py @@ -8,14 +8,14 @@ sdcard = adafruit_sdcard.SDCard(board.SPI(), digitalio.DigitalInOut(board.SD_CS)) vfs = storage.VfsFat(sdcard) storage.mount(vfs, "/sd") - print("SD card found") # no biggie + print("SD card found") # no biggie except OSError: - print("No SD card found") # no biggie + print("No SD card found") # no biggie gfx = PYOA_Graphics() gfx.load_game("/cyoa") -current_card = 0 # start with first card +current_card = 0 # start with first card while True: print("Current card:", current_card)