Initial commit
[one-dimensional-fireworks.git] / fireworks8.py
1 from microbit import *
2 import neopixel
3 import random
4 import radio # Add this line
5
6 NP_COUNT = 60
7 BURST_SIZE = 10
8 DISPLAY_ANIMATION_SPEED = 500
9
10 np = neopixel.NeoPixel(pin0, NP_COUNT)
11
12 radio.on() # Add this line
13
14 BLUE = (0, 0, 64)
15 RED = (64, 0, 0)
16 OFF = (0, 0, 0)
17
18 # Add this block
19 FIREWORK_COLOURS = [ (255, 128, 128), (128, 255, 128), (128, 128, 255)
20 , (255, 255, 128), (255, 128, 255), (128, 255, 255)
21 ]
22
23 def fade_all(pixels, first=0, last=NP_COUNT, fade_by=0.9):
24 for i in range(first, last):
25 fade(pixels, i, fade_by=fade_by)
26 pixels.show()
27
28 def fade(pixels, n, fade_by=0.9):
29 r, g, b = pixels[n]
30 pixels[n] = (int(r * fade_by), int(g * fade_by), int(b * fade_by))
31
32 def explode(pixels):
33 initial_colour = random.choice(FIREWORK_COLOURS)
34
35 for i in range(BURST_SIZE):
36 pixels[NP_COUNT - BURST_SIZE + i] = initial_colour
37 pixels[NP_COUNT - BURST_SIZE - i] = initial_colour
38 fade_all( pixels, fade_by=0.95
39 , first=(NP_COUNT - BURST_SIZE - i)
40 , last= (NP_COUNT - BURST_SIZE + 1)
41 )
42
43 for _ in range(30):
44 fade_all(pixels, first=(NP_COUNT - 2 * BURST_SIZE))
45
46 def reset(pixels):
47 for n in range(NP_COUNT):
48 pixels[n] = OFF
49 pixels[0] = BLUE
50 np.show()
51 display.show(Image.DIAMOND)
52
53
54 def shoot_firework(pixels):
55 display.show(Image.ARROW_S)
56 for pixel in range(NP_COUNT - BURST_SIZE):
57 pixels[pixel] = RED
58 pixels.show()
59 sleep(20)
60 pixels[pixel] = OFF
61 pixels.show()
62
63
64 def all_firework():
65 radio.send('fire') # Add this line
66 shoot_firework(np)
67 explode(np)
68 reset(np)
69
70
71 reset(np)
72 display_timer = 0
73 radio_timer = 0
74 last_gesture = accelerometer.current_gesture()
75
76 while True:
77 gesture = accelerometer.current_gesture()
78 if gesture != last_gesture or button_a.is_pressed():
79 # set off a firework
80 all_firework()
81 last_gesture = gesture
82 elif radio_timer > 0 and radio_timer == display_timer:
83 all_firework()
84 radio_timer = 0
85 last_gesture = gesture
86 else:
87 # animate the waiting
88 display_timer = (display_timer + 1) % DISPLAY_ANIMATION_SPEED
89 if display_timer > (DISPLAY_ANIMATION_SPEED / 2):
90 display.show(Image.DIAMOND_SMALL)
91 else:
92 display.show(Image.DIAMOND)
93 received = radio.receive()
94 if received == 'fire' and random.randrange(5) == 0:
95 radio_timer = (display_timer + random.randint(50, 350)) % DISPLAY_ANIMATION_SPEED