Coverage for puz.py: 100%

866 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-28 06:05 +0000

1from __future__ import annotations # for Python 3.9 and earlier 

2 

3import importlib.metadata 

4import string 

5import struct 

6from collections.abc import Iterable, Iterator 

7from enum import Enum, IntEnum 

8from typing import Any, Protocol, cast, runtime_checkable 

9 

10__version__ = importlib.metadata.version('puzpy') 

11 

12HEADER_FORMAT = '''< 

13 H 11s xH 

14 Q 4s 2sH 

15 12s BBH 

16 H H ''' 

17 

18HEADER_CKSUM_FORMAT = '<BBH H H ' 

19 

20EXTENSION_HEADER_FORMAT = '< 4s H H ' 

21 

22MASKSTRING = 'ICHEATED' 

23 

24ENCODING = 'ISO-8859-1' 

25ENCODING_UTF8 = 'UTF-8' 

26ENCODING_ERRORS = 'strict' # raises an exception for bad chars; change to 'replace' for laxer handling 

27 

28ACROSSDOWN = b'ACROSS&DOWN' 

29 

30BLACKSQUARE = '.' 

31BLACKSQUARE2 = ':' # used for diagramless puzzles 

32BLANKSQUARE = '-' 

33 

34 

35class PuzzleType(IntEnum): 

36 Normal = 0x0001 

37 Diagramless = 0x0401 

38 

39 

40# the following diverges from the documentation 

41# but works for the files I've tested 

42class SolutionState(IntEnum): 

43 # solution is available in plaintext 

44 Unlocked = 0x0000 

45 # solution is not present in the file 

46 NotProvided = 0x0002 

47 # solution is locked (scrambled) with a key 

48 Locked = 0x0004 

49 

50 

51class GridMarkup(IntEnum): 

52 # ordinary grid cell 

53 Default = 0x00 

54 # marked incorrect at some point 

55 PreviouslyIncorrect = 0x10 

56 # currently showing incorrect 

57 Incorrect = 0x20 

58 # user got a hint 

59 Revealed = 0x40 

60 # circled 

61 Circled = 0x80 

62 

63 

64# refer to Extensions as Extensions.Rebus, Extensions.Markup 

65class Extensions(bytes, Enum): 

66 # grid of rebus indices: 0 for non-rebus; 

67 # i+1 for key i into RebusSolutions map 

68 # should be same size as the grid 

69 Rebus = b'GRBS', 

70 

71 # map of rebus solution entries eg 0:HEART;1:DIAMOND;17:CLUB;23:SPADE; 

72 RebusSolutions = b'RTBL', 

73 

74 # user's rebus entries; binary grid format: one null-terminated string per cell (in grid order). 

75 # empty cells are a single null byte; filled rebus cells are the fill string followed by a null byte. 

76 RebusFill = b'RUSR', 

77 

78 # timer state: 'a,b' where a is the number of seconds elapsed and 

79 # b is a boolean (0,1) for whether the timer is running 

80 Timer = b'LTIM', 

81 

82 # grid cell markup: previously incorrect: 0x10; 

83 # currently incorrect: 0x20, 

84 # hinted: 0x40, 

85 # circled: 0x80 

86 Markup = b'GEXT' 

87 

88 

89class ClueEntry(dict[str, Any]): 

90 """A clue entry in a crossword puzzle. 

91 

92 Supports legacy dict-style access (e.g. entry['num']) for backwards 

93 compatibility, as well as named property access (e.g. entry.number). 

94 """ 

95 

96 _puzzle: Puzzle | None 

97 

98 def __init__(self, data: dict[str, Any], puzzle: Puzzle | None = None) -> None: 

99 super().__init__(data) 

100 self._puzzle = puzzle 

101 

102 @property 

103 def number(self) -> int: 

104 return cast(int, self['num']) 

105 

106 @property 

107 def text(self) -> str: 

108 return cast(str, self['clue']) 

109 

110 @property 

111 def length(self) -> int: 

112 return cast(int, self['len']) 

113 

114 @property 

115 def direction(self) -> str: 

116 return cast(str, self['dir']) 

117 

118 @property 

119 def row(self) -> int: 

120 return cast(int, self['row']) 

121 

122 @property 

123 def col(self) -> int: 

124 return cast(int, self['col']) 

125 

126 @property 

127 def cell(self) -> int: 

128 return cast(int, self['cell']) 

129 

130 @property 

131 def solution(self) -> str: 

132 assert self._puzzle is not None, 'ClueEntry has no puzzle reference' 

133 return Grid(self._puzzle.solution, self._puzzle.width, self._puzzle.height).get_string_for_clue(self) 

134 

135 @property 

136 def fill(self) -> str: 

137 assert self._puzzle is not None, 'ClueEntry has no puzzle reference' 

138 return Grid(self._puzzle.fill, self._puzzle.width, self._puzzle.height).get_string_for_clue(self) 

139 

140 

141def read(filename: str) -> Puzzle: 

142 """ 

143 Read a .puz file and return the Puzzle object. 

144 raises PuzzleFormatError if there's any problem with the file format. 

145 """ 

146 with open(filename, 'rb') as f: 

147 return load(f.read()) 

148 

149 

150def read_text(filename: str) -> Puzzle: 

151 """ 

152 Read an Across Lite .txt text format file and return the Puzzle object. 

153 raises PuzzleFormatError if there's any problem with the file format. 

154 """ 

155 with open(filename, encoding='utf-8', errors='replace') as f: 

156 return load_text(f.read()) 

157 

158 

159def load(data: bytes) -> Puzzle: 

160 """ 

161 Read .puz file data and return the Puzzle object. 

162 raises PuzzleFormatError if there's any problem with the file format. 

163 """ 

164 puz = Puzzle() 

165 puz.load(data) 

166 return puz 

167 

168 

169def load_text(text: str) -> Puzzle: 

170 """ 

171 Parse Across Lite Text format from a string and return a Puzzle object. 

172 raises PuzzleFormatError if there's any problem with the format. 

173 """ 

174 return from_text_format(text) 

175 

176 

177def encoding_for_version(version: tuple[int, ...]) -> str: 

178 """Text encoding used by .puz files of the given version: 

179 ISO-8859-1 before version 2.0, UTF-8 from 2.0 on.""" 

180 return ENCODING if version[0] < 2 else ENCODING_UTF8 

181 

182 

183class PuzzleFormatError(Exception): 

184 """ 

185 Indicates a format error in the .puz file. May be thrown due to 

186 invalid headers, invalid checksum validation, or other format issues. 

187 """ 

188 def __init__(self, message: str = '') -> None: 

189 self.message = message 

190 

191 

192class Puzzle: 

193 """Represents a puzzle 

194 """ 

195 def __repr__(self) -> str: 

196 return f'Puzzle({self.width}x{self.height}, title={self.title!r}, author={self.author!r})' 

197 

198 def __init__(self, version: str | bytes = '1.3') -> None: 

199 """Initializes a blank puzzle 

200 """ 

201 self.preamble = b'' 

202 self.postscript: bytes | str = b'' 

203 self.title = '' 

204 self.author = '' 

