Skip to content

Commit

Permalink
Merge pull request #18 from adafruit/pylint-update
Browse files Browse the repository at this point in the history
Ran black, updated to pylint 2.x
  • Loading branch information
kattni authored Mar 10, 2020
2 parents 22140c0 + 7bf7e9c commit b9f3b03
Show file tree
Hide file tree
Showing 4 changed files with 196 additions and 137 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
188 changes: 107 additions & 81 deletions adafruit_pyoa.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand All @@ -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):
Expand All @@ -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
Expand All @@ -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
Expand All @@ -120,7 +126,6 @@ def __init__(self):
self._right_button = None
self._middle_button = None


def load_game(self, game_directory):
"""Load a game.
Expand All @@ -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
Expand All @@ -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()

Expand All @@ -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
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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:
Expand All @@ -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):
Expand All @@ -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)
Expand All @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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.
Expand All @@ -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:]
Expand Down
Loading

0 comments on commit b9f3b03

Please sign in to comment.