Skip to content

Crossword API

blacksquare.Crossword

An object representing a crossword puzzle backed by an ultra-fast Rust engine.

Source code in src/blacksquare/crossword.py
  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
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
class Crossword:
    """An object representing a crossword puzzle backed by an ultra-fast Rust engine."""

    def __init__(
        self,
        num_rows: int | None = None,
        num_cols: int | None = None,
        grid: list[list[str]] | np.ndarray | None = None,
        symmetry: Symmetry | None = Symmetry.ROTATIONAL,
        word_list: WordList | None = None,
        display_size_px: int = 450,
        _inner: PyCrossword | None = None,
    ):
        """Creates a new Crossword object."""
        self._cached_cells: dict[CellIndex, Cell] = {}
        self._cached_words: dict[WordIndex, Word] = {}

        if _inner is not None:
            self._inner = _inner
        else:
            assert (num_rows is not None) ^ (grid is not None), (
                "Either specify shape or provide grid."
            )

            rust_sym = self._to_rust_sym(symmetry)

            if num_rows:
                n_rows = num_rows
                n_cols = num_cols if num_cols else n_rows
                if symmetry and symmetry.requires_square and n_rows != n_cols:
                    raise ValueError(
                        f"{symmetry.value} symmetry requires a square grid."
                    )
                self._inner = PyCrossword(
                    num_rows=n_rows,
                    num_cols=n_cols,
                    grid=None,
                    symmetry=rust_sym,
                    display_size_px=display_size_px,
                )
            elif grid is not None:
                assert np.all([len(r) == len(grid[0]) for r in grid])
                grid_list = []
                for r in grid:
                    row_strs = []
                    for val in r:
                        if isinstance(val, Cell):
                            row_strs.append(val.str)
                        elif isinstance(val, SpecialCellValue):
                            row_strs.append(val.str)
                        else:
                            row_strs.append(str(val))
                    grid_list.append(row_strs)

                n_rows = len(grid_list)
                n_cols = len(grid_list[0])
                if symmetry and symmetry.requires_square and n_rows != n_cols:
                    raise ValueError(
                        f"{symmetry.value} symmetry requires a square grid."
                    )

                self._inner = PyCrossword(
                    num_rows=None,
                    num_cols=None,
                    grid=grid_list,
                    symmetry=rust_sym,
                    display_size_px=display_size_px,
                )

        self.word_list = word_list if word_list is not None else DEFAULT_WORDLIST

    @staticmethod
    def _to_rust_sym(sym: Symmetry | None) -> RustSymmetry | None:
        if sym is None:
            return None
        mapping = {
            Symmetry.ROTATIONAL: RustSymmetry.Rotational,
            Symmetry.FULL: RustSymmetry.Full,
            Symmetry.VERTICAL: RustSymmetry.Vertical,
            Symmetry.HORIZONTAL: RustSymmetry.Horizontal,
            Symmetry.BIAXIAL: RustSymmetry.Biaxial,
            Symmetry.NE_DIAGONAL: RustSymmetry.NeDiagonal,
            Symmetry.NW_DIAGONAL: RustSymmetry.NwDiagonal,
        }
        return mapping.get(sym)

    @staticmethod
    def _from_rust_sym(sym: RustSymmetry | None) -> Symmetry | None:
        if sym is None:
            return None
        return Symmetry(sym.value)

    @staticmethod
    def _to_rust_dir(d: Direction) -> RustDirection:
        return RustDirection.Across if d == Direction.ACROSS else RustDirection.Down

    @staticmethod
    def _from_rust_dir(d: RustDirection) -> Direction:
        return Direction.ACROSS if d.value == "Across" else Direction.DOWN

    @property
    def num_rows(self) -> int:
        """The number of rows in the puzzle"""
        return self._inner.num_rows

    @property
    def num_cols(self) -> int:
        """The number of columns in the puzzle"""
        return self._inner.num_cols

    @property
    def symmetry(self) -> Symmetry | None:
        return self._from_rust_sym(self._inner.symmetry)

    @symmetry.setter
    def symmetry(self, sym: Symmetry | None):
        self._inner.symmetry = self._to_rust_sym(sym)

    @property
    def display_size_px(self) -> int:
        return self._inner.display_size_px

    @display_size_px.setter
    def display_size_px(self, px: int):
        self._inner.display_size_px = px

    @property
    def _grid(self) -> np.ndarray:
        rows, cols = self.num_rows, self.num_cols
        cells = [self[r, c] for r in range(rows) for c in range(cols)]
        return np.array(cells, dtype=object).reshape((rows, cols))

    @property
    def _numbers(self) -> np.ndarray:
        return np.array(self._inner.numbers_grid(), dtype=int)

    @property
    def _across(self) -> np.ndarray:
        return np.array(self._inner.across_numbers_grid(), dtype=int)

    @property
    def _down(self) -> np.ndarray:
        return np.array(self._inner.down_numbers_grid(), dtype=int)

    @property
    def _words(self) -> dict[WordIndex, Word]:
        res = {}
        for r_dir, num in self._inner.iter_word_indices():
            py_dir = self._from_rust_dir(r_dir)
            res[(py_dir, num)] = self[py_dir, num]
        return res

    @overload
    def __getitem__(self, key: tuple[Direction, int]) -> Word: ...
    @overload
    def __getitem__(self, key: tuple[int, int]) -> Cell: ...
    @overload
    def __getitem__(self, key: WordIndex) -> Word: ...
    @overload
    def __getitem__(self, key: CellIndex) -> Cell: ...
    def __getitem__(self, key: CellIndex | WordIndex | tuple[Any, Any]) -> Cell | Word:
        if isinstance(key, tuple) and len(key) == 2:
            k0, k1 = key
            if isinstance(k0, Direction) and is_intlike(k1):
                num = int(k1)
                word_idx = (k0, num)
                r_dir = self._to_rust_dir(k0)
                val = self._inner.get_word_value(r_dir, num)
                if val is not None:
                    if word_idx not in self._cached_words:
                        self._cached_words[word_idx] = Word(self, k0, num)
                    return self._cached_words[word_idx]
                else:
                    raise IndexError
            elif not isinstance(k0, Direction) and is_intlike(k0) and is_intlike(k1):
                r, c = int(k0), int(k1)
                if r < 0:
                    r += self.num_rows
                if c < 0:
                    c += self.num_cols
                if 0 <= r < self.num_rows and 0 <= c < self.num_cols:
                    if (r, c) not in self._cached_cells:
                        self._cached_cells[(r, c)] = Cell(self, (r, c))
                    return self._cached_cells[(r, c)]
                else:
                    raise IndexError
        raise IndexError

    def __setitem__(self, key, value):
        if isinstance(key, tuple) and len(key) == 2:
            k0, k1 = key
            if isinstance(k0, Direction) and is_intlike(k1):
                self.set_word((k0, int(k1)), value)
            elif not isinstance(k0, Direction) and is_intlike(k0) and is_intlike(k1):
                self.set_cell((int(k0), int(k1)), value)
            else:
                raise IndexError
        else:
            raise IndexError

    def set_cell(self, index: CellIndex, value: CellValue) -> None:
        """Sets a cell to a new value.

        Args:
            index: The index of the cell.
            value: The new value of the cell.
        """
        if isinstance(value, (list, tuple, int, float, Crossword, Word)):
            raise ValueError(f"Invalid cell value type: {type(value)}")

        r, c = int(index[0]), int(index[1])
        if r < 0:
            r += self.num_rows
        if c < 0:
            c += self.num_cols
        if not (0 <= r < self.num_rows and 0 <= c < self.num_cols):
            raise IndexError(f"Cell index {(r, c)} out of bounds")

        if isinstance(value, Rebus):
            self._inner.set_cell_rebus(r, c, value.across, value.down)
        elif isinstance(value, SpecialCellValue):
            self._inner.set_cell_value(r, c, value.str)
        elif isinstance(value, Cell):
            if isinstance(value.value, Rebus):
                self._inner.set_cell_rebus(r, c, value.value.across, value.value.down)
            else:
                self._inner.set_cell_value(r, c, value.str)
        elif isinstance(value, str):
            if value in SpecialCellValue.BLACK.input_str_reprs:
                self._inner.set_cell_value(r, c, SpecialCellValue.BLACK.str)
            elif value in SpecialCellValue.EMPTY.input_str_reprs:
                self._inner.set_cell_value(r, c, SpecialCellValue.EMPTY.str)
            elif len(value) == 1:
                self._inner.set_cell_value(r, c, value.upper())
            else:
                clean = value.strip()
                if clean in SpecialCellValue.BLACK.input_str_reprs:
                    self._inner.set_cell_value(r, c, SpecialCellValue.BLACK.str)
                elif clean in SpecialCellValue.EMPTY.input_str_reprs:
                    self._inner.set_cell_value(r, c, SpecialCellValue.EMPTY.str)
                elif len(clean) == 1:
                    self._inner.set_cell_value(r, c, clean.upper())
                else:
                    raise ValueError(f"Invalid cell value length: {value!r}")
        else:
            raise ValueError(f"Invalid cell value type: {type(value)}")

    def set_word(self, word_index: WordIndex, value: str) -> None:
        """Sets a word to a new value.

        Args:
            word_index: The index of the word.
            value: The new value of the word.
        """
        if not isinstance(value, str):
            raise ValueError(f"Word value must be str, got {type(value)}")

        direction, num = word_index[0], int(word_index[1])
        r_dir = self._to_rust_dir(direction)
        cell_indices = self._inner.get_word_cell_indices(r_dir, num)
        if cell_indices is None:
            raise IndexError(f"Word {word_index} not found in grid")

        word_cells = [self[r, c] for r, c in cell_indices]
        new_values = _parse_word_string_to_cell_values(word_cells, direction, value)
        for (r, c), new_val in zip(cell_indices, new_values):
            self.set_cell((r, c), new_val)

    def get_cell_number(self, cell_index: CellIndex) -> int | None:
        """Gets the crossword numeral at a given cell, if it exists.

        Args:
            cell_index: The index of the cell.

        Returns:
            The crossword number in that cell, if any.
        """
        r, c = int(cell_index[0]), int(cell_index[1])
        if r < 0:
            r += self.num_rows
        if c < 0:
            c += self.num_cols
        return self._inner.get_cell_number(r, c)

    def get_word_cells(self, word_index: WordIndex) -> list[Cell]:
        """Gets the cells for a word index.

        Args:
            word_index: The word index.

        Returns:
            The list of Cells in the word.
        """
        r_dir = self._to_rust_dir(word_index[0])
        num = int(word_index[1])
        coords = self._inner.get_word_cell_indices(r_dir, num)
        if coords is not None:
            return [self[r, c] for r, c in coords]
        return []

    def get_indices(self, word_index: WordIndex) -> list[CellIndex]:
        """Gets the list of cell indices for a given word.

        Args:
            word_index: The index of the desired word.

        Returns:
            A list of cell indices that belong to the word.
        """
        r_dir = self._to_rust_dir(word_index[0])
        num = int(word_index[1])
        coords = self._inner.get_word_cell_indices(r_dir, num)
        if coords is not None:
            return coords
        raise IndexError(f"Word {word_index} not found")

    def get_word_at_index(self, index: CellIndex, direction: Direction) -> Word | None:
        """Gets the word that passes through a cell in a given direction.

        Args:
            index: The index of the cell.
            direction: The direction of the word.

        Returns:
            The word passing through the index in the provided direction.
        """
        r, c = int(index[0]), int(index[1])
        if r < 0:
            r += self.num_rows
        if c < 0:
            c += self.num_cols
        r_dir = self._to_rust_dir(direction)
        res = self._inner.get_word_at_cell(r, c, r_dir)
        if res is not None:
            py_dir = self._from_rust_dir(res[0])
            return self[py_dir, res[1]]
        return None

    def get_symmetric_cell_index(
        self, index: CellIndex, force_list: bool = False
    ) -> CellIndex | list[CellIndex] | None:
        """Gets the index of a symmetric grid cell. Useful for enforcing symmetry.

        Args:
            index: The input cell index.
            force_list: Whether to require that single indices are returned as a list.

        Returns:
            The index (or indices) of the cell symmetric to the input.
        """
        if not self.symmetry:
            return [] if force_list else None
        r, c = int(index[0]), int(index[1])
        if r < 0:
            r += self.num_rows
        if c < 0:
            c += self.num_cols
        images = self._inner.get_symmetric_cell_indices(r, c)
        if not images:
            return [] if force_list else None
        if self.symmetry.is_multi_image or force_list:
            return images
        else:
            return images[0]

    def get_symmetric_word_index(
        self, word_index: WordIndex, force_list: bool = False
    ) -> WordIndex | list[WordIndex] | None:
        """Gets the index of a symmetric word. Useful for enforcing symmetry.

        Args:
            word_index: The input word index.
            force_list: Whether to require that single indices are returned as a list.

        Returns:
            The index (or indices) of the word symmetric to the input.
        """
        if not self.symmetry:
            return [] if force_list else None
        r_dir = self._to_rust_dir(word_index[0])
        images = self._inner.get_symmetric_word_indices(r_dir, int(word_index[1]))
        py_images = [(self._from_rust_dir(d), num) for d, num in images]
        if not py_images:
            return [] if force_list else None
        if self.symmetry.is_multi_image or force_list:
            return py_images
        else:
            return py_images[0]

    def get_disconnected_open_subgrids(self) -> list[list[WordIndex]]:
        """Returns a list of open subgrids, as represented by a list of words.

        Returns:
            A list of open subgrids.
        """
        raw_subs = self._inner.get_disconnected_open_subgrids()
        return [[(self._from_rust_dir(d), num) for d, num in sub] for sub in raw_subs]

    def hashable_state(
        self, word_indices: list[WordIndex]
    ) -> tuple[tuple[WordIndex, str], ...]:
        """Returns a list of tuple of (word index, current value) pairs in sorted order.

        Args:
            word_indices: The list of word indices of interest.

        Returns:
            A tuple of (word index, value) tuples
        """
        sorted_indices = sorted(word_indices)
        return tuple((i, self[i].value) for i in sorted_indices)

    def iterwords(
        self, direction: Direction | None = None, only_open: bool = False
    ) -> Iterator[Word]:
        """Method for iterating over the words in the crossword.

        Args:
            direction: If provided, limits the iterator to only the given direction.
            only_open: Whether to only return open words. Defaults to False.

        Yields:
            An iterator of Word objects.
        """
        r_dir = self._to_rust_dir(direction) if direction is not None else None
        for r_d, num in self._inner.iter_word_indices(r_dir, only_open):
            py_dir = self._from_rust_dir(r_d)
            yield self[py_dir, num]

    def itercells(self) -> Iterator[Cell]:
        """Method for iterating over the cells in the crossword.

        Yields:
            An iterator of Cell objects. Ordered left to right, top to bottom.
        """
        for r in range(self.num_rows):
            for c in range(self.num_cols):
                yield self[r, c]

    @property
    def clues(self) -> dict[WordIndex, str]:
        """A dict mapping word index to clue."""
        return {
            (self._from_rust_dir(d), num): clue
            for (d, num), clue in self._inner.get_clues()
        }

    def copy(self) -> Crossword:
        """Returns a copy of the current crossword.

        Returns:
            A copy of the current Crossword object.
        """
        return Crossword(
            _inner=self._inner.copy(),
            word_list=self.word_list,
            display_size_px=self.display_size_px,
        )

    def __deepcopy__(self, memo):
        return self.copy()

    def __repr__(self):
        words = list(self.iterwords())
        if not words:
            return 'Crossword("")'
        longest_filled_word = max(words, key=lambda w: len(w) if not w.is_open() else 0)
        return f'Crossword("{longest_filled_word.value}")'

    def fill(
        self,
        word_list: WordList | None = None,
        timeout: float | None = 30.0,
        temperature: float = 0.0,
        score_filter: float | None = None,
        allow_repeats: bool = False,
        upweight_diverse_letters: bool = False,
        show_progress: bool = True,
        progress_callback: Any | None = None,
    ) -> Crossword | None:
        """Searches for a possible fill, and returns the result as a new Crossword
        object. Backed by the native Rust backtracking solver.

        Args:
            word_list: An optional word list to use instead of the default.
            timeout: The maximum time in seconds to search before returning.
            temperature: A parameter to control randomness.
            score_filter: A threshold to apply to the word list before filling.
            allow_repeats: Whether to allow duplicate words in the grid.
            upweight_diverse_letters: Whether to upweight rare/diverse letters
                (J, Z, Q, X, etc.) during crossing candidate evaluation.
                Defaults to False.
            show_progress: Whether to display live in-progress grid updates
                for long-running searches (>100ms). Automatically adapts to
                Jupyter/Colab notebooks and terminal registers. Defaults to True.
            progress_callback: An optional custom callback invoked on progress updates with
                signature `(grid_str, elapsed_secs, states_visited, is_final, is_solved)`.

        Returns:
            The filled Crossword, or None if no solution found / timed out.
        """
        wl = word_list if word_list is not None else self.word_list

        cb = progress_callback
        if cb is None and show_progress:
            if _is_notebook():
                handle = None

                def _nb_progress(
                    grid_str: str,
                    elapsed: float,
                    states: int,
                    is_final: bool,
                    is_solved: bool,
                ) -> None:
                    nonlocal handle
                    try:
                        ipy_disp = importlib.import_module("IPython.display")
                        display = getattr(ipy_disp, "display", None)
                        html_cls = getattr(ipy_disp, "HTML", None)
                        pretty = getattr(ipy_disp, "Pretty", None)
                        if display is None:
                            return

                        if is_final:
                            if handle is not None:
                                empty = html_cls("") if html_cls is not None else ""
                                handle.update(empty)
                                handle = None
                            return

                        status = f"Fill in Progress [Elapsed: {elapsed:.2f}s | States: {states}]"
                        text = f"=== Crossword {status} ===\n{grid_str}"
                        content = pretty(text) if pretty is not None else text

                        if handle is None:
                            handle = display(content, display_id=True)
                        else:
                            handle.update(content)
                    except Exception:
                        pass

                cb = _nb_progress
            else:
                displayed_lines = [0]

                def _term_progress(
                    grid_str: str,
                    elapsed: float,
                    states: int,
                    is_final: bool,
                    is_solved: bool,
                ) -> None:
                    if is_final:
                        if displayed_lines[0] > 0:
                            sys.stderr.write(
                                f"\x1b[{displayed_lines[0]}A\r\x1b[0J\x1b[?25h"
                            )
                            sys.stderr.flush()
                            displayed_lines[0] = 0
                        return

                    status = (
                        f"Fill in Progress [Elapsed: {elapsed:.2f}s | States: {states}]"
                    )
                    header = f"=== Crossword {status} ==="
                    lines = [header] + grid_str.splitlines()
                    new_count = len(lines)

                    buf = []
                    if displayed_lines[0] == 0:
                        buf.append("\x1b[?25l")
                    else:
                        buf.append(f"\x1b[{displayed_lines[0]}A\r")

                    for line in lines:
                        buf.append(f"\x1b[K{line}\n")

                    if displayed_lines[0] > new_count:
                        for _ in range(displayed_lines[0] - new_count):
                            buf.append("\x1b[K\n")
                        buf.append(f"\x1b[{displayed_lines[0] - new_count}A\r")

                    displayed_lines[0] = new_count
                    sys.stderr.write("".join(buf))
                    sys.stderr.flush()

                cb = _term_progress

        filled_inner = self._inner.fill(
            wl._inner,
            timeout=timeout,
            temperature=temperature,
            score_filter=score_filter,
            allow_repeats=allow_repeats,
            upweight_diverse_letters=upweight_diverse_letters,
            progress_callback=cb,
        )
        if filled_inner is not None:
            return Crossword(
                _inner=filled_inner,
                word_list=wl,
                display_size_px=self.display_size_px,
            )
        return None

    @classmethod
    def from_puz(
        cls,
        source: str | os.PathLike[str] | bytes | BinaryIO,
        word_list: WordList | None = None,
    ) -> Crossword:
        """Creates a Crossword object from a .puz file path, bytes, or file-like object.

        Restores the full grid, words, clues, rebus cells (from GRBS/RTBL extensions),
        and circled cells (from GEXT extension).
        """
        if isinstance(source, (str, os.PathLike)):
            with open(source, "rb") as f:
                data = f.read()
        elif isinstance(source, bytes):
            data = source
        elif hasattr(source, "read"):
            data = source.read()
        else:
            raise TypeError(f"Unsupported source type for from_puz: {type(source)}")

        puz_data = PuzData.from_bytes(data)
        xw = cls(
            num_rows=puz_data.height,
            num_cols=puz_data.width,
            symmetry=None,
            word_list=word_list,
        )

        # Rebus reconstruction
        rebus_dict: dict[int, str] = {}
        if ExtensionCode.RebusSolutions in puz_data.extensions:
            rtbl_str = puz_data.extensions[ExtensionCode.RebusSolutions].decode(
                puz_data.encoding, "replace"
            )
            rebus_dict = parse_rebus_table(rtbl_str)

        grbs_data = puz_data.extensions.get(ExtensionCode.Rebus, b"")
        gext_data = puz_data.extensions.get(ExtensionCode.Markup, b"")

        for r in range(puz_data.height):
            for c in range(puz_data.width):
                idx = r * puz_data.width + c
                ch = puz_data.solution[idx]
                if ch in [BLACKSQUARE, BLACKSQUARE2, "#"]:
                    xw[r, c] = SpecialCellValue.BLACK
                elif grbs_data and idx < len(grbs_data) and grbs_data[idx] > 0:
                    k = grbs_data[idx] - 1
                    rebus_val = rebus_dict.get(k, ch)
                    xw[r, c] = Rebus(rebus_val)
                elif ch in [BLANKSQUARE, " ", "?", "_"]:
                    xw[r, c] = SpecialCellValue.EMPTY
                else:
                    xw[r, c] = ch

                if gext_data and idx < len(gext_data):
                    if gext_data[idx] & GridMarkup.Circled:
                        xw[r, c].circled = True

        sorted_words = sorted(
            list(xw.iterwords()), key=lambda w: (w.number, w.direction)
        )
        for w, clue_text in zip(sorted_words, puz_data.clues):
            w.clue = clue_text

        return xw

    def to_puz(
        self,
        target: str | os.PathLike[str] | BinaryIO | None = None,
        *,
        title: str = "",
        author: str = "",
        copyright: str = "",
        notes: str = "",
    ) -> bytes:
        """Exports the Crossword object to Across Lite .puz binary format.

        Saves full grid solutions, clues, rebus cells (via GRBS and RTBL extensions),
        and circled cells (via GEXT extension). If target is provided, writes to the
        file or stream; otherwise returns the raw bytes.
        """
        puz_data = PuzData(version="1.3")
        puz_data.width = self.num_cols
        puz_data.height = self.num_rows
        puz_data.title = title
        puz_data.author = author
        puz_data.copyright = copyright
        puz_data.notes = notes

        n_cells = self.num_rows * self.num_cols
        sol_chars: list[str] = []
        fill_chars: list[str] = []

        rebus_map: dict[str, int] = {}
        grbs_bytes = bytearray(n_cells)
        gext_bytes = bytearray(n_cells)
        has_rebus = False
        has_gext = False

        for r in range(self.num_rows):
            for c in range(self.num_cols):
                idx = r * self.num_cols + c
                cell = self[r, c]
                if cell == SpecialCellValue.BLACK:
                    sol_chars.append(BLACKSQUARE)
                    fill_chars.append(BLACKSQUARE)
                else:
                    fill_chars.append(BLANKSQUARE)
                    if isinstance(cell.value, Rebus):
                        has_rebus = True
                        rebus_str = str(cell.value)
                        if rebus_str not in rebus_map:
                            rebus_map[rebus_str] = len(rebus_map)
                        k = rebus_map[rebus_str]
                        grbs_bytes[idx] = k + 1
                        sol_chars.append(cell.value.across[0])
                    elif cell.is_open():
                        sol_chars.append(BLANKSQUARE)
                    else:
                        sol_chars.append(cell.str[0] if cell.str else BLANKSQUARE)

                if cell.circled:
                    has_gext = True
                    gext_bytes[idx] |= GridMarkup.Circled

        puz_data.solution = "".join(sol_chars)
        puz_data.fill = "".join(fill_chars)

        sorted_words = sorted(
            list(self.iterwords()), key=lambda w: (w.number, w.direction)
        )
        puz_data.clues = [w.clue or "" for w in sorted_words]

        if has_rebus:
            puz_data.extensions[ExtensionCode.Rebus] = bytes(grbs_bytes)
            inv_rebus = {k: v for v, k in rebus_map.items()}
            puz_data.extensions[ExtensionCode.RebusSolutions] = puz_data.encode(
                serialize_rebus_table(inv_rebus)
            )

        if has_gext:
            puz_data.extensions[ExtensionCode.Markup] = bytes(gext_bytes)

        raw_bytes = puz_data.to_bytes()

        if isinstance(target, (str, os.PathLike)):
            with open(target, "wb") as f:
                f.write(raw_bytes)
        elif hasattr(target, "write"):
            target.write(raw_bytes)

        return raw_bytes

    def to_pdf(
        self,
        filename: str,
        header: list[str] | None = None,
    ) -> None:
        """Outputs a .pdf file in NYT submission format from the Crossword object."""
        if weasyprint is None:
            raise ImportError(
                "Can't import weasyprint, run pip install blacksquare[pdf] to install."
            )

        header_html = "<br />".join(header) if header else ""
        grid_html = f"""
            <html>
            <head><meta charset="utf-8">
            <style>
            @page {{
                margin:0.25 in;
                margin-bottom: 0;
            }}

            @media print {{
            div {{
                break-inside: avoid-page !important;
            }}
            }}
            </style>
            </head>
            <body>
            <div style='font-size:14pt; break-after: avoid-page !important;'>
                {header_html}
            </div>
            <br /> <br /> <br /> <br />
            <div style='margin: auto;'>
                {self._grid_html(size_px=600)}
            </div>
            </body></html>
        """

        row_template = "<tr><td>{}</td><td>{}</td><td>{}</td></tr>"

        def clue_rows(direction):
            row_strings = [
                row_template.format(w.number, w.clue, w.value)
                for w in self.iterwords(direction)
            ]
            return "".join(row_strings)

        clue_html = f"""
            <html>
            <head>
                <meta charset="utf-8">
                <style>
                    td {{vertical-align:top;}}
                    table {{
                        text-align:left;
                        width:100%;
                        font-size:16pt;
                        border-spacing:1rem;
                    }}
                </style>
            </head>
            <body>
            <table><tbody>
            <tr><td colspan="3">ACROSS</td></tr>
            {clue_rows(ACROSS)}
            <tr><td></td></tr>
            <tr><td colspan="3">DOWN</td></tr>
            {clue_rows(DOWN)}
            </tbody></table>
            </body></html>
        """
        merger = pypdf.PdfWriter()
        for html_page in [grid_html, clue_html]:
            pdf = weasyprint.HTML(string=html_page, encoding="UTF-8").write_pdf()
            merger.append(pypdf.PdfReader(io.BytesIO(pdf)))
        merger.write(str(filename))
        merger.close()

    def to_text_grid(self, numbers: bool = False) -> str:
        """Returns a formatted text table representation of the crossword grid."""
        return self._inner.to_text_grid(numbers)

    def _text_grid(self, numbers: bool = False) -> str:
        """Returns a formatted text table representation of the crossword grid."""
        return self.to_text_grid(numbers)

    def pprint(self, numbers: bool = False) -> None:
        """Prints a formatted string representation of the crossword fill."""
        print(self.to_text_grid(numbers))

    def _repr_mimebundle_(
        self, include: Iterable[str], exclude: Iterable[str], **kwargs: Any
    ) -> dict[str, str]:
        html = self._grid_html()
        text = self.to_text_grid()
        data = {"text/plain": text, "text/html": html}
        if include:
            data = {k: v for (k, v) in data.items() if k in include}
        if exclude:
            data = {k: v for (k, v) in data.items() if k not in exclude}
        return data

    def _grid_html(self, size_px: int | None = None) -> str:
        """Returns an HTML rendering of the puzzle."""
        size_px = size_px or self.display_size_px
        suffix = token_hex(4)
        cell_size = size_px / max(self.num_rows, self.num_cols)
        cells = []
        for c in self.itercells():
            cell_number_span = f'<span class="cell-number">{c.number or ""}</span>'
            if c != BLACK:
                if len(c.str) > 1:
                    r_font_size = max(
                        int((cell_size * 0.85) / (len(c.str) * 0.55 + 0.4)),
                        6,
                    )
                    letter_span = f'<span class="letter rebus" style="font-size:{r_font_size}px;letter-spacing:-0.5px;">{c.str}</span>'
                else:
                    letter_span = f'<span class="letter">{c.str}</span>'
            else:
                letter_span = '<span class="letter"></span>'
            circle_span = '<span class="circle"></span>'
            if c == BLACK:
                extra_class = " black"
            elif c.shaded:
                extra_class = " gray"
            else:
                extra_class = ""
            cell_div = f"""
            <div class="crossword-cell{suffix}{extra_class}">
                {cell_number_span}
                {letter_span}
                {circle_span if c.circled else ""}
            </div>
            """
            cells.append(cell_div)
        val_font_size = max(int(cell_size * 0.55), 10)
        rebus_bottom = max(int(val_font_size * 0.38), 3)
        aspect_ratio = self.num_rows / self.num_cols
        css = CSS_TEMPLATE.format(
            num_cols=self.num_cols,
            height=size_px * min(1, aspect_ratio),
            width=size_px * min(1, 1 / aspect_ratio),
            num_font_size=max(int(cell_size * 0.28), 7),
            val_font_size=val_font_size,
            rebus_bottom=rebus_bottom,
            circle_dim=cell_size - 1,
            suffix=suffix,
        )
        cells_html = "\n".join(cells)
        return f"""
        <div>
            <style scoped>
                {css}
            </style>
            <div class="crossword{suffix}">
                {cells_html}
            </div>
        </div>
        """

    def check(
        self,
        symmetry: Symmetry | None = None,
        *,
        min_word_length: int = 3,
        allow_duplicates: bool = False,
        require_connected: bool = True,
        require_filled: bool = False,
        raise_on_error: bool = False,
    ) -> ValidationResult:
        """Validates the crossword puzzle against standard crossword rules.

        Checks:
        a) All word segments are at least `min_word_length` letters (no 1- or 2-letter fragments).
        b) Symmetry is satisfied (using `self.symmetry` or the provided `symmetry`).
        c) No words are reused across the puzzle (unless `allow_duplicates=True`).
        d) Full grid connectivity (all open squares form a single connected component).
        e) No empty cells if `require_filled=True`.
        """
        rust_sym = self._to_rust_sym(symmetry)
        is_valid, errors, warnings = self._inner.check(
            rust_sym,
            min_word_length,
            allow_duplicates,
            require_connected,
            require_filled,
        )

        result = ValidationResult(is_valid=is_valid, errors=errors, warnings=warnings)
        if raise_on_error and not result.is_valid:
            raise ValueError(str(result))
        return result

    def is_valid(
        self,
        symmetry: Symmetry | None = None,
        *,
        min_word_length: int = 3,
        allow_duplicates: bool = False,
        require_connected: bool = True,
        require_filled: bool = False,
    ) -> bool:
        """Returns True if the crossword passes all validation rules, False otherwise."""
        return self.check(
            symmetry=symmetry,
            min_word_length=min_word_length,
            allow_duplicates=allow_duplicates,
            require_connected=require_connected,
            require_filled=require_filled,
        ).is_valid

    def stats(self) -> CrosswordStats:
        """Computes and returns crossword grid statistics."""
        data = self._inner.stats()
        return CrosswordStats(
            total_words=data["total_words"],
            across_words=data["across_words"],
            down_words=data["down_words"],
            black_squares=data["black_squares"],
            total_cells=data["total_cells"],
            open_cells=data["open_cells"],
            word_length_counts=data["word_length_counts"],
            letter_counts=data["letter_counts"],
            rebus_count=data["rebus_count"],
            circled_count=data["circled_count"],
            shaded_count=data["shaded_count"],
            filled_words=data["filled_words"],
            open_words=data["open_words"],
        )

