-
Notifications
You must be signed in to change notification settings - Fork 15
/
icon_old.py
594 lines (503 loc) · 17.4 KB
/
icon_old.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
import gc
from os import listdir
from time import sleep
import framebuf # type: ignore
from machine import Pin, Timer # type: ignore
class Icon:
"""Models an icon and all the properties it requires"""
image = None # the image data type buf
x = 0
y = 0
__invert = False
width = 16
height = 16
name = "Empty"
def __init__(
self, filename: None, width=None, height=None, x=None, y=None, name=None
):
"""Sets up the default values"""
if width:
self.width = width
if height:
self.height = height
if name:
self.name = name
if x:
self.x = x
if y:
self.y = y
if filename is not None:
self.image = self.loadicons(filename)
@property
def invert(self) -> bool:
"""Flips the bits in the image so white become black etc and returns the image"""
print("Invert is", self.__invert)
return self.__invert
@invert.setter
def invert(self, value: bool):
"""Inverts the icon colour"""
image = self.image
for x in range(0, self.width):
for y in range(0, self.height):
pxl = image.pixel(x, y)
if pxl == 0:
image.pixel(x, y, 1)
else:
image.pixel(x, y, 0)
self.image = image
self.__invert = value
# print("Invert is", self.__invert)
def loadicons(self, file):
""" Loads the icon from the file """
# print(file)
with open(file, "rb") as f:
f.readline() # magic number
f.readline() # creator comment
f.readline() # dimensions
data = bytearray(f.read())
frame_buffer = framebuf.FrameBuffer(
data, self.width, self.height, framebuf.MONO_HLSB
)
print(self.name, self.width, self.height)
return frame_buffer
def loadicon2(self, library, icon_data):
""" Loads the icon from the file """
__import__(library, icon_data)
# frame_buffer = framebuf.FrameBuffer(name, self.width,self.height, framebuf.MONO_HLSB)
# frame_buffer = bytearray(self.width * self.height // 8)
frame_buffer = bytearray(icon_data)
return frame_buffer
class Toolbar:
"""Models the toolbar"""
__icon_array = []
__framebuf = framebuf.FrameBuffer(
bytearray(160 * 64 * 1), 160, 16, framebuf.MONO_HLSB
)
spacer = 1
__selected_item = None
__selected_index = -1 # -1 means no item selected
def __init__(self):
# print("building toolbar")
self.__framebuf = framebuf.FrameBuffer(
bytearray(160 * 64 * 8), 160, 16, framebuf.MONO_HLSB
)
def additem(self, icon):
""" Adds an icon to the toolbar """
self.__icon_array.append(icon)
def remove(self, icon):
""" Removes an icon from the toolbar """
self.__icon_array.remove(icon)
@property
def data(self):
"""Returns the toolbar array as a buffer"""
x = 0
count = 0
for icon in self.__icon_array:
# print("x:",x)
count += 1
if isinstance(icon) is Icon: # check if the icon is a static icon
self.__framebuf.blit(icon.image, x, 0)
if isinstance(icon) is Animate: # check if the icon is an animated icon
self.__framebuf.blit(icon.__frames[icon.__current_frame].image, x, 0)
fb = self.__framebuf
x += icon.width + self.spacer
return fb
def show(self, display):
""" Show the toolbar on the display """
if self.data is None:
print("Data is None")
raise ValueError
# display.set_framebuffer(self.data)
display.blit(self.data, 0, 0)
# oled.show()
def select(self, index, oled):
"""Set the item in the index to inverted"""
# for item in self.__icon_array:
# item.invert = False
self.__icon_array[index].invert = True
self.__selected_index = index
self.show(oled)
def unselect(self, index, oled):
""" Unselect the item in the index """
self.__icon_array[index].invert = False
self.__selected_index = -1
self.show(oled)
@property
def selected_item(self):
"""Returns the name of the currently selected icon"""
self.__selected_item = self.__icon_array[self.__selected_index].name
return self.__selected_item
class Animate:
"""Models an animation"""
__frames = []
__current_frame = 0
__speed = "normal" # Other speeds are 'fast' and 'slow' - it just adds frames or skips frames
__speed_value = 0
__done = False # Has the animation completed
__loop_count = 0
__bouncing = False
__animation_type = "default"
__pause = 0
__set = False
__x = 0
__y = 0
__width = 16
__height = 16
__cached = False
filename = None
""" other animations types:
- loop
- bounce
- reverse
"""
@property
def set(self) -> bool:
""" Returns the set flag"""
return self.__set
@set.setter
def set(self, value: bool):
self.__set = value
if value: # if value is True
self.load()
else:
self.unload()
@property
def speed(self):
"""Returns the current speed"""
return self.__speed
@speed.setter
def speed(self, value: str):
if value in ["very slow", "slow", "normal", "fast"]:
self.__speed = value
if value == "very slow":
self.__pause = 10
self.__speed_value = 10
if value == "slow":
self.__pause = 1
self.__speed_value = 1
if value == "normal":
self.__pause = 0
self.__speed_value = 0
else:
print(value, "is not a valid value, try 'fast','normal' or 'slow'")
@property
def animation_type(self):
""" Returns the animation type"""
return self.__animation_type
@animation_type.setter
def animation_type(self, value):
if value in ["default", "loop", "bounce", "reverse"]:
self.__animation_type = value
else:
print(
value,
" is not a valid Animation type - it should be 'loop', \
'bounce','reverse' or 'default'",
)
def __init__(
self,
frames=None,
animation_type: str = None,
x: int = None,
y: int = None,
width: int = None,
height: int = None,
filename=None,
): # type: ignore
"""setup the animation"""
print(f"initialising animation: {filename}")
if x:
self.__x = x
if y:
self.__y = y
if width:
self.__width = width
if height:
self.__height = height
self.__current_frame = 0
if frames is not None:
self.__frames = frames
self.__done = False
self.__loop_count = 1
if animation_type is not None:
self.animation_type = animation_type
if filename:
self.filename = filename
def forward(self):
"""progress the current frame"""
if self.__speed == "normal":
self.__current_frame += 1
if self.__speed in ["very slow", "slow"]:
if self.__pause > 0:
self.__pause -= 1
else:
self.__current_frame += 1
self.__pause = self.__speed_value
if self.__speed == "fast":
if self.__current_frame < self.frame_count + 2:
self.__current_frame += 2
else:
self.__current_frame += 1
def reverse(self):
""" reverse the current frame animation direction """
if self.__speed == "normal":
self.__current_frame -= 1
if self.__speed in ["very slow", "slow"]:
if self.__pause > 0:
self.__pause -= 1
else:
self.__current_frame -= 1
self.__pause = self.__speed_value
if self.__speed == "fast":
if self.__current_frame < self.frame_count + 2:
self.__current_frame -= 2
else:
self.__current_frame -= 1
def load(self):
"""load the animation files"""
# load the files from disk
if not self.__cached:
files = listdir()
array = []
for file in files:
if (file.startswith(self.filename)) and (file.endswith(".pbm")):
array.append(
Icon(
filename=file,
width=self.__width,
height=self.__height,
x=self.__x,
y=self.__y,
name=file,
)
)
self.__frames = array
self.__cached = True
def unload(self):
"""free up memory"""
self.__frames = None
self.__cached = False
gc.collect()
def animate(self, oled):
"""Animates the frames based on the animation type and for the number of times specified"""
current_frame = (
self.__current_frame
) # Current Frame number - used to index the frames array
frame = self.__frames[current_frame]
oled.blit(frame.image, frame.x, frame.y)
if self.__animation_type == "loop":
# Loop from the first frame to the last, for the number of
# cycles specificed, and then set done to True
self.forward()
if self.__current_frame > self.frame_count:
self.__current_frame = 0
self.__loop_count -= 1
if self.__loop_count == 0:
self.__done = True
if self.__animation_type == "bouncing":
# Loop from the first frame to the last, and then back
# to the first again, then set done to True
if self.__bouncing:
if self.__current_frame == 0:
if self.__loop_count == 0:
self.__done = True
else:
if self.__loop_count > 0:
self.__loop_count -= 1
self.forward()
self.__bouncing = False
if self.__loop_count == -1:
# bounce infinately
self.forward()
self.__bouncing = False
if (self.__current_frame < self.frame_count) and (
self.__current_frame > 0
):
self.reverse()
else:
if self.__current_frame == 0:
if self.__loop_count == 0:
self.__done = True
elif self.__loop_count == -1:
# bounce infinatey
self.forward()
else:
self.forward()
self.__loop_count -= 1
elif self.__current_frame == self.frame_count:
self.reverse()
self.__bouncing = True
else:
self.forward()
if self.__animation_type == "default":
# loop through from first frame to last, then set done to True
if self.__current_frame == self.frame_count:
self.__current_frame = 0
self.__done = True
else:
self.forward()
@property
def frame_count(self):
"""Returns the total number of frames in the animation"""
return len(self.__frames) - 1
@property
def done(self):
"""Has the animation completed"""
if self.__done:
self.__done = False # reset the done flag to false
return True
else:
return False
def loop(self, no: int = None):
"""Loops the animation
if no is None or -1 the animation will continue looping until animate.stop() is called
"""
if no is not None:
self.__loop_count = no
else:
self.__loop_count = -1
self.__animation_type = "loop"
def stop(self):
""" Stops the animation """
self.__loop_count = 0
self.__bouncing = False
self.__done = True
def bounce(self, no: int = None):
"""Loops the animation forward, then backward, the number of time specified in no,
if there is no number provided it will animate infinately"""
self.__animation_type = "bouncing"
if no is not None:
self.__loop_count = no
else:
self.__loop_count = -1
@property
def width(self):
"""Gets the icon width"""
return self.__width
@width.setter
def width(self, value):
"""Sets the icon width"""
self.__width = value
@property
def height(self):
"""Gets the icon height"""
return self.__width
@height.setter
def height(self, value):
"""Sets the icon height"""
self.__height = value
def __str__(self):
""" Returns the current state of the animation"""
message = f"Animate: {self.filename}, {self.__current_frame}, \
{self.__loop_count}, {self.__done}, x: {self.__x}, y: {self.__y}"
return message
class Button:
"""Models a button, check the status with is_pressed"""
# The private variables
# __pressed = False
__pin = 0
# __button_down = False
def __init__(self, pin: int):
"""Sets up the button"""
self.__pin = Pin(pin, Pin.IN, Pin.PULL_UP)
# self.__pressed = False
@property
def is_pressed(self) -> bool:
"""Returns the current state of the button"""
if self.__pin.value() == 0:
# self.__button_down = True
print("button pressed")
return True
if self.__pin.value() == 1:
# self.__button_down = False
return False
# if not self.__button_down:
# self.__button_down = False
# return True
# else:
# return False
class Event:
"""Models events that can happen, with timers and pop up messages"""
name = ""
value = 0
sprite = None
timer = -1 # -1 means no timer set
timer_ms = 0
__callback = None
message = ""
done = False
_timer_instance = None # holds the timer instance
def __init__(self, name=None, sprite=None, value=None, callback=None):
"""Create a new event"""
if name:
self.name = name
if sprite:
self.sprite = sprite
if value:
self.value = value
if callback is not None:
self.__callback = callback
def popup(self, display):
""" Displays a popup message on the screen """
# display popup window
# show sprite
# show message
fbuf = framebuf.FrameBuffer(
bytearray(128 * 48 * 1), 128, 48, framebuf.MONO_HLSB
)
fbuf.rect(0, 0, 128, 48, 1)
fbuf.blit(self.sprite.image, 5, 10)
fbuf.text(self.message, 32, 18)
display.blit(fbuf, 0, 16)
# oled.blit(fbuf, 0, 16)
display.show()
# oled.show()
sleep(2)
def tick(self):
"""Progresses the animation on frame"""
self.timer_ms += 1
if self.timer_ms >= self.timer:
if self.__callback is not None:
print("poop check callback")
self.__callback()
self.timer = -1
self.timer_ms = 0
else:
# print("Timer Alert!")
self.done = True
def reset(self):
""" Resets the timer """
self.done = False
def start(self, duration):
"""Start a timer that will run a callback routine when complete"""
# print(f"Starting Timer for {duration/1000} seconds")
self.done = False
if self._timer_instance:
self._timer_instance.deinit() # Stop any previous timer
self._timer_instance = Timer(-1) # Create a one-shot timer
self._timer_instance.init(
period=duration, mode=Timer.ONE_SHOT, callback=self._timer_callback
)
def _timer_callback(self):
"""Internal method to handle the timer callback"""
if self.__callback:
# print("Timer completed, executing callback.")
self.__callback()
else:
print("Timer complete, but no callback")
self.done = True
# self.timer = -1
class GameState:
"""Models the game state"""
states = {}
def show(self):
"""Shows the current game state"""
print("Game State: ", self.states)
def __str__(self):
"""shows the current game state"""
message = "Game State: "
# for state in self.states:
# message += ", ".join(f"{key}: {value}" for key, value in self.states.items())
message += ", ".join(f"{key}: {value}" for key, value in self.states.items())
message += "."
return message