-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgenerate-bingo-boards
executable file
·317 lines (268 loc) · 11.4 KB
/
generate-bingo-boards
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
#!/usr/bin/python3
import os
from argparse import Namespace
import sys
major, minor, maint, _, _ = sys.version_info
if major < 3 or (major == 3 and minor < 9):
print("Python 3.9 minimum required. You ran with:")
print(sys.version)
exit(1)
class Env:
""" Helpful stuff """
script_dir = os.path.dirname(os.path.abspath(__file__))
output_folder = os.path.join(script_dir, 'output')
dictionary_folder = os.path.join(script_dir, 'dictionaries')
config_folder = os.path.join(script_dir, 'config')
header = 'Here are your bingo boards! Print this page out or open it in a text editor! Fill out the spaces as people say the words!'
footer = 'Generated with love using github.com/calvincramer/covid-bingo'
footer_html = 'Generated with love using <a href="https://github.com/calvincramer/covid-bingo">github.com/calvincramer/covid-bingo</a>'
def empty_output_folder() -> None:
""" Clear all contents from the output folder """
import shutil
if os.path.exists(Env.output_folder):
shutil.rmtree(Env.output_folder)
os.mkdir(Env.output_folder)
def read_dictionary(config: dict[str, object]) -> list[str]:
"""
Read input dictionary of words from file.
:return: list of tuples of words and their frequency
"""
with open(config['Dictionary']) as fp:
lines = fp.readlines()
lines = [l.strip() for l in lines]
lines = list(set(lines)) # Remove duplicate words
return lines
def read_config_file(args: Namespace) -> dict[str, object]:
"""
Read configuration file
:return: dictionary of keys and values
"""
import configparser
def to_int(s: str) -> int:
try:
return int(s)
except Exception as e:
raise e
config_parser = configparser.ConfigParser()
config_parser.read(args.config_file)
# Gather values into dictionary
config = {}
config['Dictionary'] = config_parser['MAIN']['Dictionary']
config['People'] = config_parser['MAIN']['People']
config['BoardsPerPerson'] = config_parser['MAIN']['BoardsPerPerson']
config['BoardWidth'] = config_parser['MAIN']['BoardWidth']
config['BoardHeight'] = config_parser['MAIN']['BoardHeight']
config['FreeCenter'] = config_parser['MAIN']['FreeCenter']
# Parse values
config['Dictionary'] = os.path.join(Env.dictionary_folder, config['Dictionary'])
if not os.path.exists(config['Dictionary']) or not os.path.isfile(config['Dictionary']):
raise ValueError(f"Dictionary file does not exist {config['Dictionary']}")
config['People'] = list(set(p.strip() for p in config['People'].split(',')))
config['BoardsPerPerson'] = to_int(config['BoardsPerPerson'])
config['BoardWidth'] = to_int(config['BoardWidth'])
config['BoardHeight'] = to_int(config['BoardHeight'])
config['FreeCenter'] = config['FreeCenter'].lower() in ['yes', 'true']
return config
def parse_cmd_args() -> Namespace:
"""
Parse CLI arguments
:return:
"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--config_file", default='default-config.ini', help="Config file to use")
args = parser.parse_args()
args.config_file = os.path.join(Env.config_folder, args.config_file)
# Check the config file exists
if not os.path.exists(args.config_file) or not os.path.isfile(args.config_file):
raise(ValueError(f'Config file {args.config_file} does not exist'))
return args
def generate_board(config: dict[str, object], dictionary: list[str]) -> list[list[str]]:
""" Generate a single board """
import copy
from random import shuffle
width = config['BoardWidth']
height = config['BoardHeight']
if width * height > len(dictionary):
raise ValueError(f'The dictionary needs more words! At least {width * height} words please!')
words = copy.deepcopy(dictionary)
shuffle(words)
words = words[0: width * height] # Cut off words to make a board
if config['FreeCenter']:
words[len(words) // 2] = 'FREE!'
# Convert 1D list to 2D board
def reshape(_list, _lengths):
index = 0
for _len in _lengths:
yield _list[index: index + _len]
index += _len
return list(reshape(words, [width] * height))
def board_to_string(board: list[list[str]]) -> tuple[str, int]:
"""
Board to fancy string
:param board: a single 2D board of words
:return: tuple of string representation board, and width in characters of the board
"""
corner_char = '+'
vertical_border_char = '|'
horizontal_border_char = '-'
max_char_word = max(max(len(word) for word in line) for line in board)
interior_width = max_char_word + 2 # Two spaces
interior_height = int(interior_width * 0.3) # Height in chars is some percentage of width
interior_height = max(3, interior_height)
if interior_height % 2 == 0: # Make height odd
interior_height += 1
num_empty_rows_above_below = (interior_height - 1) // 2
# Generate row
def get_row() -> str:
s = ''
for _ in range(len(board[0])):
s = f'{s}{corner_char}{horizontal_border_char * interior_width}'
return s + corner_char + '\n'
# Empty rows
def get_empty_row() -> str:
s = ''
for _ in range(len(board[0])):
s = f'{s}{vertical_border_char}{" " * interior_width}'
return s + vertical_border_char + '\n'
# Row with words
def get_row_words(words) -> str:
s = ''
for word in words:
s = f'{s}{vertical_border_char}{word:^{interior_width}}'
return s + vertical_border_char + '\n'
board_str = ''
for row in board:
board_str += get_row() # Row border
board_str += get_empty_row() * num_empty_rows_above_below # Empty rows
board_str += get_row_words(row) # Rows with words
board_str += get_empty_row() * num_empty_rows_above_below # Empty rows
board_str += get_row() # Last row border
return board_str, len(get_row())
def board_strings_to_whole_file(board_strs: list[str], max_board_width: int) -> str:
def section_separator() -> str:
return '\n\n\n'
def board_header(board_name: object) -> str:
return f'##### BOARD {str(board_name)} #####'
max_width = max(len(Env.header), len(Env.footer), max_board_width)
s = ''
s += f'{Env.header:^{max_width}}'
s += section_separator()
for i, board_str in enumerate(board_strs):
# Board header
s += f'{board_header(i+1):^{max_width}}\n'
# Print board centered
board_lines = board_str.split('\n')
for board_line in board_lines:
s += f'{board_line:^{max_width}}\n'
s += section_separator()
s += f'{Env.footer:^{max_width}}\n'
return s
def boards_to_html(boards: list[list[list[str]]]) -> str:
""" Board to html page """
# Read template file
template = open(os.path.join(Env.script_dir, 'template.html'), 'r').read()
def get_tables() -> str:
text = ''
for i, board in enumerate(boards):
text += f'<div><table><caption>Board {i+1}</caption>\n'
for row_num, row in enumerate(board):
text += '<tr>\n'
for col_num, elm in enumerate(row):
text += f'<td><button id="t{i}r{row_num}c{col_num}">{elm}</button></td>\n'
text += '</tr>\n'
text += '</table></div>\n'
return text
def get_js_buttons() -> str:
text = """
var func_click = function() {
var button_pressed = document.getElementById(this.id);
if (button_pressed.classList.contains("selected")) {
button_pressed.classList.remove("selected");
}
else {
button_pressed.classList.add("selected");
}
}
var toggle_dark = function() {
if (document.body.classList.contains("dark")) {
document.body.classList.remove("dark");
} else {
document.body.classList.add("dark");
}
}
"""
for i, board in enumerate(boards):
for row_num, row in enumerate(board):
for col_num, elm in enumerate(row):
text += f"document.getElementById('t{i}r{row_num}c{col_num}').onclick = func_click;"
return text
"""
var func_click = function() {{
var button_pressed = document.getElementById(this.id);
if (button_pressed.style.backgroundColor == "rgb(0, 137, 0)") {{
button_pressed.style.backgroundColor = "black";
button_pressed.style.color = "white";
}}
else {{
button_pressed.style.backgroundColor = "rgb(0, 137, 0)";
button_pressed.style.color = "white";
}}
}}
document.getElementById('a1').onclick = func_click;
document.getElementById('2').onclick = func_click;
document.getElementById('3').onclick = func_click;
document.getElementById('4').onclick = func_click;
document.getElementById('5').onclick = func_click;
document.getElementById('6').onclick = func_click;
document.getElementById('7').onclick = func_click;
document.getElementById('8').onclick = func_click;
document.getElementById('9').onclick = func_click;
"""
return template.format(
header=Env.header,
footer=Env.footer_html,
tables=get_tables(),
javascriptButtons=get_js_buttons(),
)
def person_name_to_folder_name(name: str) -> str:
return name.replace(' ', '_')
def generate_stuff_for_everyone(config: dict[str, object], dictionary: list[str]):
""" Generate all the boards for everyone """
for person in config['People']:
# Make folder
folder_name = person_name_to_folder_name(person)
folder_name = os.path.join(Env.output_folder, folder_name)
os.mkdir(folder_name)
os.chdir(folder_name)
# Generate N boards for them
boards = [generate_board(config, dictionary) for _ in range(config['BoardsPerPerson'])]
# Generate string representation of boards
board_strings = []
board_widths = []
for b in boards:
board_str, board_width = board_to_string(b)
board_strings.append(board_str)
board_widths.append(board_width)
max_board_width = max(board_widths)
# Save board strings as text file
board_strings_whole = board_strings_to_whole_file(board_strings, max_board_width)
file_name = os.path.join(folder_name + os.path.sep, f'{os.path.basename(folder_name)}_all_boards.txt')
with open(file_name, 'w') as fp:
fp.write(board_strings_whole)
# Save boards as html files
html_text = boards_to_html(boards)
file_name = os.path.join(folder_name + os.path.sep, f'{os.path.basename(folder_name)}_all_boards.html')
with open(file_name, 'w') as fp:
fp.write(html_text)
# Generate / send email
# TODO: future work
def main():
print('Generating...')
args = parse_cmd_args()
config = read_config_file(args)
empty_output_folder()
generate_stuff_for_everyone(config, read_dictionary(config))
print('Generated all files to "output" directory')
if __name__ == '__main__':
main()