clues property

clues: dict[WordIndex, str]

A dict mapping word index to clue.

num_cols property

num_cols: int

The number of columns in the puzzle

num_rows property

num_rows: int

The number of rows in the puzzle

check

check(
    symmetry: Symmetry | None = None,
    *,
    min_word_length: int = 3,
    allow_duplicates: bool = False,
    require_connected: bool = True,
    require_filled: bool = False,
    raise_on_error: bool = False,
) -> ValidationResult

Validates the crossword puzzle against standard crossword rules.

Checks: a) All word segments are at least min_word_length letters (no 1- or 2-letter fragments). b) Symmetry is satisfied (using self.symmetry or the provided symmetry). c) No words are reused across the puzzle (unless allow_duplicates=True). d) Full grid connectivity (all open squares form a single connected component). e) No empty cells if require_filled=True.

Source code in src/blacksquare/crossword.py
def check(
    self,
    symmetry: Symmetry | None = None,
    *,
    min_word_length: int = 3,
    allow_duplicates: bool = False,
    require_connected: bool = True,
    require_filled: bool = False,
    raise_on_error: bool = False,
) -> ValidationResult:
    """Validates the crossword puzzle against standard crossword rules.

    Checks:
    a) All word segments are at least `min_word_length` letters (no 1- or 2-letter fragments).
    b) Symmetry is satisfied (using `self.symmetry` or the provided `symmetry`).
    c) No words are reused across the puzzle (unless `allow_duplicates=True`).
    d) Full grid connectivity (all open squares form a single connected component).
    e) No empty cells if `require_filled=True`.
    """
    rust_sym = self._to_rust_sym(symmetry)
    is_valid, errors, warnings = self._inner.check(
        rust_sym,
        min_word_length,
        allow_duplicates,
        require_connected,
        require_filled,
    )

    result = ValidationResult(is_valid=is_valid, errors=errors, warnings=warnings)
    if raise_on_error and not result.is_valid:
        raise ValueError(str(result))
    return result