205 self.copyright = '' 

206 self.width = 0 

207 self.height = 0 

208 self.set_version(version) # also sets self.encoding 

209 # these are bytes that might be unused 

210 self.unk1 = b'\0' * 2 

211 self.unk2 = b'\0' * 12 

212 self.scrambled_cksum = 0 

213 self.fill = '' 

214 self.solution = '' 

215 self.clues: list[str] = [] 

216 self.notes = '' 

217 self.extensions: dict[bytes, bytes] = {} 

218 # the folowing is so that we can round-trip values in order: 

219 self._extensions_order: list[bytes] = [] 

220 self.puzzletype = PuzzleType.Normal 

221 self.solution_state = SolutionState.Unlocked 

222 self.helpers: dict[str, PuzzleHelper] = {} # add-ons like Rebus and Markup 

223 

224 def load(self, data: bytes) -> None: 

225 s = PuzzleBuffer(data) 

226 

227 # advance to start - files may contain some data before the 

228 # start of the puzzle use the ACROSS&DOWN magic string as a waypoint 

229 # save the preamble for round-tripping 

230 if not s.seek_to(ACROSSDOWN, -2): 

231 raise PuzzleFormatError("Data does not appear to represent a " 

232 "puzzle. Are you sure you didn't intend " 

233 "to use read?") 

234 

235 # save whatever we just jumped over so that we can round-trip it on save. 

236 self.preamble = bytes(s.data[:s.pos]) 

237 

238 puzzle_data = s.unpack(HEADER_FORMAT) 

239 cksum_gbl = puzzle_data[0] 

240 # acrossDown = puzzle_data[1] 

241 cksum_hdr = puzzle_data[2] 

242 cksum_magic = puzzle_data[3] 

243 self.fileversion = puzzle_data[4] 

244 # since we don't know the role of these bytes, just round-trip them 

245 self.unk1 = puzzle_data[5] 

246 self.scrambled_cksum = puzzle_data[6] 

247 self.unk2 = puzzle_data[7] 

248 self.width = puzzle_data[8] 

249 self.height = puzzle_data[9] 

250 numclues = puzzle_data[10] 

251 self.puzzletype = puzzle_data[11] 

252 self.solution_state = puzzle_data[12] 

253 

254 self.version = self.fileversion[:3] 

255 # Once we have fileversion we can guess the encoding 

256 self.encoding = encoding_for_version(self.version_tuple()) 

257 s.encoding = self.encoding 

258 

259 self.solution = s.read(self.width * self.height).decode(self.encoding) 

260 self.fill = s.read(self.width * self.height).decode(self.encoding) 

261 

262 self.title = s.read_string() 

263 self.author = s.read_string() 

264 self.copyright = s.read_string() 

265 

266 self.clues = [s.read_string() for _ in range(numclues)] 

267 self.notes = s.read_string() 

268 

269 ext_cksum: dict[bytes, int] = {} 

270 while s.can_unpack(EXTENSION_HEADER_FORMAT): 

271 code, length, cksum = s.unpack(EXTENSION_HEADER_FORMAT) 

272 ext_cksum[code] = cksum 

273 # extension data is represented as a null-terminated string, 

274 # but since the data can contain nulls we can't use read_string 

275 self.extensions[code] = s.read(length) 

276 s.read(1) # extensions have a trailing byte 

277 # save the codes in order for round-tripping 

278 self._extensions_order.append(code) 

279 

280 # sometimes there's some extra garbage at 

281 # the end of the file, usually \r\n 

282 if s.can_read(): 

283 self.postscript = s.read_to_end() 

284 

285 if cksum_gbl != self.global_cksum(): 

286 raise PuzzleFormatError('global checksum does not match') 

287 if cksum_hdr != self.header_cksum(): 

288 raise PuzzleFormatError('header checksum does not match') 

289 if cksum_magic != self.magic_cksum(): 

290 raise PuzzleFormatError('magic checksum does not match') 

291 for code, cksum_ext in ext_cksum.items(): 

292 if cksum_ext != data_cksum(self.extensions[code]): 

293 raise PuzzleFormatError( 

294 f'extension {code} checksum does not match' 

295 ) 

296 

297 def save(self, filename: str) -> None: 

298 puzzle_bytes = self.tobytes() 

299 with open(filename, 'wb') as f: 

300 f.write(puzzle_bytes) 

301 

302 def tobytes(self) -> bytes: 

303 s = PuzzleBuffer(encoding=self.encoding) 

304 # commit any changes from helpers 

305 for h in self.helpers.values(): 

306 if isinstance(h, PuzzleHelper): 

307 h.save() 

308 

309 # the grids are one byte per square; check before computing checksums 

310 self._check_grid_bytes('solution', self.solution) 

311 self._check_grid_bytes('fill', self.fill) 

312 

313 # include any preamble text we might have found on read 

314 s.write(self.preamble) 

315 

316 s.pack(HEADER_FORMAT, 

317 self.global_cksum(), ACROSSDOWN, 

318 self.header_cksum(), self.magic_cksum(), 

319 self.fileversion, self.unk1, self.scrambled_cksum, 

320 self.unk2, self.width, self.height, 

321 len(self.clues), self.puzzletype, self.solution_state) 

322 

323 s.write(self.encode(self.solution)) 

324 s.write(self.encode(self.fill)) 

325 

326 s.write_string(self.title) 

327 s.write_string(self.author) 

328 s.write_string(self.copyright) 

329 

330 for clue in self.clues: 

331 s.write_string(clue) 

332 

333 s.write_string(self.notes) 

334 

335 # do a bit of extra work here to ensure extensions round-trip in the 

336 # order they were read. this makes verification easier. But allow 

337 # for the possibility that extensions were added or removed from 

338 # self.extensions 

339 ext = dict(self.extensions) 

340 for code in self._extensions_order: 

341 data = ext.pop(code, None) 

342 if data: 

343 s.pack(EXTENSION_HEADER_FORMAT, code, 

344 len(data), data_cksum(data)) 

345 s.write(data + b'\0') 

346 

347 for code, data in ext.items(): 

348 s.pack(EXTENSION_HEADER_FORMAT, code, len(data), data_cksum(data)) 

349 s.write(data + b'\0') 

350 

351 # postscript is initialized, read, and stored as bytes. In case it is 

352 # overwritten as a string, this try/except converts it back. 

353 postscript_bytes = self.postscript.encode(self.encoding, ENCODING_ERRORS) \ 

354 if isinstance(self.postscript, str) else self.postscript 

355 s.write(postscript_bytes) 

356 

357 return s.tobytes() 

358 

359 def _check_grid_bytes(self, name: str, grid: str) -> None: 

360 expected = self.width * self.height 

361 size = len(self.encode(grid)) 

362 if size == expected: 

363 return 

364 multibyte = [c for c in dict.fromkeys(grid) if len(self.encode(c)) > 1] 

365 if multibyte: 

366 chars = ', '.join(repr(c) for c in multibyte) 

367 raise ValueError( 

368 f'{name} contains characters that take more than one byte ' 

369 f'in {self.encoding}: {chars}. Each grid square must be a ' 

370 f'single byte; to put a multi-character or non-ASCII value ' 

371 f'in a square, use a rebus (a placeholder letter in the grid, ' 

372 f'with the value in the GRBS/RTBL extensions).') 

