-
Notifications
You must be signed in to change notification settings - Fork 0
/
crosswordGenerator.py
923 lines (735 loc) · 34.6 KB
/
crosswordGenerator.py
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
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
# ----------------------------------------------------------------------------
# Crossword - Simple Crossword generator for CTFs
# Copyright (c) 2011 Daniel Nögel
# Copyright (c) 2019 Doug Swartz
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------
# The original program generated crosswords specifically designed
# for the javascript and HTML crossword system in this package.
# ----------------------------------------------------------------------------
import os
import glob
import sys
import random
import re
import time
import string
import copy
from optparse import OptionParser, OptionGroup
import logging
## This program builds on the work of Daniel Nö and Bryan Helmig
# The notice below appears in the Daniel's version of the code
# located at https://github.com/dnoegel/crossword-generator
## Thanks Bryan Helmig for his inspiration for this script. He did a lot
# of work which I could improve in some ways.
# See http://bryanhelmig.com/python-crossword-puzzle-generator/ for his
# code.
## With Bryan's permission this code is released under GPLv3
## Define some Exceptions
class SolutionError(Exception):
pass
class TimeOutError(Exception):
pass
class WordListError(Exception):
pass
class MaxLoopError(Exception):
pass
def stats(cwd, print_missing=True):
"""Print some infos about a given crossword."""
## How many words have been placed?
print(len(cwd.placed_words), 'out of', len(cwd.wordlist))
## Which words couldn't be placed?
if print_missing:
tmplist = [w.word.lower() for w in cwd.placed_words]
missing = [w.word for w in cwd.wordlist if w.word.lower() not in tmplist]
print("Missing words: '%s'" % missing)
## Number of rounds (--)
print("Needed %i rounds" % cwd.counter)
## average number of crosses per word
score = float(cwd.score)
print("%f crosses per word" % (float(score-len(cwd.placed_words))/len(cwd.placed_words)))
## Empty and filled cells / Empty-cell-quotient
num_cells = float(cwd.cols * cwd.rows)
num_letters = sum(w.length for w in cwd.placed_words)
num_empty = num_cells - num_letters
print("total-cells/empty-cells- Quotient: %.1f/1 (%i, %i)" % (round(num_cells/num_empty, 1), num_cells, num_empty))
class SimpleParser(object):
"""A simple parser for .cwf files
Actually it's a veeeeeery simple .ini parser. But it ignores letter-cases
which most other parser do not.
"""
def __init__(self, filename=None):
self.dict = {}
if filename:
print("Options file name: '%s'" % filename )
self.parse(filename)
def get_questions(self, num=None):
"""Returns a list of (answer, question) tuples
--num Number of questions. Default: None = All
"""
if num is None or num == 0:
return self.dict["questions"]
else:
return self.dict["questions"][:num]
def get_option(self, option):
"""Get the value of a given options from the options-section"""
return self.dict["options"][option]
def has_option(self, option):
"""True/False depending on if the given options exists or not"""
return option in self.dict["options"]
def parse(self, filename):
"""Parse the given file"""
section = None
with open(filename, "r") as fh:
#~ content = [line.replace() for line in fh]
content = fh.read().split("\n")
## First pass: Just get the sections and options!
for line in content:
rg = re.match(r"\s*\[(\w.*)\]", line) ## Matches a section
if rg:
# Set current section
section = rg.group(1).strip().lower()
if not section in self.dict and section == "options":
self.dict[section] = {}
elif not section in self.dict:
self.dict[section] = []
elif re.match(r"\A\s*\Z", line):
# Ignore blank lines
pass
elif section == "options":
rg = re.match(r"\s*(?P<key>.+?)[ \t]*?[:=][ \t]*(?P<value>.+)", line) # Match key = value
if rg:
if rg.group("key").strip().lower() == "question first":
self.dict[section]["question first"] = rg.group("value").lower().strip().startswith("t")
else:
self.dict[section][rg.group("key").strip().lower()] = rg.group("value").strip()
if not "options" in self.dict:
self.dict["options"] = {}
if not "question first" in self.dict["options"]: self.dict["options"]["question first"] = True
## Second pass: Get the questions
section = None
for line in content:
rg = re.match(r" *\[(\w.*)\]", line)
if rg:
# Set current section
section = rg.group(1).strip().lower()
elif re.match(r"\A\s*\Z", line):
# Ignore blank lines
pass
#~ elif section == None:
#~ pass
elif section != "options":
print('question line:', line)
rg = re.match(r"\s*(?P<key>.+?)[ \t]*?[:=][ \t]*(?P<value>.+)", line)
if rg:
if self.dict["options"]["question first"]:
self.dict[section].append((rg.group("value").strip(), rg.group("key").strip()))
else:
self.dict[section].append((rg.group("key").strip(), rg.group("value").strip()))
class CrossWordFormatter(object):
"""Formatting Crosswords
This class manages the various ways of crossword-output. Do you want
it as html, text, solved or unsolved?"""
def __init__(self, crossword, solution=None):
self.crossword = crossword
self.crossword._number_words()
self.solution_letters = {}
if solution:
self._set_solution(solution.lower())
else:
self.solution=None
def get_crossword_html_grid(self, filename):
"""Writes an html file
"""
for word in self.crossword.placed_words:
self.crossword._write_cell(word.col, word.row, word.number)
html = """<html>
<head>
<style type="text/css">
;table { width:100%; }
td { border-spacing: 2px 2px;border:0px solid #000; vertical-align:middle; text-align:center; width:15; height:15; }
#box { border:1px solid #000; vertical-align:middle; text-align:center; width:15; height:15; }
</style>
</head>
<body>"""
html += "<table>"
for row in range(self.crossword.rows):
html += "<tr>"
for cell in self.crossword.grid[row]:
if isinstance(cell, int):
html += "<td id=\"box\"><small>%s</small></td>" % cell
elif cell == self.crossword.empty:
html += "<td>%s</td>" % cell
else :
html += "<td id=\"box\"><small> </small></td>"
html += "</tr>"
html += "</table></body></html>"
for word in self.crossword.placed_words:
self.crossword._write_cell(word.col, word.row, word.word[0])
with open(filename, "w") as fh:
fh.write(html)
return html
def _set_solution(self, solution):
"""Checks if enough letters are available for the given solution
and put those letters into an list"""
highlight_color_number = 0
while " " in solution:
solution = solution.replace(" ", " ")
self.solution = solution
for letter in solution:
if letter == " ":
highlight_color_number += 1
continue
if not letter in self.crossword.letters or self.crossword.letters[letter] == []:
raise SolutionError("Cannot mark solution-letter '%s': No '%s' in this crossword" % (letter, letter))
if solution.count(letter) > len(self.crossword.letters[letter]):
raise SolutionError("Your solution '%(solution)s' has %(num)i '%(letter)s' - there are not that much '%(letter)s's in your crosssword!" % {"num":solution.count(letter), "letter":letter, "solution":solution})
entry = random.choice(self.crossword.letters[letter])
while entry in self.solution_letters:
entry = random.choice(self.crossword.letters[letter])
self.solution_letters[entry] = highlight_color_number
col,row = entry
def get_wordfind_ascii_grid(self, printable):
"""Returns a word-find ascii grid"""
if printable:
printstr = " "
else:
printstr = ""
outStr = ""
for r in range(self.crossword.rows):
for c in self.crossword.grid[r]:
if c == self.crossword.empty:
outStr += '%s%s' % (string.lowercase[random.randint(0,len(string.lowercase)-1)], printstr)
else:
outStr += '%s%s' % (c, printstr)
outStr += '\n'
return outStr
def get_crossword_ascii_cues(self):
"""Returns the crossword's questions"""
across_str = "Across:\n"
down_str = "Down:\n"
for word in self.crossword.placed_words:
if word.vertical:
down_str += "%d: %s\n" % (word.number, word.clue)
else:
across_str += "%d: %s\n" % (word.number, word.clue)
return "%s\n\n%s" % (across_str, down_str)
def get_crossword_js_html_cues(self):
"""Returns the crossword's questions in horizontal and veritcal divisions"""
across_str = "<h1>Across:</h1>\n"
down_str = "<h1>Down:</h1>\n" # Down and across are bacward!!
for word in self.crossword.placed_words:
textNumber = format(word.sequence_number, 'x')
if word.vertical:
across_str += ("<div> <label for ='" + textNumber + "'> " + textNumber + ". %s </div>\n" % ( word.clue))
else:
down_str += ("<div> <label for ='" + textNumber + "'> " + textNumber + ". %s </div>\n" % ( word.clue))
return "<div> %s </div> <div class='vertical_line'></div> \n<div>\n%s </div>" % (across_str, down_str)
def get_crossword_ascii_grid(self, solved = False, printable=False):
"""Returns a crossword grid with numbers"""
if printable:
printstr = " "
else:
printstr = ""
outStr = ""
if not solved:
for word in self.crossword.placed_words:
self.crossword._write_cell(word.col, word.row, word.number)
for r in range(self.crossword.rows):
for c in self.crossword.grid[r]:
outStr += '%s%s' % (c, printstr)
outStr += '\n'
if not solved:
for word in self.crossword.placed_words:
self.crossword._write_cell(word.col, word.row, word.word[0])
if not solved:
outStr = re.sub(r'[a-z]', '_', outStr)
return outStr
def get_crossword_javascript_grid(self, solved=False):
"""Returns a crossword grid defined as a javascript variable"""
def write_buffer_line(outStr):
outStr += ' ",_,_,'
for c in self.crossword.grid[0]:
outStr += '_,'
outStr += '_,_,",\n'
return outStr
outStr = 'grid = [\n'
outStr = write_buffer_line(outStr)
outStr = write_buffer_line(outStr)
for r in range(self.crossword.rows):
outStr += ' ",_,_,'
for c in self.crossword.grid[r]:
outchar = ' '
if solved:
outchar = c
if c == ' ':
outchar = '_'
outStr += '%s,' % (outchar)
outStr += '_,_,",\n'
outStr = write_buffer_line(outStr)
outStr = write_buffer_line(outStr)
outStr += ' ];'
return outStr
class CrossWord(object):
"""The crossword objects represents a crossword"""
def __init__(self, cols, rows, empty = '_', maxloops = 2000, wordlist=[]):
"""Initialize the crossword. Notice: This will also be used to create
a copy of the original crossword. For this reason there is some
wordlist-"magic" in here."""
if len(wordlist) < 3:
raise WordListError("Need at least 3 entries!")
if cols =="auto" or rows == "auto":
if wordlist != [] and isinstance(wordlist[0], tuple):
longest = max(wordlist, key=lambda i: len(i[0]))[0]
average = sum([len(w[0]) for w in wordlist])/len(wordlist)
#~ elif isinstance(wordlist[0], str):
#~ longest = max(wordlist, key=lambda i: len(i))
#~ average = sum(wordlist)/len(wordlist)
elif wordlist != []:
print(type(wordlist[0]))
raise WordListError("Wordlist must contain strings or tuples!")
min_length = len(longest)
#~ if not reduce:
logging.debug("'%s': %i - Average: %i" % (longest, min_length, average))
size = int(((average*len(wordlist)*4)**0.5))
if len(wordlist) > 75:
size = int(size*0.8)
while size <= min_length:
size += 1
if cols == "auto":
cols = size
if rows == "auto":
rows = size
logging.debug("Grid size: %ix%i" % (cols, rows))
self.cols = cols
self.rows = rows
self.empty = empty
self.maxloops = maxloops
self.wordlist = wordlist
self.placed_words = []
self.counter = 0
self._setup_grid_and_letters()
self.score = -1
def _setup_grid_and_letters(self):
"""Initialize / clear grid and letters"""
## Create the grid and fill it with empty letters
self.grid = []
for i in range(self.cols):
col = []
for j in range(self.rows):
col.append(self.empty)
self.grid.append(col)
## Create our letter-dict
self.letters = {}
for letter in string.ascii_lowercase: self.letters[letter]=[]
## In "double" we'll put those coords which already are used
# by two words (cross). So we do not check coords, that are already
# occupied.
self.letters["double"]=[]
## Sort the wordlist by length. Words with same length will be
# shuffled in order.
tmplist = []
for word in self.wordlist:
if isinstance(word, Word):
tmplist.append(Word(word.word, word.clue))
else:
tmplist.append(Word(word[0], word[1]))
random.shuffle(tmplist)
tmplist.sort(key=lambda i: len(i.word), reverse=True)
self.wordlist = tmplist
def compute_crossword(self, rounds=2, best_of=3, force_solved=False):
"""Compute possible crosswords
-- rounds: How often sould be tried to place a word? (Default: 2)
-- best_of: Creates the given number of crosswords and keeps the
crossword with the best score (Default: 3)
-- force_solved Generate grids until every word from the wordlists
fits. (Default: False).
"""
copy = CrossWord(self.cols, self.rows, self.empty, self.maxloops, [(w.word, w.clue) for w in self.wordlist])
best_score = 0
count = 0
solved = False
while (count<=best_of-1 and not force_solved) or (force_solved and not solved):
self.counter += 1
logging.debug("Round %i" % count)
score = 0
copy.placed_words = []
copy._setup_grid_and_letters()
## Try to fit all the words from the wordlist onto the grid
x = 1
while x < rounds:
for word in copy.wordlist:
if word not in copy.placed_words:
#~ raw_input()
word_score = copy._place_word(word)
score += word_score
x += 1
## Check if the copy-crossword is "better" than the original.
if (len(copy.placed_words) >= len(self.placed_words) and score >= best_score) or len(copy.placed_words) > len(self.placed_words):
self.placed_words = copy.placed_words
self.wordlist = copy.wordlist
self.grid = copy.grid
self.letters = copy.letters
self.cols = copy.cols
self.rows = copy.rows
best_score = score
## If all words are on the list the crossword is "solved"
if len(copy.placed_words) == len(copy.wordlist):
solved = True
else:
solved = False
count += 1
if force_solved and count >= self.maxloops:
raise MaxLoopError("Could not solve the crossword within %i tries" % self.maxloops)
self.score = best_score
return best_score
def _get_possible_coords(self, word):
"""Generates a list of possible coords.
Any cell containing a letter of the word will be saved as a possible hit
if the word would fit at that position without leaving the grid-bounds.
Additional checking is done later.
"""
coordlist = []
## optimizations
letters = self.letters
cols = self.cols
rows = self.rows
word_str = word.word
word_length = len(word_str)
_get_score = self._get_score
letterpos = -1
#~ for letterpos, letter in enumerate(word.word): ## Enumerate seems to be slower sometimes
for letter in word_str:
letterpos += 1
try:
coords = letters[letter]
except KeyError:
coords = []
for col, row in coords:
## VERTICAL
if row - letterpos > 0:
if ((row - letterpos) + word_length) <= rows:
score = _get_score(col, row - letterpos, 1, word)
if score:
coordlist.append((col, row - letterpos, 1, score))
## HORIZONTAL
if col - letterpos > 0:
if ((col - letterpos) + word_length) <= cols:
score = _get_score(col - letterpos, row, 0, word)
if score:
coordlist.append((col - letterpos, row, 0, score))
## The same trick as in the '_randomize_wordlist' methode:
# The list needs to be sorted (this time by score) but coords
# with the same score may be shuffled and will lead to
# different crosswords each time.
random.shuffle(coordlist)
coordlist.sort(key=lambda i: i[3], reverse=True)
return coordlist
def _place_word(self, word):
"""Put a word onto the grid.
The first word will be put at random coords, the following words
will be placed by match-score."""
placed = False
count = 0
score = 0
if len(self.placed_words) == 0:
while not placed and count <= self.maxloops:
## Place the first word at fixed coords
vertical, col, row = random.randrange(0, 2), 1, 1
## Place the first word in the middle of the grid
if vertical:
col = int(round((self.cols + 1) / 2, 0))
row = int(round((self.rows + 1) / 2, 0)) - int(round((len(word.word) + 1) / 2, 0))
if row+len(word.word) > self.rows:
row = self.rows - len(word.word) + 1
else:
col = int(round((self.cols + 1) / 2, 0)) - int(round((len(word.word) + 1) / 2, 0))
row = int(round((self.rows + 1) / 2, 0))
if col+len(word.word) > self.cols:
col = self.cols - len(word.word) + 1
## Random place the first word
#~ col = random.randrange(1, self.cols + 1)
#~ row = random.randrange(1, self.rows + 1)
if self._get_score(col, row, vertical, word):
placed = True
self._write_word(col, row, vertical, word)
return 0
count += 1
else:
coordlist = self._get_possible_coords(word)
try:
col, row, vertical, fit_score = coordlist[0]
except IndexError:
## If there are no coords, don't place the word and
## return 0 (score)
return 0
score += fit_score
self._write_word(col, row, vertical, word)
if count >= self.maxloops:
raise MaxLoopError("Maxloops reached - canceling (Counter: %i, Word: %s)" % (count, word.word))
return score
def _get_score(self, col, row, vertical, word):
"""Calculate the placement-score of a word for the given coords
Return:
-- 0 No coord fits
-- 1 coord fits - but no cross
-- n n-1 crosses"""
## optimizations
empty = self.empty
_is_empty = self._is_empty
_read_cell = self._read_cell
grid = self.grid
if col < 1 or row < 1:
return 0
score = 1
letterpos = 0
lastletter = empty
#~ for letterpos, letter in enumerate(word.word): ## Enumerate is much(!) slower
for letter in word.word:
letterpos += 1
try:
active_cell = grid[col-1][row-1]#_read_cell(col, row)
except IndexError:
return 0
## Still not ideal, but this prevents the code from placing
# a word like "nose" over an already placed word like "nosebear"!
# This is quite a big issue - so this part really should kept.
#
# Another approach would be, to check for each cell if it
# already contains a letter, which is written in the same
# direction as our word. e.g.:
# The active_cell holds an 'e', also our word has an 'e'.
# If the 'e' of the active_cell belongs to a vertical word
# and our word is also going to be placed vertically, a match
# is not possible as we would overwrite the old world.
# If the active_cell belongs to a horizontal word, a cross
# would be possible. The downside of this approach: We'd
# need an additional dict/list for that info, it would be slower
if lastletter != empty and active_cell != empty:
return 0
lastletter = active_cell
## In words: If the letter of the current cell does not
# match the current letter of our word, the word doesn't
# fit!
if active_cell != empty and active_cell != letter:
#~ if active_cell != empty and letterpos != matching_letter: ## This will disallow words to be overwritten but it will also disallow multiple matches within one word
return 0
elif active_cell == letter:
score += 1
#
# Check for neighbours
#
if vertical:
## Only check for non-crosses
if active_cell != letter:
# right
if not _is_empty(col+1, row):
return 0
# left
if not _is_empty(col-1, row):
return 0
## Only check first and last letter in vertical mode
# for top/bottom neighbours.
if letterpos == 1:
if not _is_empty(col, row-1):
return 0
if letterpos == len(word.word):
if not _is_empty(col, row+1):
return 0
else:
## Only check for non-crosses
if active_cell != letter:
# top
if not _is_empty(col, row-1):
return 0
# bottom
if not _is_empty(col, row+1):
return 0
## In horizontal mode only the first and last letter
# are not allowed to have horizontal neighours
if letterpos == 1:
if not _is_empty(col-1, row):
return 0
if letterpos == len(word.word):
if not _is_empty(col+1, row):
return 0
if vertical:
row += 1
else:
col += 1
return score
def _write_word(self, col, row, vertical, word):
"""Write a word to the grid and add it to the placed_words list"""
word.col = col
word.row = row
word.vertical = vertical
self.placed_words.append(word)
for letter in word.word:
self._write_cell(col, row, letter)
if vertical:
row += 1
else:
col += 1
return
def _write_cell(self, col, row, letter):
"""Set a cell on the grid to a given letter"""
try:
if not (col, row) in self.letters[letter]:
self.letters[letter].append((col, row))
else:
## Remove coords from the list, if they already
# contain a cross. This way we do less double-checking.
self.letters[letter].remove((col, row))
self.letters["double"].append((col, row))
except KeyError:
self.letters[letter] = []
self.letters[letter].append((col, row))
self.grid[col-1][row-1] = letter
def _read_cell(self, col, row):
"""Get the content of a cell"""
return self.grid[col-1][row-1]
def _is_empty(self, col, row):
"""Check if a given cell is empty"""
try:
return self.grid[col-1][row-1] == self.empty
except IndexError:
pass
return False
def _number_words(self):
"""Orders the words and applies numbers to them
This applies numbers in two ways: the traditional way when row and column
words both start from one. And an ordinal way where words are assigned ascending
numbers regardless of whether it is a row or column.
Words starting at the same cell will get the same number (e.g.
'ask' and 'air' would become 1-across and 1-down.)
"""
self.placed_words.sort(key=lambda i: ((i.col*self.cols) + i.row))
across_count, down_count = 1, 1
word_sequence = -1
prev_word = None
for word in self.placed_words:
if prev_word == None or word.col != prev_word.col or word.row != prev_word.row:
word_sequence += 1
word.sequence_number = word_sequence
prev_word = word
ignore_num = []
for word in self.placed_words:
if word.number == None:
if word.vertical:
while across_count in ignore_num:
across_count +=1
word.number = across_count
across_count +=1
else:
while down_count in ignore_num:
down_count +=1
word.number = down_count
down_count +=1
## Check if any other word starts at the same coords
# in that case apply the same number to that word
for word2 in self.placed_words:
if word2.col == word.col and word2.row == word.row and word2 is not word:
word2.number = word.number
ignore_num.append(word.number)
class Word(object):
def __init__(self, word=None, clue=None):
self.word = re.sub(r'\s', '', word.lower())
self.clue = clue
self.length = len(word) ## Much faster than asking for len(word)
self.row = None
self.col = None
self.vertical = None
self.number = None
## Used if the word is a solution-field (colored)
self.solution = False
self.solution_char = None
def __len__(self):
print("Please use len(word.word) to ask for the length of the word - this is much faster")
return len(self.word)
if __name__ == "__main__":
parser = OptionParser()
general_group = OptionGroup(parser, "General Options")
general_group.add_option("--stats", help="Print stats", dest="stats", default=None, action="store_true")
parser.add_option_group(general_group)
crossword_group = OptionGroup(parser, "Crossword Options")
crossword_group.add_option("-c", "--cols", help="Number of columns to use (Default: auto)", dest="columns", default="auto", action="store")
crossword_group.add_option("-r", "--rows", help="Number of rows to use (Default: auto)", dest="rows", default="auto", action="store")
crossword_group.add_option("-s", "--solution", help="The crossword's solution (some colored fields which letters can be used to build a word).\nNote: This will overwrite any solution defined in the input file(s)!! ", action="store", dest="solution", default=None)
crossword_group.add_option("--solved", help="Create a solved crossword", action="store_true", dest="solved", default = False)
crossword_group.add_option("-b", "--bestof", help="Create n crosswords and keep the best", action="store", dest="bestof", default=3, type="int")
parser.add_option_group(crossword_group)
output_group = OptionGroup(parser, "Output Options")
output_group.add_option("--print-clues", help="Print crossword clues to stdout", action="store_true", dest="print_clues", default=False)
output_group.add_option("--print-crossword", help="Print crossword to stdout", action="store_true", dest="print_crossword", default=False)
output_group.add_option("--print-js-grid", help="Print crossword in javascript form for embedding to stdout", action="store_true", dest="print_js_grid", default=False)
output_group.add_option("--print-solved-js-grid", help="Print crossword in javascript form with answers to stdout", action="store_true", dest= "print_solved_js_grid",default=False)
output_group.add_option("--print-js-html-clues", help="Print clues in an html format", action="store_true", dest="print_js_html_clues", default=False)
parser.add_option_group(output_group)
(options, args) = parser.parse_args()
if args == []:
parser.print_help()
print("You need to specify an input file")
sys.exit(0)
if not options.print_js_grid and not options.print_crossword:
parser.print_help()
print("You need to specify an output")
sys.exit(0)
if options.columns.isdigit():
options.columns = int(options.columns)
if options.rows.isdigit():
options.rows = int(options.rows)
counter = 0
for inputfile in args:
if len(args) == 1:
output = "%s.png" % os.path.splitext(inputfile)[0]
c = 1
while os.path.exists(output):
output = "%s_%i.png" % (os.path.splitext(inputfile)[0], c)
c += 1
else:
filename = inputfile
output = "%s.png" % (os.path.splitext(filename)[0])
c = 1
while os.path.exists(output):
output = "%s_%i.png" % (os.path.splitext(filename)[0], c)
c += 1
parser = SimpleParser(inputfile)
if options.solution:
solution = options.solution
elif parser.has_option("solution"):
solution = parser.get_option("solution")
else:
solution = None
wordlist = parser.get_questions()
cwd = CrossWord(options.columns, options.rows, " ", 5000, wordlist)
score = cwd.compute_crossword(best_of=options.bestof, force_solved=False)
tmplist = [w.word.lower() for w in cwd.placed_words]
missing = [w.word for w in cwd.wordlist if w.word.lower() not in tmplist]
if missing != []:
print("Could not place some words. Probably your grid is too small. Sometimes setting \"--bestof\" to a higer value also help.")
print("Words that could not be placed: '%s'" % missing)
if options.stats:
stats(cwd, False)
formatter = CrossWordFormatter(cwd, solution=solution)
if options.print_js_grid:
print (formatter.get_crossword_javascript_grid())
if options.print_js_html_clues:
print (formatter.get_crossword_js_html_cues())
if options.print_solved_js_grid:
print (formatter.get_crossword_javascript_grid( True ))
if options.print_crossword:
print (formatter.get_crossword_ascii_grid(False, True))
print ("Sorry, the print-crossword-formatter is still buggy!\n")
if options.print_clues:
print (formatter.get_crossword_ascii_cues())
counter += 1