copy

copy() -> Crossword

Returns a copy of the current crossword.

Returns:

Type Description
Crossword

A copy of the current Crossword object.

Source code in src/blacksquare/crossword.py
def copy(self) -> Crossword:
    """Returns a copy of the current crossword.

    Returns:
        A copy of the current Crossword object.
    """
    return Crossword(
        _inner=self._inner.copy(),
        word_list=self.word_list,
        display_size_px=self.display_size_px,
    )

fill

fill(
    word_list: WordList | None = None,
    timeout: float | None = 30.0,
    temperature: float = 0.0,
    score_filter: float | None = None,
    allow_repeats: bool = False,
    upweight_diverse_letters: bool = False,
    show_progress: bool = True,
    progress_callback: Any | None = None,
) -> Crossword | None

Searches for a possible fill, and returns the result as a new Crossword object. Backed by the native Rust backtracking solver.

Parameters:

Name Type Description Default
word_list WordList | None

An optional word list to use instead of the default.

None
timeout float | None

The maximum time in seconds to search before returning.

30.0
temperature float

A parameter to control randomness.

0.0
score_filter float | None

A threshold to apply to the word list before filling.

None
allow_repeats bool

Whether to allow duplicate words in the grid.

False
upweight_diverse_letters bool

Whether to upweight rare/diverse letters (J, Z, Q, X, etc.) during crossing candidate evaluation. Defaults to False.