373 raise ValueError( 

374 f'{name} is {size} bytes, but a {self.width}x{self.height} grid ' 

375 f'needs exactly {expected}') 

376 

377 def encode(self, s: str) -> bytes: 

378 return s.encode(self.encoding, ENCODING_ERRORS) 

379 

380 def encode_zstring(self, s: str) -> bytes: 

381 return self.encode(s) + b'\0' 

382 

383 def version_tuple(self) -> tuple[int, ...]: 

384 return tuple(map(int, self.version.split(b'.'))) 

385 

386 def set_version(self, version: str | bytes) -> None: 

387 self.version = version.encode('utf-8') if isinstance(version, str) else bytes(version) 

388 self.fileversion = self.version + b'\0' 

389 self.encoding = encoding_for_version(self.version_tuple()) 

390 

391 def has_rebus(self) -> bool: 

392 if Extensions.Rebus in self.extensions or 'rebus' in self.helpers: 

393 return self.rebus().has_rebus() 

394 return False 

395 

396 def rebus(self) -> Rebus: 

397 if 'rebus' not in self.helpers: 

398 self.helpers['rebus'] = Rebus(self) 

399 return cast('Rebus', self.helpers['rebus']) 

400 

401 def has_timer(self) -> bool: 

402 if Extensions.Timer in self.extensions or 'timer' in self.helpers: 

403 return self.timer().has_timer() 

404 return False 

405 

406 def remove_timer(self) -> None: 

407 self.extensions.pop(Extensions.Timer, None) 

408 self.helpers.pop('timer', None) 

409 

410 def timer(self) -> Timer: 

411 if 'timer' not in self.helpers: 

412 self.helpers['timer'] = Timer(self) 

413 return cast('Timer', self.helpers['timer']) 

414 

415 def has_markup(self) -> bool: 

416 if Extensions.Markup in self.extensions or 'markup' in self.helpers: 

417 return self.markup().has_markup() 

418 return False 

419 

420 def markup(self) -> Markup: 

421 if 'markup' not in self.helpers: 

422 self.helpers['markup'] = Markup(self) 

423 return cast('Markup', self.helpers['markup']) 

424 

425 def clue_numbering(self) -> ClueNumbering: 

426 if 'clues' not in self.helpers: 

427 self.helpers['clues'] = ClueNumbering(self) 

428 return cast('ClueNumbering', self.helpers['clues']) 

429 

430 def blacksquare(self) -> str: 

431 return BLACKSQUARE2 if self.puzzletype == PuzzleType.Diagramless else BLACKSQUARE 

432 

433 def is_solution_locked(self) -> bool: 

434 return bool(self.solution_state == SolutionState.Locked) 

435 

436 def unlock_solution(self, key: int) -> bool: 

437 if self.is_solution_locked(): 

438 unscrambled = unscramble_solution(self.solution, self.width, self.height, key, 

439 ignore_chars=self.blacksquare()) 

440 if not self.check_answers(unscrambled): 

441 return False 

442 

443 # clear the scrambled bit and cksum 

444 self.solution = unscrambled 

445 self.scrambled_cksum = 0 

446 self.solution_state = SolutionState.Unlocked 

447 

448 return True 

449 

450 def lock_solution(self, key: int) -> None: 

451 if not self.is_solution_locked(): 

452 # set the scrambled bit and cksum 

453 self.scrambled_cksum = scrambled_cksum(self.solution, self.width, self.height, 

454 ignore_chars=self.blacksquare(), encoding=self.encoding) 

455 self.solution_state = SolutionState.Locked 

456 scrambled = scramble_solution(self.solution, self.width, self.height, key, 

457 ignore_chars=self.blacksquare()) 

458 self.solution = scrambled 

459 

460 def check_answers(self, fill: str, strict: bool = True) -> bool: 

461 if self.is_solution_locked(): 

462 if not strict: 

463 raise ValueError('non-strict checking not possible when solution is locked') 

464 scrambled = scrambled_cksum(fill, self.width, self.height, 

465 ignore_chars=self.blacksquare(), encoding=self.encoding) 

466 return scrambled == self.scrambled_cksum 

467 if fill == self.solution: 

468 return True 

469 if not strict: 

470 return all(a == b for a, b in zip(fill, self.solution) if b != self.blacksquare() and a != BLANKSQUARE) 

471 return False 

472 

473 def check_rebus_answers(self, strict: bool = True) -> bool: 

474 if self.has_rebus(): 

475 return self.rebus().check_rebus_fill(strict=strict) 

476 # if no rebus just return True since there's nothing to check 

477 return True 

478 

479 def header_cksum(self, cksum: int = 0) -> int: 

480 return data_cksum(struct.pack(HEADER_CKSUM_FORMAT, 

481 self.width, self.height, len(self.clues), 

482 self.puzzletype, self.solution_state), cksum) 

483 

484 def text_cksum(self, cksum: int = 0) -> int: 

485 # for the checksum to work these fields must be added in order with 

486 # null termination, followed by all non-empty clues without null 

487 # termination, followed by notes (but only for version >= 1.3) 

488 if self.title: 

489 cksum = data_cksum(self.encode_zstring(self.title), cksum) 

490 if self.author: 

491 cksum = data_cksum(self.encode_zstring(self.author), cksum) 

492 if self.copyright: 

493 cksum = data_cksum(self.encode_zstring(self.copyright), cksum) 

494 

495 for clue in self.clues: 

496 if clue: 

497 cksum = data_cksum(self.encode(clue), cksum) 

498 

499 # notes included in global cksum starting v1.3 of format 

500 if self.version_tuple() >= (1, 3) and self.notes: 

501 cksum = data_cksum(self.encode_zstring(self.notes), cksum) 

502 

503 return cksum 

504 

505 def global_cksum(self) -> int: 

506 cksum = self.header_cksum() 

507 cksum = data_cksum(self.encode(self.solution), cksum) 

508 cksum = data_cksum(self.encode(self.fill), cksum) 

509 # extensions do not seem to be included in global cksum 

510 return self.text_cksum(cksum) 

511 

512 def magic_cksum(self) -> int: 

513 cksums = [ 

514 self.header_cksum(), 

515 data_cksum(self.encode(self.solution)), 

516 data_cksum(self.encode(self.fill)), 

517 self.text_cksum() 

518 ] 

519 

520 cksum_magic = 0 

521 for (i, cksum) in enumerate(reversed(cksums)): 

522 cksum_magic <<= 8 

523 cksum_magic |= ( 

524 ord(MASKSTRING[len(cksums) - i - 1]) ^ (cksum & 0x00ff) 

525 ) 

526 cksum_magic |= ( 

527 (ord(MASKSTRING[len(cksums) - i - 1 + 4]) ^ (cksum >> 8)) << 32 

528 ) 

529 

530 return cksum_magic 

531 

532 def grid(self) -> Grid: 

533 return Grid(self.fill, self.width, self.height) 

534 

535 def solution_grid(self) -> Grid: 

