-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmorsecode.py
More file actions
89 lines (68 loc) · 1.74 KB
/
morsecode.py
File metadata and controls
89 lines (68 loc) · 1.74 KB
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
import time
import re
from light import Light
alphabet = {
'a': '.-',
'b': '-...',
'c': '-.-.',
'ch': '----',
'd': '-..',
'e': '.',
'f': '..-.',
'g': '--.',
'h': '....',
'i': '..',
'j': '.---',
'k': '-.-',
'l': '.-..',
'm': '--',
'n': '-.',
'o': '---',
'p': '.--.',
'q': '--.-',
'r': '.-.',
's': '...',
't': '-',
'u': '..-',
'v': '...-',
'w': '.--',
'x': '-..-',
'y': '-.--',
'z': '--..'
}
class InvalidMorseCodeException(Exception):
""" Exception for if a string does not consist of just dots and dashes """
class MorseCodeFlasher:
"""
Initialises with an instance of class Light and uses it to flash morse code messages
when flash_word or flash_code are called
"""
def __init__(self, a_beat: float, delay_between_letters: float, light: Light):
self.a_beat = a_beat
self.delay_between_letters = delay_between_letters
self.light = light
def __light_up_for(self, seconds: float):
self.light.on()
time.sleep(seconds)
self.light.off()
def __dash(self):
self.__light_up_for(6 * self.a_beat)
def __dot(self):
self.__light_up_for(self.a_beat)
def flash_code(self, code: str):
""" :param code: A string containing only full-stops (dots) and hypens (dashes) """
if re.match(r'[^.-]+', code) is not None:
raise InvalidMorseCodeException
for flash in code:
if flash == '.':
self.__dot()
elif flash == '-':
self.__dash()
def flash_word(self, word: str):
""" Translates each letter of the word into morse code and passes to flash_code() """
for letter in word:
code = alphabet[letter]
self.flash_code(code)
time.sleep(self.delay_between_letters)
self.light.finish()
print('Done')