False
show_progress bool

Whether to display live in-progress grid updates for long-running searches (>100ms). Automatically adapts to Jupyter/Colab notebooks and terminal registers. Defaults to True.

True
progress_callback Any | None

An optional custom callback invoked on progress updates with signature (grid_str, elapsed_secs, states_visited, is_final, is_solved).

None

Returns:

Type Description
Crossword | None

The filled Crossword, or None if no solution found / timed out.

Source code in src/blacksquare/crossword.py
def fill(
    self,
    word_list: WordList | None = None,
    timeout: float | None = 30.0,
    temperature: float = 0.0,
    score_filter: float | None = None,
    allow_repeats: bool = False,
    upweight_diverse_letters: bool = False,
    show_progress: bool = True,
    progress_callback: Any | None = None,
) -> Crossword | None:
    """Searches for a possible fill, and returns the result as a new Crossword
    object. Backed by the native Rust backtracking solver.

    Args:
        word_list: An optional word list to use instead of the default.
        timeout: The maximum time in seconds to search before returning.
        temperature: A parameter to control randomness.
        score_filter: A threshold to apply to the word list before filling.
        allow_repeats: Whether to allow duplicate words in the grid.
        upweight_diverse_letters: Whether to upweight rare/diverse letters
            (J, Z, Q, X, etc.) during crossing candidate evaluation.
            Defaults to False.
        show_progress: Whether to display live in-progress grid updates
            for long-running searches (>100ms). Automatically adapts to
            Jupyter/Colab notebooks and terminal registers. Defaults to True.
        progress_callback: An optional custom callback invoked on progress updates with
            signature `(grid_str, elapsed_secs, states_visited, is_final, is_solved)`.

    Returns:
        The filled Crossword, or None if no solution found / timed out.
    """
    wl = word_list if word_list is not None else self.word_list

    cb = progress_callback
    if cb is None and show_progress:
        if _is_notebook():
            handle = None

            def _nb_progress(
                grid_str: str,
                elapsed: float,
                states: int,
                is_final: bool,
                is_solved: bool,
            ) -> None:
                nonlocal handle
                try:
                    ipy_disp = importlib.import_module("IPython.display")
                    display = getattr(ipy_disp, "display", None)
                    html_cls = getattr(ipy_disp, "HTML", None)
                    pretty = getattr(ipy_disp, "Pretty", None)
                    if display is None:
                        return

                    if is_final:
                        if handle is not None:
                            empty = html_cls("") if html_cls is not None else ""
                            handle.update(empty)
                            handle = None
                        return

                    status = f"Fill in Progress [Elapsed: {elapsed:.2f}s | States: {states}]"
                    text = f"=== Crossword {status} ===\n{grid_str}"
                    content = pretty(text) if pretty is not None else text

                    if handle is None:
                        handle = display(content, display_id=True)
                    else:
                        handle.update(content)
                except Exception:
                    pass

            cb = _nb_progress
        else:
            displayed_lines = [0]

            def _term_progress(
                grid_str: str,
                elapsed: float,
                states: int,
                is_final: bool,
                is_solved: bool,
            ) -> None:
                if is_final:
                    if displayed_lines[0] > 0:
                        sys.stderr.write(
                            f"\x1b[{displayed_lines[0]}A\r\x1b[0J\x1b[?25h"
                        )
                        sys.stderr.flush()
                        displayed_lines[0] = 0
                    return

                status = (
                    f"Fill in Progress [Elapsed: {elapsed:.2f}s | States: {states}]"
                )
                header = f"=== Crossword {status} ==="
                lines = [header] + grid_str.splitlines()
                new_count = len(lines)

                buf = []
                if displayed_lines[0] == 0:
                    buf.append("\x1b[?25l")
                else:
                    buf.append(f"\x1b[{displayed_lines[0]}A\r")

                for line in lines:
                    buf.append(f"\x1b[K{line}\n")

                if displayed_lines[0] > new_count:
                    for _ in range(displayed_lines[0] - new_count):
                        buf.append("\x1b[K\n")
                    buf.append(f"\x1b[{displayed_lines[0] - new_count}A\r")

                displayed_lines[0] = new_count
                sys.stderr.write("".join(buf))
                sys.stderr.flush()

            cb = _term_progress

    filled_inner = self._inner.fill(
        wl._inner,
        timeout=timeout,
        temperature=temperature,
        score_filter=score_filter,
        allow_repeats=allow_repeats,
        upweight_diverse_letters=upweight_diverse_letters,
        progress_callback=cb,
    )
    if filled_inner is not None:
        return Crossword(
            _inner=filled_inner,
            word_list=wl,
            display_size_px=self.display_size_px,
        )
    return None