536 return Grid(self.solution, self.width, self.height) 

537 

538 

539class PuzzleBuffer: 

540 """PuzzleBuffer class 

541 wraps a bytes object and provides .puz-specific methods for 

542 reading and writing data 

543 """ 

544 def __repr__(self) -> str: 

545 return f'PuzzleBuffer(pos={self.pos}, length={len(self.data)}, encoding={self.encoding!r})' 

546 

547 def __init__(self, data: bytes | None = None, encoding: str = ENCODING): 

548 self.data = bytearray(data) if data else bytearray() 

549 self.encoding = encoding 

550 self.pos = 0 

551 

552 def can_read(self, n_bytes: int = 1) -> bool: 

553 return self.pos + n_bytes <= len(self.data) 

554 

555 def length(self) -> int: 

556 return len(self.data) 

557 

558 def read(self, n_bytes: int) -> bytes: 

559 start = self.pos 

560 self.pos += n_bytes 

561 return bytes(self.data[start:self.pos]) 

562 

563 def read_to_end(self) -> bytes: 

564 start = self.pos 

565 self.pos = self.length() 

566 return bytes(self.data[start:self.pos]) 

567 

568 def read_string(self) -> str: 

569 return self.read_until(b'\0') 

570 

571 def read_until(self, c: bytes) -> str: 

572 start = self.pos 

573 self.seek_to(c, 1) # read past 

574 return str(self.data[start:self.pos-1], self.encoding) 

575 

576 def seek_to(self, s: bytes, offset: int = 0) -> bool: 

577 try: 

578 self.pos = self.data.index(s, self.pos) + offset 

579 return True 

580 except ValueError: 

581 # s not found, advance to end 

582 self.pos = self.length() 

583 return False 

584 

585 def write(self, s: bytes) -> None: 

586 self.data.extend(s) 

587 

588 def write_string(self, s: str | None) -> None: 

589 s = s or '' 

590 self.data.extend(s.encode(self.encoding, ENCODING_ERRORS) + b'\0') 

591 

592 def pack(self, struct_format: str, *values: Any) -> None: 

593 self.data.extend(struct.pack(struct_format, *values)) 

594 

595 def can_unpack(self, struct_format: str) -> bool: 

596 return self.can_read(struct.calcsize(struct_format)) 

597 

598 def unpack(self, struct_format: str) -> tuple[Any, ...]: 

599 start = self.pos 

600 try: 

601 res = struct.unpack_from(struct_format, self.data, self.pos) 

602 self.pos += struct.calcsize(struct_format) 

603 return res 

604 except struct.error as err: 

605 message = f'could not unpack values at {start} for format {struct_format}' 

606 raise PuzzleFormatError(message) from err 

607 

608 def tobytes(self) -> bytes: 

609 return bytes(self.data) 

610 

611 

612# clue numbering helper 

613def get_grid_numbering(grid: str, width: int, height: int) -> tuple[list[ClueEntry], list[ClueEntry]]: 

614 # Add numbers to the grid based on positions of black squares 

615 def col(index: int) -> int: 

616 return index % width 

617 

618 def row(index: int) -> int: 

619 return index // width 

620 

621 def len_across(index: int) -> int: 

622 c = 0 

623 for c in range(width - col(index)): 

624 if is_blacksquare(grid[index + c]): 

625 return c 

626 return c + 1 

627 

628 def len_down(index: int) -> int: 

629 c = 0 

630 for c in range(height - row(index)): 

631 if is_blacksquare(grid[index + c*width]): 

632 return c 

633 return c + 1 

634 

635 across: list[ClueEntry] = [] 

636 down: list[ClueEntry] = [] 

637 count = 0 # count is the index into the clues list; 0-based and counts across and down together 

638 num = 1 # num is the clue number that gets printed in the grid 

639 for i in range(len(grid)): # i is the cell index in row-major order 

640 if not is_blacksquare(grid[i]): 

641 lastc = count 

642 is_across = col(i) == 0 or is_blacksquare(grid[i - 1]) 

643 if is_across and len_across(i) > 1: 

644 across.append(ClueEntry({ 

645 'num': num, 

646 'clue': None, # filled in by caller 

647 'clue_index': count, 

648 'cell': i, 

649 'row': row(i), 

650 'col': col(i), 

651 'len': len_across(i), 

652 'dir': 'across', 

653 })) 

654 count += 1 

655 is_down = row(i) == 0 or is_blacksquare(grid[i - width]) 

656 if is_down and len_down(i) > 1: 

657 down.append(ClueEntry({ 

658 'num': num, 

659 'clue': None, # filled in by caller 

660 'clue_index': count, 

661 'cell': i, 

662 'row': row(i), 

663 'col': col(i), 

664 'len': len_down(i), 

665 'dir': 'down' 

666 })) 

667 count += 1 

668 if count > lastc: 

669 num += 1 

670 

671 return across, down 

672 

673 

674@runtime_checkable 

675class PuzzleHelper(Protocol): 

676 def save(self) -> None: 

677 ... 

678 

679 

680class DefaultClueNumbering(PuzzleHelper): 

681 def __repr__(self) -> str: 

682 return f'DefaultClueNumbering(across={len(self.across)}, down={len(self.down)})' 

683 

684 def __init__(self, grid: str, clues: list[str], width: int, height: int) -> None: 

685 self.grid = grid 

686 self.clues = clues 

687 self.width = width 

688 self.height = height 

689 

690 self.across, self.down = get_grid_numbering(grid, width, height) 

691 for entry in self.across: 

692 entry['clue'] = clues[entry['clue_index']] 

693 for entry in self.down: 

694 entry['clue'] = clues[entry['clue_index']] 

695 

696 def save(self) -> None: 

697 pass # clue numbering is derived from the grid and clues, so no need to save anything back to the puzzle 

698 

699 # The following methods are no longer in use, but left here in case 

700 # anyone was using them externally. They may be removed in a future release. 

701 def col(self, index: int) -> int: 

702 return index % self.width 

703 

704 def row(self, index: int) -> int: 

705 return index // self.width 

706 

707 def len_across(self, index: int) -> int: 

708 c = 0 

709 for c in range(self.width - self.col(index)): 

710 if is_blacksquare(self.grid[index + c]): 

711 return c 

712 return c + 1 

713 

714 def len_down(self, index: int) -> int: 

715 c = 0 

716 for c in range(self.height - self.row(index)): 

717 if is_blacksquare(self.grid[index + c*self.width]): 

718 return c 

719 return c + 1 

720 

721 

722class ClueNumbering(DefaultClueNumbering): 

723 def __repr__(self) -> str: 

724 return f'ClueNumbering(across={len(self.across)}, down={len(self.down)})' 

725 

726 def __init__(self, puzzle: Puzzle) -> None: 

727 super().__init__(puzzle.solution, puzzle.clues, puzzle.width, puzzle.height) 

728 for entry in self.across: 

729 entry._puzzle = puzzle 

730 for entry in self.down: 

731 entry._puzzle = puzzle 

732 

733 

734class Grid: 

735 def __repr__(self) -> str: 

736 return f'Grid({self.width}x{self.height})' 

