GuyCarver-MicroPython/level.py

68 wiersze
1.9 KiB
Python

2014-11-03 23:02:34 +00:00
#Show level bubble run by the accelerometer
import pyb
import terminalfont
2014-11-13 03:01:16 +00:00
ZeroPoint = (0, 0)
2014-11-03 23:02:34 +00:00
class Bubble(object):
"""Circle simulating the level bubble."""
def __init__( self, aCenter, aSpeed, aRadius, aColor ) :
2014-11-13 03:01:16 +00:00
self.center = aCenter
self.pos = aCenter
self.oldpos = self.pos
2014-11-03 23:02:34 +00:00
self.speed = aSpeed
2014-11-13 13:21:41 +00:00
self.radius = int(aRadius)
2014-11-03 23:02:34 +00:00
self.color = aColor
self.accel = pyb.Accel()
def update( self, aDisplay, aTime ) :
xtilt, ytilt, _ = self.accel.filtered_xyz()
# xtilt = self.accel.x()
# ytilt = self.accel.y()
2014-11-13 13:21:41 +00:00
ds = aDisplay.size()
xs = (ds[0] / 2) / 70.0
ys = (ds[1] / 2) / 60.0
2014-11-03 23:02:34 +00:00
2014-11-13 13:21:41 +00:00
self.oldpos = (int(self.pos[0]), int(self.pos[1]))
2014-11-13 03:01:16 +00:00
self.pos = (int(self.center[0] + xtilt * xs), int(self.center[1] - ytilt * ys))
2014-11-03 23:02:34 +00:00
s = "x: " + str(xtilt) + " y: " + str(ytilt)
2014-11-13 13:21:41 +00:00
aDisplay.fillrect(ZeroPoint, (ds[0], 8), 0)
aDisplay.text(ZeroPoint, s, aDisplay.CYAN, terminalfont.terminalfont)
2014-11-03 23:02:34 +00:00
# aTime *= self.speed
# self.pos.x += xtilt * aTime
# self.pos.y -= ytilt * aTime
self._clamp(aDisplay)
aDisplay.fillcircle(self.oldpos, self.radius, 0)
self._draw(aDisplay, self.color)
def _draw( self, aDisplay, aColor ) :
aDisplay.fillcircle(self.pos, self.radius, aColor)
def _clamp( self, aDisplay ) :
l = self.radius
t = l
2014-11-13 13:21:41 +00:00
ds = aDisplay.size()
r = ds[0] - l
b = ds[1] - l
2014-11-13 03:01:16 +00:00
self.pos = (max(l, min(self.pos[0], r)), max(t, min(self.pos[1], b)))
2014-11-03 23:02:34 +00:00
class Level(object):
"""Simulate a level by controlling a bubble on the aDisplay
controlled by the accelerometer."""
def __init__( self, aDisplay ) :
2014-11-03 23:02:34 +00:00
self.display = aDisplay
2014-11-13 13:21:41 +00:00
cx, cy = aDisplay.size()
2014-11-13 03:01:16 +00:00
cx /= 2
cy /= 2
2014-11-13 13:21:41 +00:00
self.bubble = Bubble((cx, cy), 10.0, 5, aDisplay.RED)
2014-11-03 23:02:34 +00:00
def run( self ) :
self.display.fill(0)
sw = pyb.Switch()
while sw() == False :
pyb.delay(100)
self.bubble.update(self.display, 0.1)