from_puz classmethod

from_puz(
    source: str | PathLike[str] | bytes | BinaryIO,
    word_list: WordList | None = None,
) -> Crossword

Creates a Crossword object from a .puz file path, bytes, or file-like object.

Restores the full grid, words, clues, rebus cells (from GRBS/RTBL extensions), and circled cells (from GEXT extension).

Source code in src/blacksquare/crossword.py
@classmethod
def from_puz(
    cls,
    source: str | os.PathLike[str] | bytes | BinaryIO,
    word_list: WordList | None = None,
) -> Crossword:
    """Creates a Crossword object from a .puz file path, bytes, or file-like object.

    Restores the full grid, words, clues, rebus cells (from GRBS/RTBL extensions),
    and circled cells (from GEXT extension).
    """
    if isinstance(source, (str, os.PathLike)):
        with open(source, "rb") as f:
            data = f.read()
    elif isinstance(source, bytes):
        data = source
    elif hasattr(source, "read"):
        data = source.read()
    else:
        raise TypeError(f"Unsupported source type for from_puz: {type(source)}")

    puz_data = PuzData.from_bytes(data)
    xw = cls(
        num_rows=puz_data.height,
        num_cols=puz_data.width,
        symmetry=None,
        word_list=word_list,
    )

    # Rebus reconstruction
    rebus_dict: dict[int, str] = {}
    if ExtensionCode.RebusSolutions in puz_data.extensions:
        rtbl_str = puz_data.extensions[ExtensionCode.RebusSolutions].decode(
            puz_data.encoding, "replace"
        )
        rebus_dict = parse_rebus_table(rtbl_str)

    grbs_data = puz_data.extensions.get(ExtensionCode.Rebus, b"")
    gext_data = puz_data.extensions.get(ExtensionCode.Markup, b"")

    for r in range(puz_data.height):
        for c in range(puz_data.width):
            idx = r * puz_data.width + c
            ch = puz_data.solution[idx]
            if ch in [BLACKSQUARE, BLACKSQUARE2, "#"]:
                xw[r, c] = SpecialCellValue.BLACK
            elif grbs_data and idx < len(grbs_data) and grbs_data[idx] > 0:
                k = grbs_data[idx] - 1
                rebus_val = rebus_dict.get(k, ch)
                xw[r, c] = Rebus(rebus_val)
            elif ch in [BLANKSQUARE, " ", "?", "_"]:
                xw[r, c] = SpecialCellValue.EMPTY
            else:
                xw[r, c] = ch

            if gext_data and idx < len(gext_data):
                if gext_data[idx] & GridMarkup.Circled:
                    xw[r, c].circled = True

    sorted_words = sorted(
        list(xw.iterwords()), key=lambda w: (w.number, w.direction)
    )
    for w, clue_text in zip(sorted_words, puz_data.clues):
        w.clue = clue_text

    return xw

