Ran black, updated to pylint 2.x

This commit is contained in:
dherrada 2020-03-16 17:19:46 -04:00
parent c2d86f2f24
commit 01ab4cd0a0
11 changed files with 282 additions and 196 deletions

View file

@ -40,7 +40,7 @@ jobs:
source actions-ci/install.sh source actions-ci/install.sh
- name: Pip install pylint, black, & Sphinx - name: Pip install pylint, black, & Sphinx
run: | 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 - name: Library version
run: git describe --dirty --always --tags run: git describe --dirty --always --tags
- name: PyLint - name: PyLint

View file

@ -44,8 +44,8 @@ Implementation Notes
https://github.com/adafruit/Adafruit_CircuitPython_BusDevice https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
""" """
#pylint:disable=too-many-public-methods, too-many-instance-attributes, invalid-name # pylint:disable=too-many-public-methods, too-many-instance-attributes, invalid-name
#pylint:disable=too-few-public-methods, too-many-lines, too-many-arguments # pylint:disable=too-few-public-methods, too-many-lines, too-many-arguments
import gc import gc
import math import math
@ -56,8 +56,10 @@ import displayio
__version__ = "0.0.0-auto.0" __version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_turtle.git" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_turtle.git"
class Color(object):
class Color:
"""Standard colors""" """Standard colors"""
WHITE = 0xFFFFFF WHITE = 0xFFFFFF
BLACK = 0x000000 BLACK = 0x000000
RED = 0xFF0000 RED = 0xFF0000
@ -75,8 +77,24 @@ class Color(object):
DARK_BLUE = 0x0000AA DARK_BLUE = 0x0000AA
DARK_RED = 0x800000 DARK_RED = 0x800000
colors = (BLACK, WHITE, RED, YELLOW, GREEN, ORANGE, BLUE, PURPLE, PINK, GRAY, colors = (
LIGHT_GRAY, BROWN, DARK_GREEN, TURQUOISE, DARK_BLUE, DARK_RED) BLACK,
WHITE,
RED,
YELLOW,
GREEN,
ORANGE,
BLUE,
PURPLE,
PINK,
GRAY,
LIGHT_GRAY,
BROWN,
DARK_GREEN,
TURQUOISE,
DARK_BLUE,
DARK_RED,
)
def __init__(self): def __init__(self):
pass pass
@ -88,6 +106,7 @@ class Vec2D(tuple):
May be useful for turtle graphics programs also. May be useful for turtle graphics programs also.
Derived from tuple, so a vector is a tuple! Derived from tuple, so a vector is a tuple!
""" """
# Provides (for a, b vectors, k number): # Provides (for a, b vectors, k number):
# a+b vector addition # a+b vector addition
# a-b vector subtraction # a-b vector subtraction
@ -103,7 +122,7 @@ class Vec2D(tuple):
def __mul__(self, other): def __mul__(self, other):
if isinstance(other, Vec2D): if isinstance(other, Vec2D):
return self[0] * other[0]+self[1] * other[1] return self[0] * other[0] + self[1] * other[1]
return Vec2D(self[0] * other, self[1] * other) return Vec2D(self[0] * other, self[1] * other)
def __rmul__(self, other): def __rmul__(self, other):
@ -118,7 +137,7 @@ class Vec2D(tuple):
return Vec2D(-self[0], -self[1]) return Vec2D(-self[0], -self[1])
def __abs__(self): def __abs__(self):
return (self[0]**2 + self[1]**2)**0.5 return (self[0] ** 2 + self[1] ** 2) ** 0.5
def rotate(self, angle): def rotate(self, angle):
"""Rotate self counterclockwise by angle. """Rotate self counterclockwise by angle.
@ -137,8 +156,10 @@ class Vec2D(tuple):
def __repr__(self): def __repr__(self):
return "({:.2f},{:.2f})".format(self[0], self[1]) return "({:.2f},{:.2f})".format(self[0], self[1])
class turtle(object):
class turtle:
"""A Turtle that can be given commands to draw.""" """A Turtle that can be given commands to draw."""
# pylint:disable=too-many-statements # pylint:disable=too-many-statements
def __init__(self, display=None, scale=1): def __init__(self, display=None, scale=1):
@ -168,18 +189,20 @@ class turtle(object):
if self._w == self._h: if self._w == self._h:
i = 1 i = 1
while self._bgscale == 1: while self._bgscale == 1:
if self._w/i < 128: if self._w / i < 128:
self._bg_bitmap = displayio.Bitmap(i, i, 1) self._bg_bitmap = displayio.Bitmap(i, i, 1)
self._bgscale = self._w//i self._bgscale = self._w // i
i += 1 i += 1
else: else:
self._bgscale = self._GCD(self._w, self._h) self._bgscale = self._GCD(self._w, self._h)
self._bg_bitmap = displayio.Bitmap(self._w//self._bgscale, self._h//self._bgscale, 1) self._bg_bitmap = displayio.Bitmap(
self._w // self._bgscale, self._h // self._bgscale, 1
)
self._bg_palette = displayio.Palette(1) self._bg_palette = displayio.Palette(1)
self._bg_palette[0] = Color.colors[self._bg_color] self._bg_palette[0] = Color.colors[self._bg_color]
self._bg_sprite = displayio.TileGrid(self._bg_bitmap, self._bg_sprite = displayio.TileGrid(
pixel_shader=self._bg_palette, self._bg_bitmap, pixel_shader=self._bg_palette, x=0, y=0
x=0, y=0) )
self._bg_group = displayio.Group(scale=self._bgscale, max_size=1) self._bg_group = displayio.Group(scale=self._bgscale, max_size=1)
self._bg_group.append(self._bg_sprite) self._bg_group.append(self._bg_sprite)
self._splash.append(self._bg_group) self._splash.append(self._bg_group)
@ -195,9 +218,9 @@ class turtle(object):
self._fg_palette.make_transparent(self._bg_color) self._fg_palette.make_transparent(self._bg_color)
for i, c in enumerate(Color.colors): for i, c in enumerate(Color.colors):
self._fg_palette[i] = c self._fg_palette[i] = c
self._fg_sprite = displayio.TileGrid(self._fg_bitmap, self._fg_sprite = displayio.TileGrid(
pixel_shader=self._fg_palette, self._fg_bitmap, pixel_shader=self._fg_palette, x=0, y=0
x=0, y=0) )
self._fg_group = displayio.Group(scale=self._fg_scale, max_size=1) self._fg_group = displayio.Group(scale=self._fg_scale, max_size=1)
self._fg_group.append(self._fg_sprite) self._fg_group.append(self._fg_sprite)
self._splash.append(self._fg_group) self._splash.append(self._fg_group)
@ -215,9 +238,9 @@ class turtle(object):
self._turtle_bitmap[i, 4 + i] = 1 self._turtle_bitmap[i, 4 + i] = 1
self._turtle_bitmap[4 + i, 7 - i] = 1 self._turtle_bitmap[4 + i, 7 - i] = 1
self._turtle_bitmap[4 + i, i] = 1 self._turtle_bitmap[4 + i, i] = 1
self._turtle_sprite = displayio.TileGrid(self._turtle_bitmap, self._turtle_sprite = displayio.TileGrid(
pixel_shader=self._turtle_palette, self._turtle_bitmap, pixel_shader=self._turtle_palette, x=-100, y=-100
x=-100, y=-100) )
self._turtle_group = displayio.Group(scale=self._fg_scale, max_size=2) self._turtle_group = displayio.Group(scale=self._fg_scale, max_size=2)
self._turtle_group.append(self._turtle_sprite) self._turtle_group.append(self._turtle_sprite)
@ -238,6 +261,7 @@ class turtle(object):
self._odb_tilegrid = None self._odb_tilegrid = None
gc.collect() gc.collect()
self._display.show(self._splash) self._display.show(self._splash)
# pylint:enable=too-many-statements # pylint:enable=too-many-statements
def _drawturtle(self): def _drawturtle(self):
@ -246,11 +270,11 @@ class turtle(object):
self._turtle_sprite.y = int(self._y - 4) self._turtle_sprite.y = int(self._y - 4)
else: else:
if self._turtle_odb is not None: if self._turtle_odb is not None:
self._turtle_alt_sprite.x = int(self._x - self._turtle_odb.width//2) self._turtle_alt_sprite.x = int(self._x - self._turtle_odb.width // 2)
self._turtle_alt_sprite.y = int(self._y - self._turtle_odb.height//2) self._turtle_alt_sprite.y = int(self._y - self._turtle_odb.height // 2)
else: else:
self._turtle_alt_sprite.x = int(self._x - self._turtle_pic[0]//2) self._turtle_alt_sprite.x = int(self._x - self._turtle_pic[0] // 2)
self._turtle_alt_sprite.y = int(self._y - self._turtle_pic[1]//2) self._turtle_alt_sprite.y = int(self._y - self._turtle_pic[1] // 2)
########################################################################### ###########################################################################
# Move and draw # Move and draw
@ -261,10 +285,13 @@ class turtle(object):
:param distance: how far to move (integer or float) :param distance: how far to move (integer or float)
""" """
p = self.pos() p = self.pos()
angle = (self._angleOffset + self._angleOrient*self._heading) % self._fullcircle angle = (
self._angleOffset + self._angleOrient * self._heading
) % self._fullcircle
x1 = p[0] + math.sin(math.radians(angle)) * distance x1 = p[0] + math.sin(math.radians(angle)) * distance
y1 = p[1] + math.cos(math.radians(angle)) * distance y1 = p[1] + math.cos(math.radians(angle)) * distance
self.goto(x1, y1) self.goto(x1, y1)
fd = forward fd = forward
def backward(self, distance): def backward(self, distance):
@ -275,6 +302,7 @@ class turtle(object):
""" """
self.forward(-distance) self.forward(-distance)
bk = backward bk = backward
back = backward back = backward
@ -289,6 +317,7 @@ class turtle(object):
self._turn(angle) self._turn(angle)
else: else:
self._turn(-angle) self._turn(-angle)
rt = right rt = right
def left(self, angle): def left(self, angle):
@ -302,6 +331,7 @@ class turtle(object):
self._turn(-angle) self._turn(-angle)
else: else:
self._turn(angle) self._turn(angle)
lt = left lt = left
# pylint:disable=too-many-branches,too-many-statements # pylint:disable=too-many-branches,too-many-statements
@ -322,7 +352,7 @@ class turtle(object):
x0 = self._x x0 = self._x
y0 = self._y y0 = self._y
if not self.isdown(): if not self.isdown():
self._x = x1 # woot, we just skip ahead self._x = x1 # woot, we just skip ahead
self._y = y1 self._y = y1
self._drawturtle() self._drawturtle()
return return
@ -346,7 +376,7 @@ class turtle(object):
ystep = 1 ystep = 1
step = 1 step = 1
if self._speed > 0: if self._speed > 0:
ts = (((11-self._speed)*0.00020)*(self._speed+0.5)) ts = ((11 - self._speed) * 0.00020) * (self._speed + 0.5)
else: else:
ts = 0 ts = 0
@ -382,6 +412,7 @@ class turtle(object):
else: else:
x0 += 1 x0 += 1
self._drawturtle() self._drawturtle()
setpos = goto setpos = goto
setposition = goto setposition = goto
# pylint:enable=too-many-branches,too-many-statements # pylint:enable=too-many-branches,too-many-statements
@ -418,6 +449,7 @@ class turtle(object):
""" """
self._turn(to_angle - self._heading) self._turn(to_angle - self._heading)
seth = setheading seth = setheading
def home(self): def home(self):
@ -437,7 +469,9 @@ class turtle(object):
except IndexError: except IndexError:
pass pass
r = self._pensize // 2 + 1 r = self._pensize // 2 + 1
angle = (self._angleOffset + self._angleOrient*self._heading - 90) % self._fullcircle angle = (
self._angleOffset + self._angleOrient * self._heading - 90
) % self._fullcircle
sin = math.sin(math.radians(angle)) sin = math.sin(math.radians(angle))
cos = math.cos(math.radians(angle)) cos = math.cos(math.radians(angle))
x0 = x + sin * r x0 = x + sin * r
@ -488,12 +522,12 @@ class turtle(object):
j = -1 if y1 < y0 else 1 j = -1 if y1 < y0 else 1
if steep: if steep:
try: try:
self._fg_bitmap[int(y0+j), int(x0)] = c self._fg_bitmap[int(y0 + j), int(x0)] = c
except IndexError: except IndexError:
pass pass
else: else:
try: try:
self._fg_bitmap[int(x0), int(y0+j)] = c self._fg_bitmap[int(x0), int(y0 + j)] = c
except IndexError: except IndexError:
pass pass
err -= dy err -= dy
@ -504,6 +538,7 @@ class turtle(object):
x0 -= 1 x0 -= 1
else: else:
x0 += 1 x0 += 1
# pylint:enable=too-many-locals, too-many-statements, too-many-branches # pylint:enable=too-many-locals, too-many-statements, too-many-branches
def circle(self, radius, extent=None, steps=None): def circle(self, radius, extent=None, steps=None):
@ -532,15 +567,15 @@ class turtle(object):
if extent is None: if extent is None:
extent = self._fullcircle extent = self._fullcircle
if steps is None: if steps is None:
frac = abs(extent)/self._fullcircle frac = abs(extent) / self._fullcircle
steps = int(min(3+abs(radius)/4.0, 12.0)*frac)*4 steps = int(min(3 + abs(radius) / 4.0, 12.0) * frac) * 4
w = extent / steps w = extent / steps
w2 = 0.5 * w w2 = 0.5 * w
l = radius * math.sin(w*math.pi/180.0*self._degreesPerAU) l = radius * math.sin(w * math.pi / 180.0 * self._degreesPerAU)
if radius < 0: if radius < 0:
l, w, w2 = -l, -w, -w2 l, w, w2 = -l, -w, -w2
self.left(w2) self.left(w2)
for _ in range(steps-1): for _ in range(steps - 1):
self.forward(l) self.forward(l)
self.left(w) self.left(w)
# rounding error correction on the last step # rounding error correction on the last step
@ -575,10 +610,11 @@ class turtle(object):
""" """
if speed is None: if speed is None:
return self._speed return self._speed
elif speed > 10 or speed < 1: if speed > 10 or speed < 1:
self._speed = 0 self._speed = 0
else: else:
self._speed = speed self._speed = speed
# pylint:enable=inconsistent-return-statements # pylint:enable=inconsistent-return-statements
def dot(self, size=None, color=None): def dot(self, size=None, color=None):
@ -614,7 +650,6 @@ class turtle(object):
self._plot(self._x, self._y, color) self._plot(self._x, self._y, color)
self._pensize = pensize self._pensize = pensize
def stamp(self, bitmap=None, palette=None): def stamp(self, bitmap=None, palette=None):
""" """
Stamp a copy of the turtle shape onto the canvas at the current Stamp a copy of the turtle shape onto the canvas at the current
@ -627,25 +662,32 @@ class turtle(object):
s_id = len(self._stamps) s_id = len(self._stamps)
if self._turtle_pic is None: if self._turtle_pic is None:
# easy. # easy.
new_stamp = displayio.TileGrid(self._turtle_bitmap, new_stamp = displayio.TileGrid(
pixel_shader=self._turtle_palette, self._turtle_bitmap,
x=int(self._x-self._turtle_bitmap.width//2), pixel_shader=self._turtle_palette,
y=int(self._y - self._turtle_bitmap.height // 2)) x=int(self._x - self._turtle_bitmap.width // 2),
y=int(self._y - self._turtle_bitmap.height // 2),
)
elif self._turtle_odb is not None: elif self._turtle_odb is not None:
# odb bitmap # odb bitmap
new_stamp = displayio.TileGrid(self._turtle_odb, new_stamp = displayio.TileGrid(
pixel_shader=displayio.ColorConverter(), self._turtle_odb,
x=int(self._x-self._turtle_odb.width//2), pixel_shader=displayio.ColorConverter(),
y=int(self._y - self._turtle_odb.height // 2)) x=int(self._x - self._turtle_odb.width // 2),
y=int(self._y - self._turtle_odb.height // 2),
)
self._turtle_odb_use += 1 self._turtle_odb_use += 1
else: else:
if bitmap is None: if bitmap is None:
raise RuntimeError("a bitmap must be provided") raise RuntimeError("a bitmap must be provided")
if palette is None: if palette is None:
raise RuntimeError("a palette must be provided") raise RuntimeError("a palette must be provided")
new_stamp = displayio.TileGrid(bitmap, pixel_shader=palette, new_stamp = displayio.TileGrid(
x=int(self._x-bitmap.width//2), bitmap,
y=int(self._y - bitmap.height // 2)) pixel_shader=palette,
x=int(self._x - bitmap.width // 2),
y=int(self._y - bitmap.height // 2),
)
self._fg_addon_group.append(new_stamp) self._fg_addon_group.append(new_stamp)
if self._turtle_odb is not None: if self._turtle_odb is not None:
self._stamps[s_id] = (new_stamp, self._turtle_odb_file) self._stamps[s_id] = (new_stamp, self._turtle_odb_file)
@ -701,6 +743,7 @@ class turtle(object):
def pos(self): def pos(self):
"""Return the turtle's current location (x,y) (as a Vec2D vector).""" """Return the turtle's current location (x,y) (as a Vec2D vector)."""
return Vec2D(self._x - self._w // 2, self._h // 2 - self._y) return Vec2D(self._x - self._w // 2, self._h // 2 - self._y)
position = pos position = pos
def towards(self, x1, y1=None): def towards(self, x1, y1=None):
@ -718,9 +761,9 @@ class turtle(object):
x1 = x1[0] x1 = x1[0]
x0, y0 = self.pos() x0, y0 = self.pos()
result = math.degrees(math.atan2(x1-x0, y1-y0)) result = math.degrees(math.atan2(x1 - x0, y1 - y0))
result /= self._degreesPerAU result /= self._degreesPerAU
return (self._angleOffset + self._angleOrient*result) % self._fullcircle return (self._angleOffset + self._angleOrient * result) % self._fullcircle
def xcor(self): def xcor(self):
"""Return the turtle's x coordinate.""" """Return the turtle's x coordinate."""
@ -749,7 +792,7 @@ class turtle(object):
y1 = x1[1] y1 = x1[1]
x1 = x1[0] x1 = x1[0]
x0, y0 = self.pos() x0, y0 = self.pos()
return math.sqrt((x0-x1) ** 2 + (y0 - y1) ** 2) return math.sqrt((x0 - x1) ** 2 + (y0 - y1) ** 2)
########################################################################### ###########################################################################
# Setting and measurement # Setting and measurement
@ -757,11 +800,11 @@ class turtle(object):
def _setDegreesPerAU(self, fullcircle): def _setDegreesPerAU(self, fullcircle):
"""Helper function for degrees() and radians()""" """Helper function for degrees() and radians()"""
self._fullcircle = fullcircle self._fullcircle = fullcircle
self._degreesPerAU = 360/fullcircle self._degreesPerAU = 360 / fullcircle
if self._logomode: if self._logomode:
self._angleOffset = 0 self._angleOffset = 0
else: else:
self._angleOffset = -fullcircle/4 self._angleOffset = -fullcircle / 4
def degrees(self, fullcircle=360): def degrees(self, fullcircle=360):
"""Set angle measurement units, i.e. set number of "degrees" for """Set angle measurement units, i.e. set number of "degrees" for
@ -775,7 +818,7 @@ class turtle(object):
def radians(self): def radians(self):
"""Set the angle measurement units to radians. """Set the angle measurement units to radians.
Equivalent to degrees(2*math.pi).""" Equivalent to degrees(2*math.pi)."""
self._setDegreesPerAU(2*math.pi) self._setDegreesPerAU(2 * math.pi)
def mode(self, mode=None): def mode(self, mode=None):
""" """
@ -791,7 +834,7 @@ class turtle(object):
if mode == "standard": if mode == "standard":
self._logomode = False self._logomode = False
self._angleOrient = -1 self._angleOrient = -1
self._angleOffset = self._fullcircle/4 self._angleOffset = self._fullcircle / 4
elif mode == "logo": elif mode == "logo":
self._logomode = True self._logomode = True
self._angleOrient = 1 self._angleOrient = 1
@ -820,12 +863,14 @@ class turtle(object):
def pendown(self): def pendown(self):
"""Pull the pen down - drawing when moving.""" """Pull the pen down - drawing when moving."""
self._penstate = True self._penstate = True
pd = pendown pd = pendown
down = pendown down = pendown
def penup(self): def penup(self):
"""Pull the pen up - no drawing when moving.""" """Pull the pen up - no drawing when moving."""
self._penstate = False self._penstate = False
pu = penup pu = penup
up = penup up = penup
@ -844,6 +889,7 @@ class turtle(object):
if width is not None: if width is not None:
self._pensize = width self._pensize = width
return self._pensize return self._pensize
width = pensize width = pensize
########################################################################### ###########################################################################
@ -853,6 +899,7 @@ class turtle(object):
def _color_to_pencolor(self, c): def _color_to_pencolor(self, c):
return Color.colors.index(c) return Color.colors.index(c)
# pylint:enable=no-self-use # pylint:enable=no-self-use
def pencolor(self, c=None): def pencolor(self, c=None):
@ -935,14 +982,17 @@ class turtle(object):
self._bg_pic = None self._bg_pic = None
self._bg_pic_filename = "" self._bg_pic_filename = ""
else: else:
self._bg_pic = open(picname, 'rb') self._bg_pic = open(picname, "rb")
odb = displayio.OnDiskBitmap(self._bg_pic) odb = displayio.OnDiskBitmap(self._bg_pic)
self._odb_tilegrid = displayio.TileGrid(odb, pixel_shader=displayio.ColorConverter()) self._odb_tilegrid = displayio.TileGrid(
odb, pixel_shader=displayio.ColorConverter()
)
self._bg_addon_group.append(self._odb_tilegrid) self._bg_addon_group.append(self._odb_tilegrid)
self._bg_pic_filename = picname self._bg_pic_filename = picname
# centered # centered
self._odb_tilegrid.y = ((self._h*self._fg_scale)//2) - (odb.height//2) self._odb_tilegrid.y = ((self._h * self._fg_scale) // 2) - (odb.height // 2)
self._odb_tilegrid.x = ((self._w*self._fg_scale)//2) - (odb.width//2) self._odb_tilegrid.x = ((self._w * self._fg_scale) // 2) - (odb.width // 2)
# pylint:enable=inconsistent-return-statements # pylint:enable=inconsistent-return-statements
########################################################################### ###########################################################################
@ -962,8 +1012,6 @@ class turtle(object):
self.pensize(1) self.pensize(1)
self.pencolor(Color.WHITE) self.pencolor(Color.WHITE)
def clear(self): def clear(self):
"""Delete the turtle's drawings from the screen. Do not move turtle.""" """Delete the turtle's drawings from the screen. Do not move turtle."""
self.clearstamps() self.clearstamps()
@ -988,6 +1036,7 @@ class turtle(object):
self._turtle_group.append(self._turtle_sprite) self._turtle_group.append(self._turtle_sprite)
else: else:
self._turtle_group.append(self._turtle_alt_sprite) self._turtle_group.append(self._turtle_alt_sprite)
st = showturtle st = showturtle
def hideturtle(self): def hideturtle(self):
@ -996,6 +1045,7 @@ class turtle(object):
if not self._turtle_group: if not self._turtle_group:
return return
self._turtle_group.pop() self._turtle_group.pop()
ht = hideturtle ht = hideturtle
def isvisible(self): def isvisible(self):
@ -1016,22 +1066,21 @@ class turtle(object):
if source is None: if source is None:
if self._turtle_pic is None: if self._turtle_pic is None:
return return
else: if self._turtle_group:
if self._turtle_group: self._turtle_group.remove(self._turtle_alt_sprite)
self._turtle_group.remove(self._turtle_alt_sprite) self._turtle_group.append(self._turtle_sprite)
self._turtle_group.append(self._turtle_sprite) self._turtle_alt_sprite = None
self._turtle_alt_sprite = None if self._turtle_odb is not None:
if self._turtle_odb is not None: self._turtle_odb_use -= 1
self._turtle_odb_use -= 1 self._turtle_odb = None
self._turtle_odb = None if self._turtle_odb_file is not None:
if self._turtle_odb_file is not None: if self._turtle_odb_use == 0:
if self._turtle_odb_use == 0: self._turtle_odb_file.close()
self._turtle_odb_file.close() self._turtle_odb_file = None
self._turtle_odb_file = None self._turtle_pic = None
self._turtle_pic = None self._drawturtle()
self._drawturtle() return
return if isinstance(source, str):
elif isinstance(source, str):
visible = self.isvisible() visible = self.isvisible()
if self._turtle_pic is not None: if self._turtle_pic is not None:
if self._turtle_group: if self._turtle_group:
@ -1043,7 +1092,7 @@ class turtle(object):
self._turtle_odb_file = None self._turtle_odb_file = None
self._turtle_odb_use -= 1 self._turtle_odb_use -= 1
self._turtle_pic = None self._turtle_pic = None
self._turtle_odb_file = open(source, 'rb') self._turtle_odb_file = open(source, "rb")
try: try:
self._turtle_odb = displayio.OnDiskBitmap(self._turtle_odb_file) self._turtle_odb = displayio.OnDiskBitmap(self._turtle_odb_file)
except: except:
@ -1055,8 +1104,9 @@ class turtle(object):
raise raise
self._turtle_odb_use += 1 self._turtle_odb_use += 1
self._turtle_pic = True self._turtle_pic = True
self._turtle_alt_sprite = displayio.TileGrid(self._turtle_odb, self._turtle_alt_sprite = displayio.TileGrid(
pixel_shader=displayio.ColorConverter()) self._turtle_odb, pixel_shader=displayio.ColorConverter()
)
if self._turtle_group: if self._turtle_group:
self._turtle_group.pop() self._turtle_group.pop()
@ -1076,7 +1126,10 @@ class turtle(object):
self._turtle_group.append(self._turtle_alt_sprite) self._turtle_group.append(self._turtle_alt_sprite)
self._drawturtle() self._drawturtle()
else: else:
raise TypeError('Argument must be "str", a "displayio.TileGrid" or nothing.') raise TypeError(
'Argument must be "str", a "displayio.TileGrid" or nothing.'
)
# pylint:enable=too-many-statements, too-many-branches # pylint:enable=too-many-statements, too-many-branches
########################################################################### ###########################################################################
@ -1087,15 +1140,17 @@ class turtle(object):
return return
if not self.isdown() or self._pensize == 1: if not self.isdown() or self._pensize == 1:
self._heading += angle self._heading += angle
self._heading %= self._fullcircle # wrap self._heading %= self._fullcircle # wrap
return return
start_angle = self._heading start_angle = self._heading
steps = math.ceil((self._pensize*2)*3.1415*(abs(angle)/self._fullcircle)) steps = math.ceil(
(self._pensize * 2) * 3.1415 * (abs(angle) / self._fullcircle)
)
if steps < 1: if steps < 1:
d_angle = angle d_angle = angle
steps = 1 steps = 1
else: else:
d_angle = angle/steps d_angle = angle / steps
if d_angle > 0: if d_angle > 0:
d_angle = math.ceil(d_angle) d_angle = math.ceil(d_angle)
@ -1107,16 +1162,16 @@ class turtle(object):
self._heading += angle self._heading += angle
else: else:
self._heading -= angle self._heading -= angle
self._heading %= self._fullcircle # wrap self._heading %= self._fullcircle # wrap
return return
if abs(angle-steps*d_angle) >= abs(d_angle): if abs(angle - steps * d_angle) >= abs(d_angle):
steps += abs(angle-steps*d_angle) // abs(d_angle) steps += abs(angle - steps * d_angle) // abs(d_angle)
self._plot(self._x, self._y, self._pencolor) self._plot(self._x, self._y, self._pencolor)
for _ in range(steps): for _ in range(steps):
self._heading += d_angle self._heading += d_angle
self._heading %= self._fullcircle # wrap self._heading %= self._fullcircle # wrap
self._plot(self._x, self._y, self._pencolor) self._plot(self._x, self._y, self._pencolor)
# error correction # error correction

View file

@ -2,7 +2,8 @@
import os import os
import sys import sys
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath(".."))
# -- General configuration ------------------------------------------------ # -- General configuration ------------------------------------------------
@ -10,46 +11,68 @@ sys.path.insert(0, os.path.abspath('..'))
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones. # ones.
extensions = [ extensions = [
'sphinx.ext.autodoc', "sphinx.ext.autodoc",
'sphinx.ext.intersphinx', "sphinx.ext.intersphinx",
'sphinx.ext.napoleon', "sphinx.ext.napoleon",
'sphinx.ext.todo', "sphinx.ext.todo",
] ]
# TODO: Please Read! # TODO: Please Read!
# Uncomment the below if you use native CircuitPython modules such as # Uncomment the below if you use native CircuitPython modules such as
# digitalio, micropython and busio. List the modules you use. Without it, the # digitalio, micropython and busio. List the modules you use. Without it, the
# autodoc module docs will fail to generate with a warning. # autodoc module docs will fail to generate with a warning.
autodoc_mock_imports = ["rtc", "supervisor", "pulseio", "audioio", "displayio", "neopixel", autodoc_mock_imports = [
"microcontroller", "adafruit_touchscreen", "adafruit_bitmap_font", "rtc",
"adafruit_display_text", "adafruit_esp32spi", "secrets", "supervisor",
"adafruit_sdcard", "storage", "adafruit_io", "adafruit_button", "pulseio",
"adafruit_logging", "board"] "audioio",
"displayio",
"neopixel",
"microcontroller",
"adafruit_touchscreen",
"adafruit_bitmap_font",
"adafruit_display_text",
"adafruit_esp32spi",
"secrets",
"adafruit_sdcard",
"storage",
"adafruit_io",
"adafruit_button",
"adafruit_logging",
"board",
]
intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None),'BusDevice': ('https://circuitpython.readthedocs.io/projects/busdevice/en/latest/', None),'CircuitPython': ('https://circuitpython.readthedocs.io/en/latest/', None)} intersphinx_mapping = {
"python": ("https://docs.python.org/3.4", None),
"BusDevice": (
"https://circuitpython.readthedocs.io/projects/busdevice/en/latest/",
None,
),
"CircuitPython": ("https://circuitpython.readthedocs.io/en/latest/", None),
}
# Add any paths that contain templates here, relative to this directory. # 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. # The master toctree document.
master_doc = 'index' master_doc = "index"
# General information about the project. # General information about the project.
project = u'Adafruit turtle Library' project = u"Adafruit turtle Library"
copyright = u'2019 Adafruit' copyright = u"2019 Adafruit"
author = u'Adafruit' author = u"Adafruit"
# The version info for the project you're documenting, acts as replacement for # The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the # |version| and |release|, also used in various other places throughout the
# built documents. # built documents.
# #
# The short X.Y version. # The short X.Y version.
version = u'1.0' version = u"1.0"
# The full version, including alpha/beta/rc tags. # The full version, including alpha/beta/rc tags.
release = u'1.0' release = u"1.0"
# The language for content autogenerated by Sphinx. Refer to documentation # The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages. # for a list of supported languages.
@ -61,7 +84,7 @@ language = None
# List of patterns, relative to source directory, that match files and # List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files. # directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path # 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 # The reST default role (used for this markup: `text`) to use for all
# documents. # documents.
@ -73,7 +96,7 @@ default_role = "any"
add_function_parentheses = True add_function_parentheses = True
# The name of the Pygments (syntax highlighting) style to use. # 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. # If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False todo_include_todos = False
@ -88,59 +111,62 @@ napoleon_numpy_docstring = False
# The theme to use for HTML and HTML Help pages. See the documentation for # The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes. # 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 if not on_rtd: # only import and set the theme if we're building docs locally
try: try:
import sphinx_rtd_theme 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: except:
html_theme = 'default' html_theme = "default"
html_theme_path = ['.'] html_theme_path = ["."]
else: else:
html_theme_path = ['.'] html_theme_path = ["."]
# Add any paths that contain custom static files (such as style sheets) here, # 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, # relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css". # 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 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 # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large. # pixels large.
# #
html_favicon = '_static/favicon.ico' html_favicon = "_static/favicon.ico"
# Output file base name for HTML help builder. # Output file base name for HTML help builder.
htmlhelp_basename = 'AdafruitTurtleLibrarydoc' htmlhelp_basename = "AdafruitTurtleLibrarydoc"
# -- Options for LaTeX output --------------------------------------------- # -- Options for LaTeX output ---------------------------------------------
latex_elements = { latex_elements = {
# The paper size ('letterpaper' or 'a4paper'). # The paper size ('letterpaper' or 'a4paper').
# #
# 'papersize': 'letterpaper', # 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
# The font size ('10pt', '11pt' or '12pt'). #
# # 'pointsize': '10pt',
# 'pointsize': '10pt', # Additional stuff for the LaTeX preamble.
#
# Additional stuff for the LaTeX preamble. # 'preamble': '',
# # Latex figure (float) alignment
# 'preamble': '', #
# 'figure_align': 'htbp',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
} }
# Grouping the document tree into LaTeX files. List of tuples # Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, # (source start file, target name, title,
# author, documentclass [howto, manual, or own class]). # author, documentclass [howto, manual, or own class]).
latex_documents = [ latex_documents = [
(master_doc, 'AdafruitturtleLibrary.tex', u'Adafruitturtle Library Documentation', (
author, 'manual'), master_doc,
"AdafruitturtleLibrary.tex",
u"Adafruitturtle Library Documentation",
author,
"manual",
),
] ]
# -- Options for manual page output --------------------------------------- # -- Options for manual page output ---------------------------------------
@ -148,8 +174,13 @@ latex_documents = [
# One entry per manual page. List of tuples # One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section). # (source start file, name, description, authors, manual section).
man_pages = [ man_pages = [
(master_doc, 'Adafruitturtlelibrary', u'Adafruit turtle Library Documentation', (
[author], 1) master_doc,
"Adafruitturtlelibrary",
u"Adafruit turtle Library Documentation",
[author],
1,
)
] ]
# -- Options for Texinfo output ------------------------------------------- # -- Options for Texinfo output -------------------------------------------
@ -158,7 +189,13 @@ man_pages = [
# (source start file, target name, title, author, # (source start file, target name, title, author,
# dir menu entry, description, category) # dir menu entry, description, category)
texinfo_documents = [ texinfo_documents = [
(master_doc, 'AdafruitturtleLibrary', u'Adafruit turtle Library Documentation', (
author, 'AdafruitturtleLibrary', 'One line description of project.', master_doc,
'Miscellaneous'), "AdafruitturtleLibrary",
u"Adafruit turtle Library Documentation",
author,
"AdafruitturtleLibrary",
"One line description of project.",
"Miscellaneous",
),
] ]

View file

@ -12,7 +12,7 @@ turtle.pendown()
start = turtle.pos() start = turtle.pos()
for x in range(benzsize): for x in range(benzsize):
turtle.pencolor(colors[x%6]) turtle.pencolor(colors[x % 6])
turtle.forward(x) turtle.forward(x)
turtle.left(59) turtle.left(59)

View file

@ -1,6 +1,7 @@
import board import board
from adafruit_turtle import turtle from adafruit_turtle import turtle
def hilbert2(step, rule, angle, depth, t): def hilbert2(step, rule, angle, depth, t):
if depth > 0: if depth > 0:
a = lambda: hilbert2(step, "a", angle, depth - 1, t) a = lambda: hilbert2(step, "a", angle, depth - 1, t)
@ -33,6 +34,7 @@ def hilbert2(step, rule, angle, depth, t):
a() a()
right() right()
turtle = turtle(board.DISPLAY) turtle = turtle(board.DISPLAY)
turtle.penup() turtle.penup()
turtle.setheading(90) turtle.setheading(90)

View file

@ -1,10 +1,9 @@
import board import board
from adafruit_turtle import turtle from adafruit_turtle import turtle
def f(side_length, depth, generation): def f(side_length, depth, generation):
if depth == 0: if depth != 0:
side = turtle.forward(side_length)
else:
side = lambda: f(side_length / 3, depth - 1, generation + 1) side = lambda: f(side_length / 3, depth - 1, generation + 1)
side() side()
turtle.left(60) turtle.left(60)
@ -14,6 +13,7 @@ def f(side_length, depth, generation):
turtle.left(60) turtle.left(60)
side() side()
turtle = turtle(board.DISPLAY) turtle = turtle(board.DISPLAY)
unit = min(board.DISPLAY.width / 3, board.DISPLAY.height / 4) unit = min(board.DISPLAY.width / 3, board.DISPLAY.height / 4)

View file

@ -3,10 +3,9 @@ from adafruit_turtle import turtle, Color
generation_colors = [Color.RED, Color.BLUE, Color.GREEN] generation_colors = [Color.RED, Color.BLUE, Color.GREEN]
def f(side_length, depth, generation): def f(side_length, depth, generation):
if depth == 0: if depth != 0:
side = turtle.forward(side_length)
else:
side = lambda: f(side_length / 3, depth - 1, generation + 1) side = lambda: f(side_length / 3, depth - 1, generation + 1)
side() side()
turtle.left(60) turtle.left(60)
@ -16,6 +15,7 @@ def f(side_length, depth, generation):
turtle.left(60) turtle.left(60)
side() side()
def snowflake(num_generations, generation_color): def snowflake(num_generations, generation_color):
top_side = lambda: f(top_len, num_generations, 0) top_side = lambda: f(top_len, num_generations, 0)
turtle.pencolor(generation_color) turtle.pencolor(generation_color)
@ -28,7 +28,7 @@ def snowflake(num_generations, generation_color):
turtle = turtle(board.DISPLAY) turtle = turtle(board.DISPLAY)
unit= min(board.DISPLAY.width / 3, board.DISPLAY.height / 4) unit = min(board.DISPLAY.width / 3, board.DISPLAY.height / 4)
top_len = unit * 3 top_len = unit * 3
print(top_len) print(top_len)
turtle.setheading(90) turtle.setheading(90)

View file

@ -1,8 +1,10 @@
import board import board
from adafruit_turtle import turtle from adafruit_turtle import turtle
def getMid(p1, p2): def getMid(p1, p2):
return ((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2) #find midpoint return ((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2) # find midpoint
def triangle(points, depth): def triangle(points, depth):
@ -14,23 +16,24 @@ def triangle(points, depth):
turtle.goto(points[0][0], points[0][1]) turtle.goto(points[0][0], points[0][1])
if depth > 0: if depth > 0:
triangle([points[0], triangle(
getMid(points[0], points[1]), [points[0], getMid(points[0], points[1]), getMid(points[0], points[2])],
getMid(points[0], points[2])], depth - 1,
depth-1) )
triangle([points[1], triangle(
getMid(points[0], points[1]), [points[1], getMid(points[0], points[1]), getMid(points[1], points[2])],
getMid(points[1], points[2])], depth - 1,
depth-1) )
triangle([points[2], triangle(
getMid(points[2], points[1]), [points[2], getMid(points[2], points[1]), getMid(points[0], points[2])],
getMid(points[0], points[2])], depth - 1,
depth-1) )
turtle = turtle(board.DISPLAY) turtle = turtle(board.DISPLAY)
big = min(board.DISPLAY.width / 2, board.DISPLAY.height / 2) big = min(board.DISPLAY.width / 2, board.DISPLAY.height / 2)
little = big / 1.4 little = big / 1.4
seed_points = [[-big, -little], [0, big], [big, -little]] #size of triangle seed_points = [[-big, -little], [0, big], [big, -little]] # size of triangle
triangle(seed_points, 4) triangle(seed_points, 4)
while True: while True:

View file

@ -10,7 +10,7 @@ turtle.pencolor(Color.BLUE)
turtle.setheading(90) turtle.setheading(90)
turtle.penup() turtle.penup()
turtle.goto(-starsize/2, 0) turtle.goto(-starsize / 2, 0)
turtle.pendown() turtle.pendown()
start = turtle.pos() start = turtle.pos()

View file

@ -10,7 +10,7 @@ turtle.pencolor(Color.BLUE)
turtle.setheading(90) turtle.setheading(90)
turtle.penup() turtle.penup()
turtle.goto(-starsize/2, 0) turtle.goto(-starsize / 2, 0)
turtle.pendown() turtle.pendown()
start = turtle.pos() start = turtle.pos()

View file

@ -6,6 +6,7 @@ https://github.com/pypa/sampleproject
""" """
from setuptools import setup, find_packages from setuptools import setup, find_packages
# To use a consistent encoding # To use a consistent encoding
from codecs import open from codecs import open
from os import path from os import path
@ -13,52 +14,40 @@ from os import path
here = path.abspath(path.dirname(__file__)) here = path.abspath(path.dirname(__file__))
# Get the long description from the README file # Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f: with open(path.join(here, "README.rst"), encoding="utf-8") as f:
long_description = f.read() long_description = f.read()
setup( setup(
name='adafruit-circuitpython-turtle', name="adafruit-circuitpython-turtle",
use_scm_version=True, use_scm_version=True,
setup_requires=['setuptools_scm'], setup_requires=["setuptools_scm"],
description="Turtle graphics library for CircuitPython and displayio",
description='Turtle graphics library for CircuitPython and displayio',
long_description=long_description, long_description=long_description,
long_description_content_type='text/x-rst', long_description_content_type="text/x-rst",
# The project's main homepage. # The project's main homepage.
url='https://github.com/adafruit/Adafruit_CircuitPython_turtle', url="https://github.com/adafruit/Adafruit_CircuitPython_turtle",
# Author details # Author details
author='Adafruit Industries', author="Adafruit Industries",
author_email='circuitpython@adafruit.com', author_email="circuitpython@adafruit.com",
install_requires=["Adafruit-Blinka", "adafruit-circuitpython-busdevice"],
install_requires=[
'Adafruit-Blinka',
'adafruit-circuitpython-busdevice'
],
# Choose your license # Choose your license
license='MIT', license="MIT",
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[ classifiers=[
'Development Status :: 3 - Alpha', "Development Status :: 3 - Alpha",
'Intended Audience :: Developers', "Intended Audience :: Developers",
'Topic :: Software Development :: Libraries', "Topic :: Software Development :: Libraries",
'Topic :: System :: Hardware', "Topic :: System :: Hardware",
'License :: OSI Approved :: MIT License', "License :: OSI Approved :: MIT License",
'Programming Language :: Python :: 3', "Programming Language :: Python :: 3",
'Programming Language :: Python :: 3.4', "Programming Language :: Python :: 3.4",
'Programming Language :: Python :: 3.5', "Programming Language :: Python :: 3.5",
], ],
# What does your project relate to? # What does your project relate to?
keywords='adafruit blinka circuitpython micropython turtle graphics,turtle', keywords="adafruit blinka circuitpython micropython turtle graphics,turtle",
# You can just specify the packages manually here if your project is # You can just specify the packages manually here if your project is
# simple. Or you can use find_packages(). # simple. Or you can use find_packages().
# TODO: IF LIBRARY FILES ARE A PACKAGE FOLDER, # TODO: IF LIBRARY FILES ARE A PACKAGE FOLDER,
# CHANGE `py_modules=['...']` TO `packages=['...']` # CHANGE `py_modules=['...']` TO `packages=['...']`
py_modules=['adafruit_turtle'], py_modules=["adafruit_turtle"],
) )