File size: 6,701 Bytes
6829252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Quick test script for Wrdler puzzle generator.
Tests the new horizontal-only, 6x8 grid generator.
"""

import sys
import os

# Force UTF-8 encoding on Windows
if sys.platform == "win32":
    import codecs
    sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
    sys.stderr = codecs.getwriter("utf-8")(sys.stderr.detach())

from wrdler.generator import generate_puzzle, validate_puzzle
from wrdler.word_loader import load_word_list

def test_basic_generation():
    """Test basic puzzle generation with default parameters."""
    print("Test 1: Basic puzzle generation (6 rows Γ— 8 columns)")
    print("=" * 60)

    try:
        puzzle = generate_puzzle()
        print(f"βœ“ Puzzle generated successfully!")
        print(f"  Grid: {puzzle.grid_rows} rows Γ— {puzzle.grid_cols} columns")
        print(f"  Words: {len(puzzle.words)}")
        print()

        # Print words
        print("Words in puzzle:")
        for i, word in enumerate(sorted(puzzle.words, key=lambda w: w.start.x), 1):
            print(f"  {i}. '{word.text}' ({len(word.text)} letters) - Row {word.start.x}, Cols {word.start.y}-{word.start.y + len(word.text) - 1}, Direction: {word.direction}")
        print()

        # Validate
        validate_puzzle(puzzle, grid_rows=puzzle.grid_rows, grid_cols=puzzle.grid_cols)
        print("βœ“ Puzzle validation passed!")
        print()

        return True
    except Exception as e:
        print(f"βœ— Test failed: {e}")
        import traceback
        traceback.print_exc()
        return False


def test_with_seed():
    """Test deterministic generation with seed."""
    print("Test 2: Deterministic generation with seed")
    print("=" * 60)

    try:
        puzzle1 = generate_puzzle(seed=12345)
        puzzle2 = generate_puzzle(seed=12345)

        # Should generate same words
        words1 = [w.text for w in puzzle1.words]
        words2 = [w.text for w in puzzle2.words]

        if words1 == words2:
            print(f"βœ“ Deterministic generation works!")
            print(f"  Both puzzles have words: {words1}")
            print()
            return True
        else:
            print(f"βœ— Deterministic generation failed!")
            print(f"  Puzzle 1: {words1}")
            print(f"  Puzzle 2: {words2}")
            print()
            return False
    except Exception as e:
        print(f"βœ— Test failed: {e}")
        import traceback
        traceback.print_exc()
        return False


def test_target_words():
    """Test generation with specific target words."""
    print("Test 3: Generation with target words")
    print("=" * 60)

    target_words = ["CAT", "DOGS", "BIRDS", "FISH", "MONKEY", "ELEPHANT"]

    try:
        puzzle = generate_puzzle(target_words=target_words)
        generated_words = sorted([w.text for w in puzzle.words])
        expected_words = sorted([w.upper() for w in target_words])

        if generated_words == expected_words:
            print(f"βœ“ Target words generation works!")
            print(f"  Generated: {generated_words}")
            print()
            return True
        else:
            print(f"βœ— Target words generation failed!")
            print(f"  Expected: {expected_words}")
            print(f"  Got: {generated_words}")
            print()
            return False
    except Exception as e:
        print(f"βœ— Test failed: {e}")
        import traceback
        traceback.print_exc()
        return False


def test_grid_visualization():
    """Visualize a generated puzzle on the grid."""
    print("Test 4: Grid visualization")
    print("=" * 60)

    try:
        puzzle = generate_puzzle(seed=42)

        # Create 6x8 grid
        grid = [[' ' for _ in range(puzzle.grid_cols)] for _ in range(puzzle.grid_rows)]

        # Fill in words
        for word in puzzle.words:
            for i, cell in enumerate(word.cells):
                grid[cell.x][cell.y] = word.text[i]

        # Print grid
        print("Grid visualization:")
        print("  " + "+-" * puzzle.grid_cols + "+")
        for row_idx, row in enumerate(grid):
            print(f"{row_idx} |" + "|".join(row) + "|")
        print("  " + "+-" * puzzle.grid_cols + "+")
        print("    " + "".join(str(i) for i in range(puzzle.grid_cols)))
        print()

        print("βœ“ Grid visualization complete!")
        print()
        return True
    except Exception as e:
        print(f"βœ— Test failed: {e}")
        import traceback
        traceback.print_exc()
        return False


def test_validation_checks():
    """Test that validation catches errors."""
    print("Test 5: Validation error detection")
    print("=" * 60)

    # This should work
    try:
        puzzle = generate_puzzle()
        validate_puzzle(puzzle, grid_rows=6, grid_cols=8)
        print("βœ“ Valid puzzle passes validation")
    except AssertionError as e:
        print(f"βœ— Valid puzzle failed validation: {e}")
        return False

    # Test row count enforcement
    try:
        from wrdler.models import Word, Coord, Puzzle

        # Try to create puzzle with wrong number of rows
        words = [
            Word("CAT", Coord(0, 0), "H"),
            Word("DOG", Coord(1, 0), "H"),
            Word("RAT", Coord(2, 0), "H"),
        ]
        bad_puzzle = Puzzle(words=words, grid_rows=6, grid_cols=8)

        try:
            validate_puzzle(bad_puzzle, grid_rows=6, grid_cols=8)
            print("βœ— Validation should have failed for 3 words (expected 6)")
            return False
        except AssertionError:
            print("βœ“ Validation correctly rejects wrong word count")
    except Exception as e:
        print(f"βœ— Test error: {e}")
        return False

    print()
    return True


def main():
    """Run all tests."""
    print("\n" + "=" * 60)
    print("WRDLER PUZZLE GENERATOR TESTS")
    print("=" * 60)
    print()

    tests = [
        test_basic_generation,
        test_with_seed,
        test_target_words,
        test_grid_visualization,
        test_validation_checks,
    ]

    results = []
    for test_func in tests:
        result = test_func()
        results.append((test_func.__name__, result))

    # Summary
    print("=" * 60)
    print("TEST SUMMARY")
    print("=" * 60)
    for name, passed in results:
        status = "βœ“ PASS" if passed else "βœ— FAIL"
        print(f"{status}: {name}")

    total = len(results)
    passed = sum(1 for _, p in results if p)
    print()
    print(f"Results: {passed}/{total} tests passed")
    print("=" * 60)

    return all(p for _, p in results)


if __name__ == "__main__":
    import sys
    success = main()
    sys.exit(0 if success else 1)