get_cell_number

get_cell_number(cell_index: CellIndex) -> int | None

Gets the crossword numeral at a given cell, if it exists.

Parameters:

Name Type Description Default
cell_index CellIndex

The index of the cell.

required

Returns:

Type Description
int | None

The crossword number in that cell, if any.

Source code in src/blacksquare/crossword.py
def get_cell_number(self, cell_index: CellIndex) -> int | None:
    """Gets the crossword numeral at a given cell, if it exists.

    Args:
        cell_index: The index of the cell.

    Returns:
        The crossword number in that cell, if any.
    """
    r, c = int(cell_index[0]), int(cell_index[1])
    if r < 0:
        r += self.num_rows
    if c < 0:
        c += self.num_cols
    return self._inner.get_cell_number(r, c)

get_disconnected_open_subgrids

get_disconnected_open_subgrids() -> list[list[WordIndex]]

Returns a list of open subgrids, as represented by a list of words.

Returns:

Type Description
list[list[WordIndex]]

A list of open subgrids.

Source code in src/blacksquare/crossword.py
def get_disconnected_open_subgrids(self) -> list[list[WordIndex]]:
    """Returns a list of open subgrids, as represented by a list of words.

    Returns:
        A list of open subgrids.
    """
    raw_subs = self._inner.get_disconnected_open_subgrids()
    return [[(self._from_rust_dir(d), num) for d, num in sub] for sub in raw_subs]

get_indices

get_indices(word_index: WordIndex) -> list[CellIndex]

Gets the list of cell indices for a given word.

Parameters:

Name Type Description Default
word_index WordIndex

The index of the desired word.

required

Returns:

Type Description
list[CellIndex]

A list of cell indices that belong to the word.

Source code in src/blacksquare/crossword.py
def get_indices(self, word_index: WordIndex) -> list[CellIndex]:
    """Gets the list of cell indices for a given word.

    Args:
        word_index: The index of the desired word.

    Returns:
        A list of cell indices that belong to the word.
    """
    r_dir = self._to_rust_dir(word_index[0])
    num = int(word_index[1])
    coords = self._inner.get_word_cell_indices(r_dir, num)
    if coords is not None:
        return coords
    raise IndexError(f"Word {word_index} not found")

get_symmetric_cell_index

get_symmetric_cell_index(
    index: CellIndex, force_list: bool = False
) -> CellIndex | list[CellIndex] | None

Gets the index of a symmetric grid cell. Useful for enforcing symmetry.

Parameters:

Name Type Description Default
index CellIndex

The input cell index.

required
force_list bool

Whether to require that single indices are returned as a list.

False

Returns:

Type Description
CellIndex | list[CellIndex] | None

The index (or indices) of the cell symmetric to the input.

Source code in src/blacksquare/crossword.py
def get_symmetric_cell_index(
    self, index: CellIndex, force_list: bool = False
) -> CellIndex | list[CellIndex] | None:
    """Gets the index of a symmetric grid cell. Useful for enforcing symmetry.

    Args:
        index: The input cell index.
        force_list: Whether to require that single indices are returned as a list.

    Returns:
        The index (or indices) of the cell symmetric to the input.
    """
    if not self.symmetry:
        return [] if force_list else None
    r, c = int(index[0]), int(index[1])
    if r < 0:
        r += self.num_rows
    if c < 0:
        c += self.num_cols
    images = self._inner.get_symmetric_cell_indices(r, c)
    if not images:
        return [] if force_list else None
    if self.symmetry.is_multi_image or force_list:
        return images
    else:
        return images[0]

get_symmetric_word_index

get_symmetric_word_index(
    word_index: WordIndex, force_list: bool = False
) -> WordIndex | list[WordIndex] | None

Gets the index of a symmetric word. Useful for enforcing symmetry.

Parameters:

Name Type Description Default
word_index WordIndex

The input word index.

required
force_list bool

Whether to require that single indices are returned as a list.

False

Returns:

Type Description
WordIndex | list[WordIndex] | None

The index (or indices) of the word symmetric to the input.