737 

738 def __init__(self, grid: str, width: int, height: int) -> None: 

739 self.grid = grid 

740 self.width = width 

741 self.height = height 

742 assert len(self.grid) == self.width * self.height 

743 

744 def get_cell(self, row: int, col: int) -> str: 

745 return self.grid[self.get_cell_index(row, col)] 

746 

747 def get_cell_index(self, row: int, col: int) -> int: 

748 return row * self.width + col 

749 

750 def get_range(self, row: int, col: int, length: int, dir: str = 'across') -> list[str]: # noqa: A002 

751 if dir == 'across': 

752 return self.get_range_across(row, col, length) 

753 if dir == 'down': 

754 return self.get_range_down(row, col, length) 

755 raise AssertionError("dir not one of 'across' or 'down'") 

756 

757 def get_range_across(self, row: int, col: int, length: int) -> list[str]: 

758 return [self.grid[self.get_cell_index(row, col + i)] for i in range(length)] 

759 

760 def get_range_down(self, row: int, col: int, length: int) -> list[str]: 

761 return [self.grid[self.get_cell_index(row + i, col)] for i in range(length)] 

762 

763 def get_range_for_clue(self, clue: ClueEntry) -> list[str]: 

764 return self.get_range(clue['row'], clue['col'], clue['len'], clue['dir']) 

765 

766 def __iter__(self) -> Iterator[list[str]]: 

767 return self.rows() 

768 

769 def rows(self) -> Iterator[list[str]]: 

770 for row in range(self.height): 

771 yield self.get_row(row) 

772 

773 def cols(self) -> Iterator[list[str]]: 

774 for col in range(self.width): 

775 yield self.get_column(col) 

776 

777 def get_row(self, row: int) -> list[str]: 

778 return self.get_range_across(row, 0, self.width) 

779 

780 def get_column(self, col: int) -> list[str]: 

781 return self.get_range_down(0, col, self.height) 

782 

783 def get_string(self, row: int, col: int, length: int, dir: str = 'across') -> str: # noqa: A002 

784 return ''.join(self.get_range(row, col, length, dir)) 

785 

786 def get_string_across(self, row: int, col: int, length: int) -> str: 

787 return ''.join(self.get_range_across(row, col, length)) 

788 

789 def get_string_down(self, row: int, col: int, length: int) -> str: 

790 return ''.join(self.get_range_down(row, col, length)) 

791 

792 def get_string_for_clue(self, clue: ClueEntry) -> str: 

793 return ''.join(self.get_range_for_clue(clue)) 

794 

795 

796class Rebus(PuzzleHelper): 

797 def __repr__(self) -> str: 

798 return f'Rebus(squares={len(self.get_rebus_squares())}, solutions={len(self.solutions)})' 

799 

800 def __init__(self, puzzle: Puzzle) -> None: 

801 self.puzzle = puzzle 

802 

803 N = self.puzzle.width * self.puzzle.height 

804 

805 self._dirty = False # track whether there are unsaved changes to the rebus helper that need to be committed 

806 # to the puzzle before saving 

807 

808 # the rebus table has the same number of entries as the grid and maps 1:1. 

809 # cell values v > 0 represent rebus squares, where v corresponds to a solution key k=v-1 in the solutions map. 

810 # 0 values indicate non-rebus squares. 

811 self.table: list[int] = [0] * N 

812 

813 # the solutions table is a map of rebus solution key k (an int) to the corresponding solution string, 

814 # eg 0:HEART;1:DIAMOND;17:CLUB;23:SPADE; k values need not be consecutive or in any order, but are 

815 # typically numbered sequentially starting from 0. When k values appear in the rebus table, they are 

816 # 1-indexed (ie v=k+1). 

817 self.solutions: dict[int, str] = {} 

818 

819 # the fill table has the same number of entries as the grid and maps 1:1. Each cell value is a string 

820 # representing the user's current fill for that cell, eg "STAR". Non-filled cells and non-rebus cells 

821 # are empty strings. 

822 # When a cell is a rebus entry, the corresponding cell in puzzle.fill will often be set to the first 

823 # letter of the rebus, eg 'S' for "STAR". 

824 self.fill: list[str] = [] 

825 

826 # parse rebus data 

827 if Extensions.Rebus in self.puzzle.extensions: 

828 rebus_data = self.puzzle.extensions[Extensions.Rebus] 

829 self.table = parse_bytes(rebus_data) 

830 

831 if Extensions.RebusSolutions in self.puzzle.extensions: 

832 raw_solution_data = self.puzzle.extensions[Extensions.RebusSolutions] 

833 solutions_str = raw_solution_data.decode(puzzle.encoding) 

834 self.solutions = { 

835 int(item[0]): item[1] 

836 for item in parse_dict(solutions_str).items() 

837 } 

838 

839 if Extensions.RebusFill in self.puzzle.extensions: 

840 s = PuzzleBuffer(self.puzzle.extensions[Extensions.RebusFill], encoding=puzzle.encoding) 

841 fill: list[str] = [] 

842 while s.can_read(): 

843 fill.append(s.read_string()) 

844 self.fill = (fill + [''] * N)[:N] 

845 else: 

846 self.fill = [''] * N 

847 

848 def has_rebus(self) -> bool: 

849 return Extensions.Rebus in self.puzzle.extensions or any(self.table) 

850 

851 def is_rebus_square(self, index: int) -> bool: 

852 return self.table[index] > 0 

853 

854 def get_rebus_squares(self) -> list[int]: 

855 return [i for i, k in enumerate(self.table) if k > 0] 

856 

857 def add_rebus_squares(self, squares: int | list[int], solution: str) -> None: 

858 if isinstance(squares, int): 

859 squares = [squares] 

860 

861 k = self.add_rebus_solution(solution) 

862 for i in squares: 

863 self.table[i] = k + 1 # rebus value is 1-indexed because 0 is reserved for non-rebus squares 

864 

865 def add_rebus_solution(self, solution: str) -> int: 

866 k = next((i for i, s in self.solutions.items() if s == solution), -1) 

867 if k < 0: 

868 k = (max(self.solutions) + 1) if self.solutions else 0 

869 self.solutions[k] = solution 

870 return k 

871 

872 def check_rebus_fill(self, indexes: int | list[int] | None = None, strict: bool = True) -> bool: 

873 if isinstance(indexes, int): 

874 indexes = [indexes] 

875 if indexes is None: 

876 indexes = self.get_rebus_squares() 

877 for index in indexes: 

878 if not self.is_rebus_square(index): 

879 raise ValueError(f'index {index} is not a rebus square') 

880 solution = self.get_rebus_solution(index) 

881 fill = self.get_rebus_fill(index) 

882 if solution != fill and (fill or strict): 

883 return False 

884 return True 

885 

886 def get_rebus_solution(self, index: int) -> str | None: 

887 if self.is_rebus_square(index): 

888 # rebus value is 1-indexed because 0 is reserved for non-rebus squares 

889 # so we need to subtract 1 to get the correct solution from the map 

890 return self.solutions[self.table[index] - 1] 

891 return None 

892 

893 def set_rebus_solution(self, index: int, solution: str) -> None: 

