Word removal functionality completed
[getaclue.git] / crosswordpuzzle.py
1 # Get A Clue (C) 2010 V. Harishankar
2 # Crossword puzzle maker program
3 # Licensed under the GNU GPL v3
4
5 # Class for the puzzle data representation
6
7 # for export to PNG image
8 import cairo
9
10 class GridItem:
11 # initialize the item
12 def __init__ (self, item_char='.', item_guess = None, across_start = False,
13 down_start = False, occupied_across = False,
14 occupied_down = False, num = 0, clue_across = None,
15 clue_down = None, revealed = False):
16 # character in the cell
17 self.char = item_char
18 # guess of character in cell
19 self.guess = item_guess
20 # is the cell the start of an across word?
21 self.across_start = across_start
22 # is the cell the start of a down word?
23 self.down_start = down_start
24 # is the cell occupied by a letter in an across word?
25 self.occupied_across = occupied_across
26 # is the cell occupied by a letter in a down word?
27 self.occupied_down = occupied_down
28 # numbering of the cell if it is the start of a word
29 self.numbered = num
30 # clue across if the cell is the start of an across word
31 self.clue_across = clue_across
32 # clue down if the cell is the start of a down word
33 self.clue_down = clue_down
34 # is the letter revealed or hidden?
35 self.revealed = revealed
36
37 # clear the across data
38 def clear_across_data (self):
39 self.across_start = False
40 self.occupied_across = False
41 self.clue_across = None
42 # if no down word starting at item
43 if self.down_start is False:
44 self.numbered = 0
45 # if no down word at the item
46 if self.occupied_down is False:
47 self.char = '.'
48 self.revealed = False
49 self.guess = None
50
51 # clear the down data
52 def clear_down_data (self):
53 self.down_start = False
54 self.occupied_down = False
55 self.clue_down = None
56 # if no across word starting at item
57 if self.across_start is False:
58 self.numbered = 0
59 # if no across word at the item
60 if self.occupied_across is False:
61 self.char = '.'
62 self.revealed = False
63 self.guess = None
64
65 # reset a grid item completely - use only to destroy whole grid, otherwise
66 # use either clear_across_data () or clear_down_data () for erasing single
67 # words
68 def reset (self):
69 # character in the cell
70 self.char = '.'
71 # guess of character in cell
72 self.guess = None
73 # is the cell the start of an across word?
74 self.across_start = False
75 # is the cell the start of a down word?
76 self.down_start = False
77 # is the cell occupied by a letter in an across word?
78 self.occupied_across = False
79 # is the cell occupied by a letter in a down word?
80 self.occupied_down = False
81 # numbering of the cell if it is the start of a word
82 self.numbered = 0
83 # clue across if the cell is the start of an across word
84 self.clue_across = None
85 # clue down if the cell is the start of a down word
86 self.clue_down = None
87 # is the letter revealed or hidden?
88 self.revealed = False
89
90 # exception for too long words
91 class TooLongWordException (Exception):
92 def __init__ (self, word, length):
93 self.word = word
94 self.length = length
95
96 # exception for intersecting words
97 class IntersectWordException (Exception):
98 def __init__ (self, word, length):
99 self.word = word
100 self.length = length
101
102 # exception when grid is sought to be changed when frozen
103 class FrozenGridException (Exception):
104 def __init__ (self):
105 self.msg = "Grid is frozen and cannot be edited"
106
107 # exception when no word is found at a position
108 class NoWordException (Exception):
109 def __init__ (self, row, col):
110 self.pos = (row, col)
111
112 # exception when no words are present in the grid
113 class NoWordsException (Exception):
114 def __init__ (self):
115 self.msg = "No words in grid"
116
117 class CrosswordPuzzle:
118 def __init__ (self, rows, cols):
119 # define number of rows and columns
120 self.rows = rows
121 self.cols = cols
122
123 # initialize the list to hold the grid
124 self.data = []
125
126 # initial state of the grid is unfrozen
127 self.frozen_grid = False
128
129 # create the grid data
130 for i in range (rows):
131 self.data.append ([])
132 for j in range (cols):
133 self.data[i].append (GridItem ())
134
135 # export to an image
136 def export_image (self, pngfile, htmlfile=None, puztitle="Crossword Puzzle",
137 solution=True):
138 # don't export if grid is not frozen
139 if self.frozen_grid is False:
140 raise FrozenGridException
141
142 # create cairo image surface and context
143 px = 30
144 surf = cairo.ImageSurface (cairo.FORMAT_RGB24, self.cols*px, self.rows*px)
145 ctx = cairo.Context (surf)
146
147 ctx.set_source_rgb (1, 1, 1)
148 ctx.rectangle (0, 0, self.cols*px, self.rows*px)
149 ctx.fill ()
150
151 # get the clues across and down
152 clues_across = self.get_clues_across ()
153 clues_down = self.get_clues_down ()
154
155
156 # traverse through the grid
157 for row in range (self.rows):
158 for col in range (self.cols):
159 # if grid is un-occupied
160 if (self.data[row][col].occupied_across is False and
161 self.data[row][col].occupied_down is False):
162 ctx.set_source_rgb (0, 0, 0)
163 ctx.rectangle (col*px, row*px, px, px)
164 ctx.fill ()
165 # grid is occupied
166 else:
167 ctx.set_source_rgb (1, 1, 1)
168 ctx.rectangle (col*px, row*px, px, px)
169 ctx.fill ()
170 ctx.set_source_rgb (0, 0, 0)
171 ctx.rectangle (col*px, row*px, px, px)
172 ctx.stroke ()
173 # if solution is not to be provided, number the grid
174 if solution is False:
175 if self.data[row][col].numbered <> 0:
176 ctx.select_font_face ("Serif")
177 ctx.set_font_size (10)
178 ctx.move_to (col*px+5, row*px+10)
179 ctx.show_text (str(self.data[row][col].numbered))
180 # display the words
181 else:
182 ctx.select_font_face ("Serif")
183 ctx.set_font_size (16)
184 ctx.move_to (col*px+10, row*px+20)
185 ctx.show_text (self.data[row][col].char)
186
187 surf.write_to_png (open (pngfile, "wb"))
188
189 # if solution is false, publish the clues and the image in a HTML file
190 if htmlfile and solution is False:
191 html_contents = ["<html>", "<head>", "<title>"]
192 html_contents.append (puztitle)
193 html_contents.append ("</title>")
194 html_contents.append ("</head>")
195 html_contents.append ("<body>")
196 html_contents.append ("<h1>" + puztitle + "</h1>")
197 html_contents.append ('<img src="' + pngfile + '" alt="puzzle" />')
198
199 html_contents.append ("<h2>Across clues</h2>")
200 html_contents.append ("<p>")
201 for word, clue in clues_across:
202 # clue should be: <num> - clue text (chars)
203 clue_str = str (self.data[word[1]][word[2]].numbered) + " - " \
204 + clue + " (" + str (word[3]) + ")"
205 html_contents.append (clue_str)
206 html_contents.append ("<br />")
207 html_contents.append ("</p>")
208
209 html_contents.append ("<h2>Down clues</h2>")
210 html_contents.append ("<p>")
211 for word, clue in clues_down:
212 clue_str = str (self.data[word[1]][word[2]].numbered) + " - " \
213 + clue + " (" + str (word[3]) + ")"
214 html_contents.append (clue_str)
215 html_contents.append ("<br />")
216 html_contents.append ("</p>")
217 html_contents.append ("</body>")
218 html_contents.append ("</html>")
219
220 html_str = "\r\n".join (html_contents)
221
222 fhtml = open (htmlfile, "wb")
223 fhtml.write (html_str)
224 fhtml.close ()
225
226 # get the AcrossLite(TM) data for exporting
227 def export_acrosslite (self, title, author, copyright):
228 # don't export if grid is not frozen
229 if self.frozen_grid is False:
230 raise FrozenGridException
231
232 across_data = []
233 across_data.append ("<ACROSS PUZZLE>\r\n")
234 across_data.append ("<TITLE>\r\n")
235 across_data.append (title + "\r\n")
236 across_data.append ("<AUTHOR>\r\n")
237 across_data.append (author + "\r\n")
238 across_data.append ("<COPYRIGHT>\r\n")
239 across_data.append (copyright + "\r\n")
240 across_data.append ("<SIZE>\r\n")
241 str_size = str (self.cols) + "x" + str (self.rows)
242 across_data.append (str_size + "\r\n")
243 across_data.append ("<GRID>\r\n")
244 for row in range (self.rows):
245 for col in range (self.cols):
246 if (self.data[row][col].occupied_across is True or
247 self.data[row][col].occupied_down is True):
248 across_data.append (self.data[row][col].char)
249 else:
250 across_data.append (".")
251 across_data.append ("\r\n")
252
253 across_data.append ("<ACROSS>\r\n")
254 clues_across = self.get_clues_across ()
255 for word, clue in clues_across:
256 if clue:
257 across_data.append (clue + "\r\n")
258 else:
259 across_data.append ("(No clue yet)\r\n")
260
261 across_data.append ("<DOWN>\r\n")
262 clues_down = self.get_clues_down ()
263 for word, clue in clues_down:
264 if clue:
265 across_data.append (clue + "\r\n")
266 else:
267 across_data.append ("(No clue yet\r\n")
268
269 acrosslite_str = "".join (across_data)
270 return acrosslite_str
271
272 # get all the clues for across
273 def get_clues_across (self):
274 clues = []
275 # traverse the grid
276 for row in range (self.rows):
277 for col in range (self.cols):
278 if (self.data[row][col].occupied_across is True and
279 self.data[row][col].across_start is True):
280 word_across = self.get_word_across (row, col)
281 clues.append ((word_across, self.data[row][col].clue_across))
282 # if no across words are found at all
283 if not clues:
284 raise NoWordsException
285
286 return clues
287
288 # get all the clues for down
289 def get_clues_down (self):
290 clues = []
291 # traverse the grid
292 for row in range (self.rows):
293 for col in range (self.cols):
294 if (self.data[row][col].occupied_down is True and
295 self.data[row][col].down_start is True):
296 word_down = self.get_word_down (row, col)
297 clues.append ((word_down, self.data[row][col].clue_down))
298 # if no down words are found at all
299 if not clues:
300 raise NoWordsException
301
302 return clues
303
304 # getting a down word at a position
305 def get_word_down (self, row, col):
306 # if index is out of bounds
307 if row >= self.rows or col >= self.cols:
308 raise NoWordException (row, col)
309
310 # if there is no occupied down letter at that position
311 if self.data[row][col].occupied_down is False:
312 raise NoWordException (row, col)
313
314 # now traverse the grid to find the beginning of the word
315 i = row
316 while i >= 0:
317 # if it is occupied down and is the beginning of the word
318 if (self.data[i][col].occupied_down is True and
319 self.data[i][col].down_start is True):
320 start_row = i
321 break
322 i -= 1
323
324 i = start_row
325 word_chars = []
326 # now seek the end of the word
327 while i < self.rows:
328 if self.data[i][col].occupied_down is True:
329 word_chars.append (self.data[i][col].char)
330 else:
331 break
332 i += 1
333
334 word = "".join (word_chars)
335
336 # return the word, starting row, column and length as a tuple
337 return (word, start_row, col, len(word))
338
339 # getting an across word at a position
340 def get_word_across (self, row, col):
341 # if index is out of bounds
342 if row >= self.rows or col >= self.cols:
343 raise NoWordException (row, col)
344
345 # if there is no occupied across letter at that position
346 if self.data[row][col].occupied_across is False:
347 raise NoWordException (row, col)
348
349 # now traverse the grid to look for the beginning of the word
350 i = col
351 while i >= 0:
352 # if it is occupied across and is the beginning of the word
353 if (self.data[row][i].occupied_across is True and
354 self.data[row][i].across_start is True):
355 start_col = i
356 break
357 i -= 1
358
359 i = start_col
360 word_chars = []
361 # now seek the end of the word
362 while i < self.cols:
363 if self.data[row][i].occupied_across is True:
364 word_chars.append (self.data[row][i].char)
365 else:
366 break
367 i += 1
368
369 word = "".join (word_chars)
370
371 # return the word, starting column, row and length as a tuple
372 return (word, row, start_col, len(word))
373
374 # setting a down word
375 def set_word_down (self, row, col, word):
376 # if the grid is frozen the abort
377 if self.frozen_grid is True:
378 raise FrozenGridException
379
380 # if the word length greater than totalrows - startrow
381 if len(word) > self.rows - row:
382 raise TooLongWordException (word, len(word))
383
384 # is the word intersecting any other word?
385 for i in range (len(word)):
386 # on the same column
387 if self.data[row+i][col].occupied_down is True:
388 raise IntersectWordException (word, len(word))
389 # on the previous column except first column
390 if col > 0:
391 # except the first and last col
392 if i > 0 and i < len(word) - 1:
393 if self.data[row+i][col-1].occupied_down is True:
394 raise IntersectWordException (word, len(word))
395 # if the previous column is the end of an across word
396 if (self.data[row+i][col-1].occupied_across is True and
397 self.data[row+i][col].occupied_across is False):
398 raise IntersectWordException (word, len(word))
399
400 # on the next column except last column
401 if col < len(word) - 1:
402 # except the first and last row check if there is any
403 # down word in previous column
404 if i > 0 and i < len(word) - 1:
405 if self.data[row+i][col+1].occupied_down is True:
406 raise IntersectWordException (word, len(word))
407 # check if there is any across word starting in the
408 # next column
409 if self.data[row+i][col+1].across_start is True:
410 raise IntersectWordException (word, len(word))
411
412 # also check the character before and after
413 if (row > 0 and self.data[row-1][col].occupied_down is True
414 and self.data[row-1][col].occupied_across is True):
415 raise IntersectWordException (word, len(word))
416 if (row + len(word) < self.rows and
417 self.data[row+len(word)][col].occupied_across is True and
418 self.data[row+len(word)][col].occupied_down is True):
419 raise IntersectWordException (word, len(word))
420
421 # set the down start to true
422 self.data[row][col].down_start = True
423 # set the word
424 for i in range (len(word)):
425 self.data[row+i][col].occupied_down = True
426 self.data[row+i][col].char = word[i].upper ()
427
428
429 # setting an across word
430 def set_word_across (self, row, col, word):
431 # if the grid is frozen the abort
432 if self.frozen_grid is True:
433 raise FrozenGridException
434
435 # is the word length greater than totalcols - startcol?
436 if len(word) > self.cols - col:
437 raise TooLongWordException (word, len(word))
438
439 # is the word intersecting any other word?
440 for i in range (len(word)):
441 # on the same row
442 if self.data[row][col+i].occupied_across is True:
443 raise IntersectWordException (word, len(word))
444 # on a previous row except first row
445 if row > 0:
446 # if not the first or last col
447 if i > 0 and i < len(word) - 1:
448 if self.data[row-1][col+i].occupied_across is True:
449 raise IntersectWordException (word, len(word))
450 # if the previous row is the end of a down word
451 if (self.data[row-1][col+i].occupied_down is True and
452 self.data[row][col+i].occupied_down is False):
453 raise IntersectWordException (word, len(word))
454
455 # on a next row
456 if (row < (self.rows - 1)):
457 # except the first and last letter check if there is
458 # any across intersection
459 if i > 0 and i < len (word) - 1:
460 if self.data[row+1][col+i].occupied_across is True:
461 raise IntersectWordException (word, len(word))
462 # if a down word is starting at any column below the
463 # word
464 if self.data[row+1][col+i].down_start is True:
465 raise IntersectWordException (word, len(word))
466
467 # also check the character beyond and before and after
468 if (col > 0 and (self.data[row][col-1].occupied_across is True or
469 self.data[row][col-1].occupied_down is True)):
470 raise IntersectWordException (word, len(word))
471 if (col + len(word) < self.cols and
472 (self.data[row][col+len(word)].occupied_across is True or
473 self.data[row][col+len(word)].occupied_down is True)):
474 raise IntersectWordException (word, len(word))
475
476 # set across start to true
477 self.data[row][col].across_start = True
478
479 # set the word
480 for i in range (len(word)):
481 self.data[row][col+i].char = word[i].upper ()
482 self.data[row][col+i].occupied_across = True
483
484 # freeze the grid numbers etc.
485 def freeze_grid (self):
486 # numbering
487 numbering = 1
488 # run through the grid
489 for row in range (self.rows):
490 for col in range (self.cols):
491 # if grid is blank set the character to #
492 if (self.data[row][col].occupied_across is False
493 and self.data[row][col].occupied_down is False):
494 self.data[row][col].char = "#"
495 elif (self.data[row][col].across_start is True or
496 self.data[row][col].down_start is True):
497 self.data[row][col].numbered = numbering
498 numbering += 1
499
500 self.frozen_grid = True
501
502 # unfreeze the grid numbers etc.
503 def unfreeze_grid (self):
504 # run through the grid
505 for row in range (self.rows):
506 for col in range (self.cols):
507 self.data[row][col].numbered = 0
508 if (self.data[row][col].occupied_across is False and
509 self.data[row][col].occupied_down is False):
510 self.data[row][col].char = '.'
511
512 self.frozen_grid = False
513
514 # reset the entire grid
515 def reset_grid (self):
516 # run through the grid
517 for row in range (self.rows):
518 for col in range (self.cols):
519 # re-initialize all data
520 self.data[row][col].reset ()
521
522 self.frozen_grid = False
523
524 # remove an across word at position
525 def remove_word_across (self, row, col):
526 # if grid is frozen don't allow removal of word
527 if self.frozen_grid is True:
528 raise FrozenGridException
529
530 word, brow, bcol, l = self.get_word_across (row, col)
531
532 # traverse from the beginning to end of the word and erase it
533 c = bcol
534 while True:
535 if self.data[brow][c].occupied_across is True:
536 self.data[brow][c].clear_across_data ()
537 else:
538 break
539 c += 1
540
541 # remove a down word at position
542 def remove_word_down (self, row, col):
543 # if grid is frozen don't allow removal of word
544 if self.frozen_grid is True:
545 raise FrozenGridException
546
547 word, brow, bcol, l = self.get_word_down (row, col)
548 # traverse from the beginn to end of the word and erase it
549 r = brow
550 while True:
551 if self.data[r][bcol].occupied_down is True:
552 self.data[r][bcol].clear_down_data ()
553 else:
554 break
555 r += 1
556
557
558