Source code in src/blacksquare/crossword.py
def get_symmetric_word_index(
    self, word_index: WordIndex, force_list: bool = False
) -> WordIndex | list[WordIndex] | None:
    """Gets the index of a symmetric word. Useful for enforcing symmetry.

    Args:
        word_index: The input word index.
        force_list: Whether to require that single indices are returned as a list.

    Returns:
        The index (or indices) of the word symmetric to the input.
    """
    if not self.symmetry:
        return [] if force_list else None
    r_dir = self._to_rust_dir(word_index[0])
    images = self._inner.get_symmetric_word_indices(r_dir, int(word_index[1]))
    py_images = [(self._from_rust_dir(d), num) for d, num in images]
    if not py_images:
        return [] if force_list else None
    if self.symmetry.is_multi_image or force_list:
        return py_images
    else:
        return py_images[0]

get_word_at_index

get_word_at_index(
    index: CellIndex, direction: Direction
) -> Word | None

Gets the word that passes through a cell in a given direction.

Parameters:

Name Type Description Default
index CellIndex

The index of the cell.

required
direction Direction

The direction of the word.

required

Returns:

Type Description
Word | None

The word passing through the index in the provided direction.

Source code in src/blacksquare/crossword.py
def get_word_at_index(self, index: CellIndex, direction: Direction) -> Word | None:
    """Gets the word that passes through a cell in a given direction.

    Args:
        index: The index of the cell.
        direction: The direction of the word.

    Returns:
        The word passing through the index in the provided direction.
    """
    r, c = int(index[0]), int(index[1])
    if r < 0:
        r += self.num_rows
    if c < 0:
        c += self.num_cols
    r_dir = self._to_rust_dir(direction)
    res = self._inner.get_word_at_cell(r, c, r_dir)
    if res is not None:
        py_dir = self._from_rust_dir(res[0])
        return self[py_dir, res[1]]
    return None

get_word_cells

get_word_cells(word_index: WordIndex) -> list[Cell]

Gets the cells for a word index.

Parameters:

Name Type Description Default
word_index WordIndex

The word index.

required

Returns:

Type Description
list[Cell]

The list of Cells in the word.

Source code in src/blacksquare/crossword.py
def get_word_cells(self, word_index: WordIndex) -> list[Cell]:
    """Gets the cells for a word index.

    Args:
        word_index: The word index.

    Returns:
        The list of Cells in the word.
    """
    r_dir = self._to_rust_dir(word_index[0])
    num = int(word_index[1])
    coords = self._inner.get_word_cell_indices(r_dir, num)
    if coords is not None:
        return [self[r, c] for r, c in coords]
    return []

hashable_state

hashable_state(
    word_indices: list[WordIndex],
) -> tuple[tuple[WordIndex, str], ...]

Returns a list of tuple of (word index, current value) pairs in sorted order.

Parameters:

Name Type Description Default
word_indices list[WordIndex]

The list of word indices of interest.

required

Returns:

Type Description
tuple[tuple[WordIndex, str], ...]

A tuple of (word index, value) tuples

Source code in src/blacksquare/crossword.py
def hashable_state(
    self, word_indices: list[WordIndex]
) -> tuple[tuple[WordIndex, str], ...]:
    """Returns a list of tuple of (word index, current value) pairs in sorted order.

    Args:
        word_indices: The list of word indices of interest.

    Returns:
        A tuple of (word index, value) tuples
    """
    sorted_indices = sorted(word_indices)
    return tuple((i, self[i].value) for i in sorted_indices)

is_valid

is_valid(
    symmetry: Symmetry | None = None,
    *,
    min_word_length: int = 3,
    allow_duplicates: bool = False,
    require_connected: bool = True,
    require_filled: bool = False,
) -> bool

Returns True if the crossword passes all validation rules, False otherwise.

Source code in src/blacksquare/crossword.py
def is_valid(
    self,
    symmetry: Symmetry | None = None,
    *,
    min_word_length: int = 3,
    allow_duplicates: bool = False,
    require_connected: bool = True,
    require_filled: bool = False,
) -> bool:
    """Returns True if the crossword passes all validation rules, False otherwise."""
    return self.check(
        symmetry=symmetry,
        min_word_length=min_word_length,
        allow_duplicates=allow_duplicates,
        require_connected=require_connected,
        require_filled=require_filled,
    ).is_valid

itercells

itercells() -> Iterator[Cell]

Method for iterating over the cells in the crossword.

Yields:

Type Description
Cell

An iterator of Cell objects. Ordered left to right, top to bottom.

Source code in src/blacksquare/crossword.py
def itercells(self) -> Iterator[Cell]:
    """Method for iterating over the cells in the crossword.

    Yields:
        An iterator of Cell objects. Ordered left to right, top to bottom.
    """
    for r in range(self.num_rows):
        for c in range(self.num_cols):
            yield self[r, c]

iterwords

iterwords(
    direction: Direction | None = None,
    only_open: bool = False,
) -> Iterator[Word]

Method for iterating over the words in the crossword.

Parameters:

Name Type Description Default
direction Direction | None

If provided, limits the iterator to only the given direction.

None
only_open bool

Whether to only return open words. Defaults to False.

False

Yields:

Type Description
Word

An iterator of Word objects.

Source code in src/blacksquare/crossword.py
def iterwords(
    self, direction: Direction | None = None, only_open: bool = False
) -> Iterator[Word]:
    """Method for iterating over the words in the crossword.

    Args:
        direction: If provided, limits the iterator to only the given direction.
        only_open: Whether to only return open words. Defaults to False.

    Yields:
        An iterator of Word objects.
    """
    r_dir = self._to_rust_dir(direction) if direction is not None else None
    for r_d, num in self._inner.iter_word_indices(r_dir, only_open):
        py_dir = self._from_rust_dir(r_d)
        yield self[py_dir, num]

pprint

pprint(numbers: bool = False) -> None

Prints a formatted string representation of the crossword fill.

Source code in src/blacksquare/crossword.py
def pprint(self, numbers: bool = False) -> None:
    """Prints a formatted string representation of the crossword fill."""
    print(self.to_text_grid(numbers))

set_cell

set_cell(index: CellIndex, value: CellValue) -> None

Sets a cell to a new value.

Parameters:

Name Type Description Default
index CellIndex

The index of the cell.

required
value CellValue

The new value of the cell.

required
Source code in src/blacksquare/crossword.py
def set_cell(self, index: CellIndex, value: CellValue) -> None:
    """Sets a cell to a new value.

    Args:
        index: The index of the cell.
        value: The new value of the cell.
    """
    if isinstance(value, (list, tuple, int, float, Crossword, Word)):
        raise ValueError(f"Invalid cell value type: {type(value)}")

    r, c = int(index[0]), int(index[1])
    if r < 0:
        r += self.num_rows
    if c < 0:
        c += self.num_cols
    if not (0 <= r < self.num_rows and 0 <= c < self.num_cols):
        raise IndexError(f"Cell index {(r, c)} out of bounds")

    if isinstance(value, Rebus):
        self._inner.set_cell_rebus(r, c, value.across, value.down)
    elif isinstance(value, SpecialCellValue):
        self._inner.set_cell_value(r, c, value.str)
    elif isinstance(value, Cell):
        if isinstance(value.value, Rebus):
            self._inner.set_cell_rebus(r, c, value.value.across, value.value.down)
        else:
            self._inner.set_cell_value(r, c, value.str)
    elif isinstance(value, str):
        if value in SpecialCellValue.BLACK.input_str_reprs:
            self._inner.set_cell_value(r, c, SpecialCellValue.BLACK.str)
        elif value in SpecialCellValue.EMPTY.input_str_reprs:
            self._inner.set_cell_value(r, c, SpecialCellValue.EMPTY.str)
        elif len(value) == 1:
            self._inner.set_cell_value(r, c, value.upper())
        else:
            clean = value.strip()
            if clean in SpecialCellValue.BLACK.input_str_reprs:
                self._inner.set_cell_value(r, c, SpecialCellValue.BLACK.str)
            elif clean in SpecialCellValue.EMPTY.input_str_reprs:
                self._inner.set_cell_value(r, c, SpecialCellValue.EMPTY.str)
            elif len(clean) == 1:
                self._inner.set_cell_value(r, c, clean.upper())
            else:
                raise ValueError(f"Invalid cell value length: {value!r}")
    else:
        raise ValueError(f"Invalid cell value type: {type(value)}")

