Skip to content

Commit 09908e3

Browse files
committed
Add sounds
1 parent 2dfc8d1 commit 09908e3

1 file changed

Lines changed: 46 additions & 9 deletions

File tree

Minesweep/code.py

Lines changed: 46 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import board
1717
import digitalio
1818
import displayio
19+
import audioio
1920
import adafruit_imageload
2021
import adafruit_touchscreen
2122
from random import seed, randint
@@ -24,6 +25,17 @@
2425

2526
seed(int(time.monotonic()))
2627

28+
# Set up audio
29+
speaker_enable = digitalio.DigitalInOut(board.SPEAKER_ENABLE)
30+
speaker_enable.switch_to_output(False)
31+
if hasattr(board, 'AUDIO_OUT'):
32+
audio = audioio.AudioOut(board.AUDIO_OUT)
33+
elif hasattr(board, 'SPEAKER'):
34+
audio = audioio.AudioOut(board.SPEAKER)
35+
else:
36+
raise AttributeError('Board does not have a builtin speaker!')
37+
38+
2739
NUMBER_OF_BOMBS = 15
2840

2941
# Board pieces
@@ -205,18 +217,43 @@ def reset_board():
205217
seed_bombs(NUMBER_OF_BOMBS)
206218
compute_counts()
207219

208-
def play_won_sound():
209-
pass
220+
def play_sound(file_name):
221+
board.DISPLAY.wait_for_frame()
222+
wavfile = open(file_name, "rb")
223+
wavedata = audioio.WaveFile(wavfile)
224+
speaker_enable.value = True
225+
audio.play(wavedata)
226+
return wavfile
227+
228+
def wait_for_sound_and_cleanup(wavfile):
229+
while audio.playing:
230+
pass
231+
wavfile.close()
232+
speaker_enable.value = False
233+
234+
def win():
235+
print('You won')
236+
# make_new_screenshot()
237+
wait_for_sound_and_cleanup(play_sound('win.wav'))
210238

211-
def play_lost_sound():
212-
pass
239+
def loose():
240+
print('You lost')
241+
# make_new_screenshot()
242+
wavfile = play_sound('loose.wav')
243+
for _ in range(10):
244+
tilegrid.x = randint(-2, 2)
245+
tilegrid.y = randint(-2, 2)
246+
display.refresh_soon()
247+
display.wait_for_frame()
248+
tilegrid.x = 0
249+
tilegrid.y = 0
250+
wait_for_sound_and_cleanup(wavfile)
213251

214252
while True:
215253
reset_board()
216254
if play_a_game():
217-
print('You won')
218-
play_won_sound()
255+
win()
219256
else:
220-
print('You lost')
221-
play_lost_sound()
222-
time.sleep(10.0)
257+
reveal()
258+
loose()
259+
time.sleep(5.0)

0 commit comments

Comments
 (0)