894 if self.is_rebus_square(index): 

895 solution_index = self.add_rebus_solution(solution) 

896 self.table[index] = solution_index + 1 

897 

898 def get_rebus_fill(self, index: int) -> str | None: 

899 if self.is_rebus_square(index): 

900 return self.fill[index] or None 

901 return None 

902 

903 def remove_rebus_squares(self, squares: int | list[int]) -> None: 

904 if isinstance(squares, int): 

905 squares = [squares] 

906 

907 for i in squares: 

908 self.table[i] = 0 

909 self._dirty = True 

910 

911 def remove_rebus_solution(self, solution: str | int) -> None: 

912 k = next((i for i, s in self.solutions.items() if s == solution), -1) if isinstance(solution, str) else solution 

913 if k >= 0: 

914 del self.solutions[k] 

915 for i, v in enumerate(self.table): 

916 if v == k + 1: # rebus value is 1-indexed because 0 is reserved for non-rebus squares 

917 self.table[i] = 0 

918 self._dirty = True 

919 

920 def set_rebus_fill(self, index: int, value: str) -> None: 

921 if self.is_rebus_square(index): 

922 self.fill[index] = value 

923 

924 def save(self) -> None: 

925 if self.has_rebus(): 

926 self.puzzle.extensions[Extensions.Rebus] = pack_bytes(self.table) 

927 if self.solutions: 

928 self.puzzle.extensions[Extensions.RebusSolutions] = self.puzzle.encode(dict_to_string(self.solutions)) 

929 else: 

930 self.puzzle.extensions.pop(Extensions.RebusSolutions, None) 

931 if any(self.fill) or Extensions.RebusFill in self.puzzle.extensions: 

932 s = PuzzleBuffer(encoding=self.puzzle.encoding) 

933 for cell_fill in self.fill: 

934 s.write_string(cell_fill) 

935 self.puzzle.extensions[Extensions.RebusFill] = s.tobytes() 

936 else: 

937 self.puzzle.extensions.pop(Extensions.RebusFill, None) 

938 elif self._dirty: 

939 self.puzzle.extensions.pop(Extensions.Rebus, None) 

940 self.puzzle.extensions.pop(Extensions.RebusSolutions, None) 

941 self.puzzle.extensions.pop(Extensions.RebusFill, None) 

942 

943 

944class Markup(PuzzleHelper): 

945 def __repr__(self) -> str: 

946 return f'Markup(marked_squares={len(self.get_markup_squares())})' 

947 

948 def __init__(self, puzzle: Puzzle) -> None: 

949 self.puzzle = puzzle 

950 self._dirty = False # track whether there are unsaved changes to the markup helper that need to be committed 

951 markup_data = self.puzzle.extensions.get(Extensions.Markup, b'') 

952 self.markup = parse_bytes(markup_data) or [0] * (self.puzzle.width * self.puzzle.height) 

953 

954 def clear_markup_squares(self, indices: list[int] | int, markup_types: list[GridMarkup] | GridMarkup | None = None) -> None: # noqa: E501 

955 if isinstance(indices, int): 

956 indices = [indices] 

957 markup_mask = sum(markup_types) if isinstance(markup_types, list) else markup_types if markup_types else 0xff 

958 for i in indices: 

959 self.markup[i] &= ~markup_mask 

960 self._dirty = True 

961 

962 def has_markup(self, markup_types: list[GridMarkup] | GridMarkup | None = None) -> bool: 

963 markup_mask = sum(markup_types) if isinstance(markup_types, list) else markup_types if markup_types else 0xff 

964 return any(bool(b & markup_mask) for b in self.markup) 

965 

966 def get_markup_squares(self, markup_types: list[GridMarkup] | GridMarkup | None = None) -> list[int]: 

967 markup_mask = sum(markup_types) if isinstance(markup_types, list) else markup_types if markup_types else 0xff 

968 return [i for i, b in enumerate(self.markup) if b & markup_mask] 

969 

970 def is_markup_square(self, index: int, markup_types: list[GridMarkup] | GridMarkup | None = None) -> bool: 

971 markup_mask = sum(markup_types) if isinstance(markup_types, list) else markup_types if markup_types else 0xff 

972 return bool(self.markup[index] & markup_mask) 

973 

974 def set_markup_squares(self, indices: list[int] | int, markup_type: list[GridMarkup] | GridMarkup | None = None) -> None: 

975 if isinstance(indices, int): 

976 indices = [indices] 

977 markup_mask = sum(markup_type) if isinstance(markup_type, list) else markup_type if markup_type else 0xff 

978 for i in indices: 

979 self.markup[i] |= markup_mask 

980 

981 def save(self) -> None: 

982 if self.has_markup(): 

983 self.puzzle.extensions[Extensions.Markup] = pack_bytes(self.markup) 

984 elif self._dirty: 

985 self.puzzle.extensions.pop(Extensions.Markup, None) 

986 

987 

988class TimerStatus(IntEnum): 

989 Running = 0 

990 Stopped = 1 

991 

992 

993class Timer(PuzzleHelper): 

994 def __repr__(self) -> str: 

995 return f'Timer(elapsed_seconds={self.elapsed_seconds}, status={self.status.name})' 

996 

997 def __init__(self, puzzle: Puzzle) -> None: 

998 self.puzzle = puzzle 

999 timer_data = self.puzzle.extensions.get(Extensions.Timer, b'0,1') 

1000 elapsed_str, status_str = timer_data.decode().split(',') 

1001 

1002 self.elapsed_seconds = int(elapsed_str) 

1003 self.status = TimerStatus(int(status_str)) 

1004 self._loaded = (self.elapsed_seconds, self.status) 

1005 

1006 def is_running(self) -> bool: 

1007 return self.status == TimerStatus.Running 

1008 

1009 def is_stopped(self) -> bool: 

1010 return self.status == TimerStatus.Stopped 

1011 

1012 def has_timer(self) -> bool: 

1013 # a timer the file didn't have only counts once its values are changed 

1014 return (Extensions.Timer in self.puzzle.extensions 

1015 or (self.elapsed_seconds, self.status) != self._loaded) 

1016 

1017 def save(self) -> None: 

1018 if self.has_timer(): 

1019 self.puzzle.extensions[Extensions.Timer] = f'{self.elapsed_seconds},{self.status}'.encode() 

1020 

1021 

1022# helper functions for cksums and scrambling 

1023def data_cksum(data: bytes, cksum: int = 0) -> int: 

1024 for b in data: 

1025 # right-shift one with wrap-around 

1026 lowbit = (cksum & 0x0001) 

1027 cksum = (cksum >> 1) 

1028 if lowbit: 

1029 cksum = (cksum | 0x8000) 

1030 

1031 # then add in the data and clear any carried bit past 16 

1032 cksum = (cksum + b) & 0xffff 

1033 

1034 return cksum 

1035 

1036 

1037def replace_chars(s: str, chars: str, replacement: str = '') -> str: 

1038 for ch in chars: 

1039 s = s.replace(ch, replacement) 

1040 return s 

1041 

1042 

1043def scramble_solution(solution: str, width: int, height: int, key: int, ignore_chars: str = BLACKSQUARE) -> str: 