set_word

set_word(word_index: WordIndex, value: str) -> None

Sets a word to a new value.

Parameters:

Name Type Description Default
word_index WordIndex

The index of the word.

required
value str

The new value of the word.

required
Source code in src/blacksquare/crossword.py
def set_word(self, word_index: WordIndex, value: str) -> None:
    """Sets a word to a new value.

    Args:
        word_index: The index of the word.
        value: The new value of the word.
    """
    if not isinstance(value, str):
        raise ValueError(f"Word value must be str, got {type(value)}")

    direction, num = word_index[0], int(word_index[1])
    r_dir = self._to_rust_dir(direction)
    cell_indices = self._inner.get_word_cell_indices(r_dir, num)
    if cell_indices is None:
        raise IndexError(f"Word {word_index} not found in grid")

    word_cells = [self[r, c] for r, c in cell_indices]
    new_values = _parse_word_string_to_cell_values(word_cells, direction, value)
    for (r, c), new_val in zip(cell_indices, new_values):
        self.set_cell((r, c), new_val)

stats

stats() -> CrosswordStats

Computes and returns crossword grid statistics.

Source code in src/blacksquare/crossword.py
def stats(self) -> CrosswordStats:
    """Computes and returns crossword grid statistics."""
    data = self._inner.stats()
    return CrosswordStats(
        total_words=data["total_words"],
        across_words=data["across_words"],
        down_words=data["down_words"],
        black_squares=data["black_squares"],
        total_cells=data["total_cells"],
        open_cells=data["open_cells"],
        word_length_counts=data["word_length_counts"],
        letter_counts=data["letter_counts"],
        rebus_count=data["rebus_count"],
        circled_count=data["circled_count"],
        shaded_count=data["shaded_count"],
        filled_words=data["filled_words"],
        open_words=data["open_words"],
    )

to_pdf

to_pdf(
    filename: str, header: list[str] | None = None
) -> None

Outputs a .pdf file in NYT submission format from the Crossword object.

Source code in src/blacksquare/crossword.py
def to_pdf(
    self,
    filename: str,
    header: list[str] | None = None,
) -> None:
    """Outputs a .pdf file in NYT submission format from the Crossword object."""
    if weasyprint is None:
        raise ImportError(
            "Can't import weasyprint, run pip install blacksquare[pdf] to install."
        )

    header_html = "<br />".join(header) if header else ""
    grid_html = f"""
        <html>
        <head><meta charset="utf-8">
        <style>
        @page {{
            margin:0.25 in;
            margin-bottom: 0;
        }}

        @media print {{
        div {{
            break-inside: avoid-page !important;
        }}
        }}
        </style>
        </head>
        <body>
        <div style='font-size:14pt; break-after: avoid-page !important;'>
            {header_html}
        </div>
        <br /> <br /> <br /> <br />
        <div style='margin: auto;'>
            {self._grid_html(size_px=600)}
        </div>
        </body></html>
    """

    row_template = "<tr><td>{}</td><td>{}</td><td>{}</td></tr>"

    def clue_rows(direction):
        row_strings = [
            row_template.format(w.number, w.clue, w.value)
            for w in self.iterwords(direction)
        ]
        return "".join(row_strings)

    clue_html = f"""
        <html>
        <head>
            <meta charset="utf-8">
            <style>
                td {{vertical-align:top;}}
                table {{
                    text-align:left;
                    width:100%;
                    font-size:16pt;
                    border-spacing:1rem;
                }}
            </style>
        </head>
        <body>
        <table><tbody>
        <tr><td colspan="3">ACROSS</td></tr>
        {clue_rows(ACROSS)}
        <tr><td></td></tr>
        <tr><td colspan="3">DOWN</td></tr>
        {clue_rows(DOWN)}
        </tbody></table>
        </body></html>
    """
    merger = pypdf.PdfWriter()
    for html_page in [grid_html, clue_html]:
        pdf = weasyprint.HTML(string=html_page, encoding="UTF-8").write_pdf()
        merger.append(pypdf.PdfReader(io.BytesIO(pdf)))
    merger.write(str(filename))
    merger.close()

to_puz

to_puz(
    target: str | PathLike[str] | BinaryIO | None = None,
    *,
    title: str = "",
    author: str = "",
    copyright: str = "",
    notes: str = "",
) -> bytes

Exports the Crossword object to Across Lite .puz binary format.

Saves full grid solutions, clues, rebus cells (via GRBS and RTBL extensions), and circled cells (via GEXT extension). If target is provided, writes to the file or stream; otherwise returns the raw bytes.

Source code in src/blacksquare/crossword.py
def to_puz(
    self,
    target: str | os.PathLike[str] | BinaryIO | None = None,
    *,
    title: str = "",
    author: str = "",
    copyright: str = "",
    notes: str = "",
) -> bytes:
    """Exports the Crossword object to Across Lite .puz binary format.

    Saves full grid solutions, clues, rebus cells (via GRBS and RTBL extensions),
    and circled cells (via GEXT extension). If target is provided, writes to the
    file or stream; otherwise returns the raw bytes.
    """
    puz_data = PuzData(version="1.3")
    puz_data.width = self.num_cols
    puz_data.height = self.num_rows
    puz_data.title = title
    puz_data.author = author
    puz_data.copyright = copyright
    puz_data.notes = notes

    n_cells = self.num_rows * self.num_cols
    sol_chars: list[str] = []
    fill_chars: list[str] = []

    rebus_map: dict[str, int] = {}
    grbs_bytes = bytearray(n_cells)
    gext_bytes = bytearray(n_cells)
    has_rebus = False
    has_gext = False

    for r in range(self.num_rows):
        for c in range(self.num_cols):
            idx = r * self.num_cols + c
            cell = self[r, c]
            if cell == SpecialCellValue.BLACK:
                sol_chars.append(BLACKSQUARE)
                fill_chars.append(BLACKSQUARE)
            else:
                fill_chars.append(BLANKSQUARE)
                if isinstance(cell.value, Rebus):
                    has_rebus = True
                    rebus_str = str(cell.value)
                    if rebus_str not in rebus_map:
                        rebus_map[rebus_str] = len(rebus_map)
                    k = rebus_map[rebus_str]
                    grbs_bytes[idx] = k + 1
                    sol_chars.append(cell.value.across[0])
                elif cell.is_open():
                    sol_chars.append(BLANKSQUARE)
                else:
                    sol_chars.append(cell.str[0] if cell.str else BLANKSQUARE)

            if cell.circled:
                has_gext = True
                gext_bytes[idx] |= GridMarkup.Circled

    puz_data.solution = "".join(sol_chars)
    puz_data.fill = "".join(fill_chars)

    sorted_words = sorted(
        list(self.iterwords()), key=lambda w: (w.number, w.direction)
    )
    puz_data.clues = [w.clue or "" for w in sorted_words]

    if has_rebus:
        puz_data.extensions[ExtensionCode.Rebus] = bytes(grbs_bytes)
        inv_rebus = {k: v for v, k in rebus_map.items()}
        puz_data.extensions[ExtensionCode.RebusSolutions] = puz_data.encode(
            serialize_rebus_table(inv_rebus)
        )

    if has_gext:
        puz_data.extensions[ExtensionCode.Markup] = bytes(gext_bytes)

    raw_bytes = puz_data.to_bytes()

    if isinstance(target, (str, os.PathLike)):
        with open(target, "wb") as f:
            f.write(raw_bytes)
    elif hasattr(target, "write"):
        target.write(raw_bytes)

    return raw_bytes

to_text_grid

to_text_grid(numbers: bool = False) -> str

Returns a formatted text table representation of the crossword grid.

Source code in src/blacksquare/crossword.py
def to_text_grid(self, numbers: bool = False) -> str:
    """Returns a formatted text table representation of the crossword grid."""
    return self._inner.to_text_grid(numbers)