-
Notifications
You must be signed in to change notification settings - Fork 42
/
demo_bouncing_boxes.py
110 lines (93 loc) · 3.18 KB
/
demo_bouncing_boxes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
"""ILI9341 demo (bouncing boxes)."""
from machine import Pin, SPI
from random import random, seed
from ili9341 import Display, color565
from utime import sleep_us, ticks_cpu, ticks_us, ticks_diff
class Box(object):
"""Bouncing box."""
def __init__(self, screen_width, screen_height, size, display, color):
"""Initialize box.
Args:
screen_width (int): Width of screen.
screen_height (int): Width of height.
size (int): Square side length.
display (ILI9341): display object.
color (int): RGB565 color value.
"""
self.size = size
self.w = screen_width
self.h = screen_height
self.display = display
self.color = color
# Generate non-zero random speeds between -5.0 and 5.0
seed(ticks_cpu())
r = random() * 10.0
self.x_speed = 5.0 - r if r < 5.0 else r - 10.0
r = random() * 10.0
self.y_speed = 5.0 - r if r < 5.0 else r - 10.0
self.x = self.w / 2.0
self.y = self.h / 2.0
self.prev_x = self.x
self.prev_y = self.y
def update_pos(self):
"""Update box position and speed."""
x = self.x
y = self.y
size = self.size
w = self.w
h = self.h
x_speed = abs(self.x_speed)
y_speed = abs(self.y_speed)
self.prev_x = x
self.prev_y = y
if x + size >= w - x_speed:
self.x_speed = -x_speed
elif x - size <= x_speed + 1:
self.x_speed = x_speed
if y + size >= h - y_speed:
self.y_speed = -y_speed
elif y - size <= y_speed + 1:
self.y_speed = y_speed
self.x = x + self.x_speed
self.y = y + self.y_speed
def draw(self):
"""Draw box."""
x = int(self.x)
y = int(self.y)
size = self.size
prev_x = int(self.prev_x)
prev_y = int(self.prev_y)
self.display.fill_hrect(prev_x - size,
prev_y - size,
size, size, 0)
self.display.fill_hrect(x - size,
y - size,
size, size, self.color)
def test():
"""Bouncing box."""
try:
# Baud rate of 40000000 seems about the max
spi = SPI(1, baudrate=40000000, sck=Pin(14), mosi=Pin(13))
display = Display(spi, dc=Pin(4), cs=Pin(16), rst=Pin(17))
display.clear()
colors = [color565(255, 0, 0),
color565(0, 255, 0),
color565(0, 0, 255),
color565(255, 255, 0),
color565(0, 255, 255),
color565(255, 0, 255)]
sizes = [12, 11, 10, 9, 8, 7]
boxes = [Box(239, 319, sizes[i], display,
colors[i]) for i in range(6)]
while True:
timer = ticks_us()
for b in boxes:
b.update_pos()
b.draw()
# Attempt to set framerate to 30 FPS
timer_dif = 33333 - ticks_diff(ticks_us(), timer)
if timer_dif > 0:
sleep_us(timer_dif)
except KeyboardInterrupt:
display.cleanup()
test()