1044 sq = square(solution, width, height) 

1045 data = restore(sq, scramble_string(replace_chars(sq, ignore_chars), key)) 

1046 return square(data, height, width) 

1047 

1048 

1049def scramble_string(s: str, key: int) -> str: 

1050 """ 

1051 s is the puzzle's solution in column-major order, omitting black squares: 

1052 i.e. if the puzzle is: 

1053 C A T 

1054 # # A 

1055 # # R 

1056 solution is CATAR 

1057 

1058 

1059 Key is a 4-digit number in the range 1000 <= key <= 9999 

1060 

1061 """ 

1062 digits = key_digits(key) 

1063 for k in digits: # foreach digit in the key 

1064 s = shift(s, digits) # for each char by each digit in the key in sequence 

1065 s = s[k:] + s[:k] # cut the sequence around the key digit 

1066 s = shuffle(s) # do a 1:1 shuffle of the 'deck' 

1067 

1068 return s 

1069 

1070 

1071def unscramble_solution(scrambled: str, width: int, height: int, key: int, ignore_chars: str = BLACKSQUARE) -> str: 

1072 # width and height are reversed here 

1073 sq = square(scrambled, width, height) 

1074 data = restore(sq, unscramble_string(replace_chars(sq, ignore_chars), key)) 

1075 return square(data, height, width) 

1076 

1077 

1078def unscramble_string(s: str, key: int) -> str: 

1079 digits = key_digits(key) 

1080 l = len(s) # noqa: E741 

1081 for k in digits[::-1]: 

1082 s = unshuffle(s) 

1083 s = s[l-k:] + s[:l-k] 

1084 s = unshift(s, digits) 

1085 

1086 return s 

1087 

1088 

1089def scrambled_cksum(scrambled: str, width: int, height: int, ignore_chars: str = BLACKSQUARE, encoding: str = ENCODING) -> int: 

1090 data = replace_chars(square(scrambled, width, height), ignore_chars) 

1091 return data_cksum(data.encode(encoding, ENCODING_ERRORS)) 

1092 

1093 

1094def key_digits(key: int) -> list[int]: 

1095 return [int(c) for c in str(key).zfill(4)] 

1096 

1097 

1098def square(data: str, w: int, h: int) -> str: 

1099 aa = [data[i:i+w] for i in range(0, len(data), w)] 

1100 return ''.join( 

1101 [''.join([aa[r][c] for r in range(h)]) for c in range(w)] 

1102 ) 

1103 

1104 

1105def shift(s: str, key: list[int]) -> str: 

1106 atoz = string.ascii_uppercase 

1107 return ''.join( 

1108 atoz[(atoz.index(c) + key[i % len(key)]) % len(atoz)] 

1109 for i, c in enumerate(s) 

1110 ) 

1111 

1112 

1113def unshift(s: str, key: list[int]) -> str: 

1114 return shift(s, [-k for k in key]) 

1115 

1116 

1117def shuffle(s: str) -> str: 

1118 mid = len(s) // 2 

1119 return ''.join(a + b for a, b in zip(s[mid:], s[:mid])) + (s[-1] if len(s) % 2 else '') 

1120 

1121 

1122def unshuffle(s: str) -> str: 

1123 return s[1::2] + s[::2] 

1124 

1125 

1126def restore(s: str, t: Iterable[str]) -> str: 

1127 """ 

1128 s is the source string, it can contain '.' 

1129 t is the target, it's smaller than s by the number of '.'s in s 

1130 

1131 Each char in s is replaced by the corresponding 

1132 char in t, jumping over '.'s in s. 

1133 

1134 >>> restore('ABC.DEF', 'XYZABC') 

1135 'XYZ.ABC' 

1136 """ 

1137 t = (c for c in t) 

1138 return ''.join(next(t) if not is_blacksquare(c) else c for c in s) 

1139 

1140 

1141def is_blacksquare(c: str | int) -> bool: 

1142 if isinstance(c, int): 

1143 c = chr(c) 

1144 return c in [BLACKSQUARE, BLACKSQUARE2] 

1145 

1146 

1147# 

1148# functions for parsing / serializing primitives 

1149# 

1150 

1151 

1152def parse_bytes(s: bytes) -> list[int]: 

1153 return list(struct.unpack('B' * len(s), s)) 

1154 

1155 

1156def pack_bytes(a: list[int]) -> bytes: 

1157 return struct.pack('B' * len(a), *a) 

1158 

1159 

1160# dict string format is k1:v1;k2:v2;...;kn:vn; 

1161# (for whatever reason there's a trailing ';') 

1162def parse_dict(s: str) -> dict[str, str]: 

1163 return dict(p.split(':', 1) for p in s.split(';') if ':' in p) 

1164 

1165 

1166def dict_to_string(d: dict[int, str]) -> str: 

1167 # Across Lite format right-aligns keys in a 2-char field: ' 0:VAL;', '13:VAL;' 

1168 return ';'.join(f'{k:>2}:{v}' for k, v in d.items()) + ';' 

1169 

1170 

1171def from_text_format(s: str) -> Puzzle: 

1172 d = text_file_as_dict(s) 

1173 

1174 if 'ACROSS PUZZLE' in d: 

1175 # file_version = 'v1' 

1176 pass 

1177 elif 'ACROSS PUZZLE V2' in d or 'ACROSS PUZZLE v2' in d: 

1178 # file_version = 'v2' 

1179 pass 

1180 else: 

1181 raise PuzzleFormatError('Not a valid Across Lite text puzzle') 

1182 

1183 p = Puzzle() 

1184 across_clues: list[str] = [] 

1185 down_clues: list[str] = [] 

1186 if 'TITLE' in d: 

1187 p.title = d['TITLE'] 

1188 if 'AUTHOR' in d: 

1189 p.author = d['AUTHOR'] 

1190 if 'COPYRIGHT' in d: 

1191 p.copyright = d['COPYRIGHT'] 

1192 if 'SIZE' in d: 

1193 w, h = d['SIZE'].split('x') 

1194 p.width = int(w) 

1195 p.height = int(h) 

1196 # parse REBUS section before GRID — markers in the grid reference it 

1197 # format: marker:EXTENDED_SOLUTION:SHORT_CHAR (one per line) 

1198 # optional flag line: MARK; (circles all lowercase-letter cells in the grid) 

1199 rebus_map: dict[str, tuple[str, str]] = {} # marker char -> (extended_solution, short_char) 

1200 mark_flag = False 

1201 if 'REBUS' in d: 

1202 for line in d['REBUS'].splitlines(): 

1203 line = line.strip() 

1204 if not line: 

1205 continue 

1206 if ':' not in line: 

1207 # flag line, e.g. "MARK;" 

1208 if 'MARK' in [f.strip().upper() for f in line.split(';') if f.strip()]: 

1209 mark_flag = True 

1210 else: 

1211 parts = line.split(':') 

1212 marker = parts[0] 

1213 extended = parts[1] if len(parts) > 1 else '' 

1214 short = parts[2] if len(parts) > 2 else (extended[0] if extended else marker) 

1215 if marker: 

