-
Notifications
You must be signed in to change notification settings - Fork 0
/
wordsearch
executable file
·588 lines (496 loc) · 18.3 KB
/
wordsearch
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
#!/usr/local/bin/python3
# Wordsearch
#
# Copyright (c) 2022
# Pat Jensen (patj@passpackets.com)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# License: BSD-2-Clause
import os
import sys
import random
import curses
import getpass
import pickle
from operator import itemgetter
from datetime import date
from copy import deepcopy
from curses.textpad import rectangle
wsver = "2.2"
# Maximum number of rows and columns.
NMAX = 32
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
nrows = 15
ncols = 15
score = 0
theme = ''
def circle_mask(grid):
"""A circular mask to shape the grid."""
r2 = min(ncols, nrows)**2 // 4
cx, cy = ncols//2, nrows // 2
for irow in range(nrows):
for icol in range(ncols):
if (irow - cy)**2 + (icol - cx)**2 > r2:
grid[irow][icol] = '*'
def squares_mask(grid):
"""A mask of overlapping squares to shape the grid."""
a = int(0.38 * min(ncols, nrows))
cy = nrows // 2
cx = ncols // 2
for irow in range(nrows):
for icol in range(ncols):
if a <= icol < ncols-a:
if irow < cy-a or irow > cy+a:
grid[irow][icol] = '*'
if a <= irow < nrows-a:
if icol < cx-a or icol > cx+a:
grid[irow][icol] = '*'
def no_mask(grid):
"""The default, no mask."""
pass
# A dictionary of masking functions, keyed by their name.
apply_mask = {
None: no_mask,
'circle': circle_mask,
'squares': squares_mask,
}
def make_grid(mask=None):
"""Make the grid and apply a mask (locations a letter cannot be placed)."""
grid = [[' ']*ncols for _ in range(nrows)]
apply_mask[mask](grid)
return grid
def _make_wordsearch(nrows, ncols, wordlist, allow_backwards_words=True,
mask=None):
"""Attempt to make a word search with the given parameters."""
grid = make_grid(mask)
def fill_grid_randomly(grid):
"""Fill up the empty, unmasked positions with random letters."""
for irow in range(nrows):
for icol in range(ncols):
if grid[irow][icol] == ' ':
grid[irow][icol] = random.choice(alphabet)
def remove_mask(grid):
"""Remove the mask, for text output, by replacing with whitespace."""
for irow in range(nrows):
for icol in range(ncols):
if grid[irow][icol] == '*':
grid[irow][icol] = ' '
def test_candidate(irow, icol, dx, dy, word):
"""Test the candidate location (icol, irow) for word in orientation
dx, dy)."""
for j in range(len(word)):
if grid[irow][icol] not in (' ', word[j]):
return False
irow += dy
icol += dx
return True
def place_word(word):
"""Place word randomly in the grid and return True, if possible."""
# Left, down, and the diagonals.
dxdy_choices = [(0,1), (1,0), (1,1), (1,-1)]
random.shuffle(dxdy_choices)
for (dx, dy) in dxdy_choices:
if allow_backwards_words and random.choice([True, False]):
# If backwards words are allowed, simply reverse word.
word = word[::-1]
# Work out the minimum and maximum column and row indexes, given
# the word length.
n = len(word)
colmin = 0
colmax = ncols - n if dx else ncols - 1
rowmin = 0 if dy >= 0 else n - 1
rowmax = nrows - n if dy >= 0 else nrows - 1
if colmax - colmin < 0 or rowmax - rowmin < 0:
# No possible place for the word in this orientation.
continue
# Build a list of candidate locations for the word.
candidates = []
for irow in range(rowmin, rowmax+1):
for icol in range(colmin, colmax+1):
if test_candidate(irow, icol, dx, dy, word):
candidates.append((irow, icol))
# If we don't have any candidates, try the next orientation.
if not candidates:
continue
# Pick a random candidate location and place the word in this
# orientation.
loc = irow, icol = random.choice(candidates)
for j in range(n):
grid[irow][icol] = word[j]
irow += dy
icol += dx
# We're done: no need to try any more orientations.
break
else:
# If we're here, it's because we tried all orientations but
# couldn't find anywhere to place the word. Oh dear.
return False
# will use this later for scoring
# print(word, loc, (dx, dy))
return True
# Iterate over the word list and try to place each word (without spaces).
for word in wordlist:
word = word.replace(' ', '')
if not place_word(word):
# We failed to place word, so bail.
return None, None
# grid is a list of lists, so we need to deepcopy here for an independent
# copy to keep as the solution (without random letters in unfilled spots).
solution = deepcopy(grid)
fill_grid_randomly(grid)
remove_mask(grid)
remove_mask(solution)
return grid, solution
def make_wordsearch(*args, **kwargs):
"""Make a word search, attempting to fit words into the specified grid."""
# We try NATTEMPTS times (with random orientations) before giving up.
NATTEMPTS = 10
for i in range(NATTEMPTS):
grid, solution = _make_wordsearch(*args, **kwargs)
if grid:
# print('Fitted the words in {} attempt(s)'.format(i+1))
return grid, solution
print('I failed to place all the words after {} attempts.'
.format(NATTEMPTS))
return None, None
def show_grid_text(grid):
"""Output a text version of the filled grid wordsearch."""
for irow in range(nrows):
print(' '.join(grid[irow]))
def show_wordlist_text(wordlist):
"""Output a text version of the list of the words to find."""
for word in wordlist:
print(word)
def show_wordsearch_text(grid, wordlist):
"""Output the wordsearch grid and list of words to find."""
show_grid_text(grid)
print()
show_wordlist_text(wordlist)
def get_wordlist(wordlist_filename):
"""Read in the word list from wordlist_filename."""
wordlist = []
with open(wordlist_filename) as fi:
for line in fi:
# The word is upper-cased and comments and blank lines are ignored.
line = line.strip().upper()
if not line or line.startswith('#'):
continue
wordlist.append(line)
return wordlist
def listToString(s):
str1 = " "
return (str1.join(s))
def adjac(ele, sub = []):
if not ele:
yield sub
else:
# ele[0] - 1, ele[0] + 3
yield from [idx for j in range(ele[0] - 2, ele[0] + 3)
for idx in adjac(ele[1:], sub + [j])]
def puzzlepicker():
# Prefer local puzzles/ directory first, then try BSD paths
# /usr/local/share and /usr/pkg/share
picked = 0
wordlist_filename = ''
if (os.path.isdir("puzzles")):
wordlist_filename = 'puzzles/' + ''.join(random.choice(os.listdir("puzzles/")))
picked = 1
if (os.path.isdir("/usr/local/share/wordsearch")) and not picked == 1:
wordlist_filename = '/usr/local/share/wordsearch/' + ''.join(random.choice(os.listdir("/usr/local/share/wordsearch/")))
picked = 1
if (os.path.isdir("/usr/pkg/share/wordsearch")) and not picked == 1:
wordlist_filename = '/usr/pkg/share/wordsearch/' + ''.join(random.choice(os.listdir("/usr/pkg/share/wordsearch/")))
picked = 1
if not wordlist_filename:
curses.endwin()
print("Please make sure you have placed puzzle files in one of the following directories:")
print("puzzles/")
print("/usr/local/share/wordsearch/")
print("/usr/pkg/share/wordsearch/")
exit()
return wordlist_filename
def check_size(window):
height, width = window.getmaxyx()
if not height > 23 or not width > 79:
curses.endwin()
print("wordsearch requires an 80-column terminal to play.")
print("You are " + str(width) + "x" + str(height))
print("If you are using a windowed or virtual terminal, please resize your window to larger then 80x24.")
exit()
def scoreWrite():
HighscoreList = []
# No need to write a score if we didn't play a game
if (score == 0):
return()
# Capture user and score details
username = getpass.getuser()
today = date.today()
datestr = f"{today.month}/{today.day}/{today.year}"
# Open the high score if available
try:
with open('/var/tmp/wsscore', 'rb') as Highscorefile:
HighscoreList = pickle.load(Highscorefile)
except: pass
# Add high score to the score list
HighscoreList.append((username, score, datestr))
# Sort the score list by score and identify 10 scores
HighscoreList = sorted(HighscoreList, key=itemgetter(1), reverse=True)[:10]
# Write the last 10 scores to disk
with open('/var/tmp/wsscore', 'wb') as Highscorefile:
pickle.dump(HighscoreList, Highscorefile)
exit()
def scoreList():
HighscoreList = []
try:
with open('/var/tmp/wsscore', 'rb') as Highscorefile:
HighscoreList = pickle.load(Highscorefile)
print("wordsearch")
print("High Scores")
print()
print("Username Score Date")
for a in HighscoreList:
print(a[0]+" "+str(a[1])+" "+a[2])
except: pass
exit()
def Main(window):
mask = None
max_word_len = max(nrows, ncols)
scoreword = ''
global score
check_size(window)
wordlist_filename = puzzlepicker()
wordlist = sorted(get_wordlist(wordlist_filename), key=lambda w: len(w),
reverse=True)
if max(len(word) for word in wordlist) > max_word_len:
raise ValueError('Word list contains a word with too many letters.'
'The maximum is {}'.format(max(nrows, ncols)))
allow_backwards_words = False
grid, solution = make_wordsearch(nrows, ncols, wordlist, allow_backwards_words,
mask)
width = 80
height = 24
# Set up coordinates to track scoring and completed words
adjacent = 0
duplicate = 0
ScoreList = []
CompletedList = []
# Initialize curses. If we can't set cursor modes, continue
try:
curses.curs_set(2)
except: pass
# Theme picker. If we can't set color modes, continue
try:
if (theme == "green"):
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
if (theme == "black"):
curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK)
if (theme == "red"):
curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_RED)
if (theme == "blue"):
curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
if (theme == "purple"):
curses.init_pair(1, curses.COLOR_MAGENTA, curses.COLOR_BLACK)
if not theme:
curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
window.bkgd(' ', curses.color_pair(1))
except: pass
# Render background UX
window.hline(0, 0, " ", width, curses.A_REVERSE)
category = (os.path.basename(wordlist_filename)).replace(".txt", "")
window.addstr(0, 0, category.center(width, ' '), curses.A_REVERSE)
window.addstr(0, 0, " wordsearch", curses.A_REVERSE)
# Render new score
scoretext = "Score: " + str(score)
sx = width - 9
sx = sx - len(str(score))
window.addstr(0, sx, scoretext, curses.A_REVERSE)
# Draw search box
rectangle(window, 2, 24, 18, 54)
# Render word search surface
startrow = 3
startcol = 25
for irow in range(nrows):
puzrow = ' '.join(grid[irow])
window.addstr(startrow, startcol, puzrow);
startrow = startrow + 1
# Render word hint list
wordlistdisp = listToString(wordlist)
window.addstr(20, 0, wordlistdisp.center(width, ' '))
# Render navigational directions
window.addstr(23, 0, "Arrow keys to navigate. Space: Select, Return: Clear, Q: Quit")
# Move on to puzzle surface
window.move(10, 37)
# Main event loop
key = window.getch()
while True:
if key == ord('q'):
curses.endwin()
scoreWrite()
scoreList()
exit()
if key == curses.KEY_UP or key == ord('k'):
cy, cx = curses.getsyx()
if not cy < 4:
try:
window.move(cy-1, cx)
except:
curses.beep()
window.refresh()
elif key == curses.KEY_DOWN or key == ord('j'):
cy, cx = curses.getsyx()
if not cy > 16:
try:
window.move(cy+1, cx)
except:
curses.beep()
window.refresh()
elif key == curses.KEY_LEFT or key == ord('h'):
cy, cx = curses.getsyx()
if not cx < 27:
try:
window.move(cy, cx-2)
except:
curses.beep()
window.refresh()
elif key == curses.KEY_RIGHT or key == ord('l'):
cy, cx = curses.getsyx()
if not cx > 52:
try:
window.move(cy, cx+2)
except:
curses.beep()
window.refresh()
elif key == curses.KEY_RESIZE:
maxy, maxx = window.getmaxyx()
window.resize(maxy, maxx)
window.clear()
window.bkgd(' ', curses.color_pair(1))
window.hline(0, 0, " ", maxx, curses.A_REVERSE)
category = (os.path.basename(wordlist_filename)).replace(".txt", "")
window.addstr(0, 0, category.center(width, ' '), curses.A_REVERSE)
window.addstr(0, 0, " wordsearch", curses.A_REVERSE)
scoretext = "Score: " + str(score)
sx = maxx - 9
sx = sx - len(str(score))
window.addstr(0, sx, scoretext, curses.A_REVERSE)
wordlistdisp = listToString(wordlist)
window.addstr(20, 0, wordlistdisp.center(maxx, ' '))
window.addstr(maxy-1, 0, "Arrow keys to navigate. Space: Select, Return: Clear, Q: Quit")
window.move(10, 37)
window.refresh()
# Return to wipe
elif key == 10:
cy, cx = curses.getsyx()
# Check scored coordinates to make sure we dont wipe completed items
for cord in ScoreList:
if cord not in CompletedList:
wipeint = window.inch(cord[0], cord[1])
wipechar = wipeint & 0xFF
window.addch(cord[0], cord[1], wipechar)
# Clear scoreword and ScoreList to start over
ScoreList.clear()
window.addstr(10, 60, " ")
scoreword = ''
window.move(cy, cx)
# Space to score
elif key == ord(' '): # space bar
cy, cx = curses.getsyx() # get y/x
cur = [cy, cx]
cur2 = (cy, cx)
duplicate = 0
# Check for existing ScoreList, then check if we are y +/- 1, or x +/- 2 away
if ScoreList:
# Get list of adjacencies
res = list(adjac(ScoreList[-1]))
for member in res:
if cur in res:
adjacent = 1
else:
adjacent = 0
curses.beep()
curses.beep()
curses.beep()
else:
adjacent = 1
# Check for existing ScoreList, then check if this character is in it already
if ScoreList:
if cur2 in ScoreList:
curses.beep()
duplicate = 1
if adjacent == 1 and not duplicate == 1:
# Add coords for each letter we are adding
ScoreList.append((cy, cx))
# Find cursor and see if we have character match
scoreint = window.inch(cy, cx)
scorechar = scoreint & 0xFF
scoreword = ''.join([scoreword, chr(scorechar)])
window.addstr(10, 60, scoreword)
# Now let's check for a word match
for word in wordlist:
if (word == scoreword) or (word == scoreword[::-1]):
# Increase score based on number of chars
score = score + len(word)
# Render new score
scoretext = "Score: " + str(score)
sx = width - 9
sx = sx - len(str(score))
window.addstr(0, sx, scoretext, curses.A_REVERSE)
# Reset settings for next word and clear buffer
window.addstr(10, 60, " ")
scoreword = ''
# Let's remember the coords for this set
CompletedList.append(ScoreList)
# Reset the scoring list
ScoreList.clear()
# Clear word from word list and redraw word list
wordlist.remove(word)
wordlistdisp = listToString(wordlist)
window.addstr(20, 0, wordlistdisp.center(width, ' '))
# Did we win?
if not wordlist:
winstr = "Congratulations! Press any key for a new game."
window.addstr(20, 0, winstr.center(width, ' '))
key = window.getch()
Main(window)
window.addstr(cy, cx, chr(scorechar), curses.A_REVERSE) # highlight char
window.move(cy, cx) # move back on board
key = window.getch()
# Initalize wordsearch
opts = [opt for opt in sys.argv[1:] if opt.startswith("-")]
args = [arg for arg in sys.argv[1:] if not arg.startswith("-")]
if "-v" in opts:
print(f"Wordsearch {wsver}")
print("Copyright (c) 2022 Pat Jensen")
print("All rights reserved.")
print()
print("Redistribution and use in source and binary forms, with or without")
print("modification, are permitted provided that the following conditions are met:")
print()
print("1. Redistributions of source code must retain the above copyright notice, this")
print(" list of conditions and the following disclaimer.")
print()
print("2. Redistributions in binary form must reproduce the above copyright notice,")
print(" this list of conditions and the following disclaimer in the documentation")
print(" and/or other materials provided with the distribution.")
print()
exit()
if "-s" in opts:
scoreList()
exit()
if "-h" in opts:
print(f"Usage: {sys.argv[0]} (-v | -s | -h) (-t red|blue|black|green|purple)")
exit()
if "-t" in opts:
theme = sys.argv[2]
# Start curses and go to main
curses.wrapper(Main)