1216 rebus_map[marker] = (extended, short) 

1217 

1218 rebus_cells: dict[int, str] = {} # cell index -> extended solution 

1219 mark_cells: list[int] = [] # cell indices to be circled (MARK flag) 

1220 if 'GRID' in d: 

1221 solution_lines = d['GRID'].splitlines() 

1222 raw = ''.join(line.strip() for line in solution_lines if line.strip()) 

1223 if rebus_map or mark_flag: 

1224 solution_chars: list[str] = [] 

1225 for i, c in enumerate(raw): 

1226 if c in rebus_map: 

1227 extended, short = rebus_map[c] 

1228 solution_chars.append(short) 

1229 rebus_cells[i] = extended 

1230 elif mark_flag and c.islower() and not is_blacksquare(c): 

1231 solution_chars.append(c.upper()) 

1232 mark_cells.append(i) 

1233 else: 

1234 solution_chars.append(c) 

1235 p.solution = ''.join(solution_chars) 

1236 else: 

1237 p.solution = raw 

1238 if 'ACROSS' in d: 

1239 across_clues.extend(line.strip() for line in d['ACROSS'].splitlines() if line.strip()) 

1240 if 'DOWN' in d: 

1241 down_clues.extend(line.strip() for line in d['DOWN'].splitlines() if line.strip()) 

1242 if 'NOTEPAD' in d: 

1243 p.notes = d['NOTEPAD'] 

1244 

1245 if p.solution: 

1246 if BLACKSQUARE2 in p.solution: 

1247 p.puzzletype = PuzzleType.Diagramless 

1248 p.fill = ''.join(c if is_blacksquare(c) else BLANKSQUARE for c in p.solution) 

1249 across, down = get_grid_numbering(p.fill, p.width, p.height) 

1250 # we have to match puzfile's expected clue ordering or we won't be able to 

1251 # write the puzzle out as a valid .puz file 

1252 p.clues = [''] * (len(across) + len(down)) 

1253 for i in range(len(across)): 

1254 clue = across_clues[i] if i < len(across_clues) else '' 

1255 across[i]['clue'] = clue 

1256 p.clues[across[i]['clue_index']] = clue 

1257 for i in range(len(down)): 

1258 clue = down_clues[i] if i < len(down_clues) else '' 

1259 down[i]['clue'] = clue 

1260 p.clues[down[i]['clue_index']] = clue 

1261 

1262 if rebus_cells: 

1263 for i, extended in rebus_cells.items(): 

1264 p.rebus().add_rebus_squares(i, extended) 

1265 if mark_cells: 

1266 p.markup().set_markup_squares(mark_cells, GridMarkup.Circled) 

1267 

1268 return p 

1269 

1270 

1271def text_file_as_dict(s: str) -> dict[str, str]: 

1272 d: dict[str, str] = {} 

1273 k = '' 

1274 v: list[str] = [] 

1275 for line in s.splitlines(): 

1276 line = line.strip() 

1277 if line.startswith('<') and line.endswith('>'): 

1278 if k: 

1279 d[k] = '\n'.join(v) 

1280 k = line[1:-1] 

1281 v = [] 

1282 else: 

1283 v.append(line) 

1284 

1285 if k: 

1286 d[k] = '\n'.join(v) 

1287 return d 

1288 

1289 

1290def to_text_format(p: Puzzle, text_version: str = 'v1') -> str: 

1291 TAB = '\t' # most lines begin indented with whitespace 

1292 lines: list[str] = [] 

1293 

1294 has_rebus = p.has_rebus() 

1295 # text only supports circled cells using the MARK flag 

1296 has_mark = p.has_markup() and p.markup().has_markup([GridMarkup.Circled]) 

1297 

1298 # REBUS section and MARK flag require v2 format; auto-upgrade if needed 

1299 if (has_rebus or has_mark) and text_version == 'v1': 

1300 text_version = 'v2' 

1301 

1302 if text_version == 'v1': 

1303 lines.append('<ACROSS PUZZLE>') 

1304 elif text_version: 

1305 lines.append(f'<ACROSS PUZZLE {text_version}>') 

1306 else: 

1307 raise ValueError("invalid text_version") 

1308 

1309 lines.append('<TITLE>') 

1310 lines.append(TAB + p.title) 

1311 lines.append('<AUTHOR>') 

1312 lines.append(TAB + p.author) 

1313 lines.append('<COPYRIGHT>') 

1314 lines.append(TAB + p.copyright) 

1315 lines.append('<SIZE>') 

1316 lines.append(TAB + f'{p.width}x{p.height}') 

1317 

1318 # assign a single-char marker to each unique rebus solution 

1319 # digits 1-9 then lowercase a-z, matching the v2 spec convention 

1320 solution_to_marker: dict[str, str] = {} 

1321 rebus_squares: set[int] = set() 

1322 solution_to_short_char: dict[str, str] = {} 

1323 if has_rebus: 

1324 _marker_chars = [str(i) for i in range(1, 10)] + list('abcdefghijklmnopqrstuvwxyz') 

1325 for idx, solution in enumerate(p.rebus().solutions.values()): 

1326 if idx < len(_marker_chars): 

1327 solution_to_marker[solution] = _marker_chars[idx] 

1328 rebus_squares = set(p.rebus().get_rebus_squares()) 

1329 for i in rebus_squares: 

1330 sol = p.rebus().get_rebus_solution(i) 

1331 if sol and sol not in solution_to_short_char: 

1332 solution_to_short_char[sol] = p.solution[i] 

1333 

1334 circled_squares: set[int] = set(p.markup().get_markup_squares(GridMarkup.Circled)) if has_mark else set() 

1335 

1336 lines.append('<GRID>') 

1337 for row_idx in range(p.height): 

1338 row = '' 

1339 for col_idx in range(p.width): 

1340 i = row_idx * p.width + col_idx 

1341 if i in rebus_squares: 

1342 sol = p.rebus().get_rebus_solution(i) 

1343 row += solution_to_marker.get(sol or '', p.solution[i]) 

1344 elif i in circled_squares: 

1345 row += p.solution[i].lower() 

1346 else: 

1347 row += p.solution[i] 

1348 lines.append(TAB + row) 

1349 

1350 if has_rebus or has_mark: 

1351 lines.append('<REBUS>') 

1352 if has_mark: 

1353 lines.append(TAB + 'MARK;') 

1354 if has_rebus: 

1355 for solution, marker in solution_to_marker.items(): 

1356 short_char = solution_to_short_char.get(solution, solution[0]) 

1357 lines.append(TAB + f'{marker}:{solution}:{short_char}') 

1358 

1359 # get clues in across/down order 

1360 numbering = p.clue_numbering() 

1361 lines.append('<ACROSS>') 

1362 for clue in numbering.across: 

1363 lines.append(TAB + (clue['clue'] or '')) 

1364 lines.append('<DOWN>') 

1365 for clue in numbering.down: 

1366 lines.append(TAB + (clue['clue'] or '')) 

1367 

1368 lines.append('<NOTEPAD>') 

1369 lines.append(p.notes) # no tab here, idk why 

1370 

1371 return '\n'.join(lines)