feat: add BoardFactory for word search grid generation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Mathew Sir Guest the best
2026-05-06 22:39:43 -06:00
co-authored by Claude Opus 4.6
parent 1c4154b84b
commit e483d1127a
3 changed files with 204 additions and 0 deletions
+89
View File
@@ -0,0 +1,89 @@
import random
from models.category import Category, CategoryWord
from game.factory import BoardFactory
DIRECTIONS = {
"E": (0, 1),
"W": (0, -1),
"S": (1, 0),
"N": (-1, 0),
"SE": (1, 1),
"SW": (1, -1),
"NE": (-1, 1),
"NW": (-1, -1),
}
def _seed_category(db_session, name, words):
cat = Category(name=name)
db_session.add(cat)
db_session.flush()
for w in words:
db_session.add(CategoryWord(category_id=cat.id, word=w))
db_session.commit()
return cat
def test_factory_creates_game_and_words(db_session):
cat = _seed_category(
db_session,
"animals",
["TIGER", "LION", "BEAR", "WOLF", "EAGLE", "HAWK", "DEER", "FROG"],
)
factory = BoardFactory(db_session)
game, words = factory.create(category_id=cat.id, board_size=10, word_count=5)
assert game.board_size == 10
assert game.category_id == cat.id
assert len(game.grid) == 10
assert all(len(row) == 10 for row in game.grid)
assert len(words) <= 5
assert len(words) >= 1
def test_factory_words_are_on_grid(db_session):
cat = _seed_category(
db_session,
"test",
["CAT", "DOG", "BAT", "RAT", "OWL", "COW", "PIG", "HEN"],
)
random.seed(42)
factory = BoardFactory(db_session)
game, words = factory.create(category_id=cat.id, board_size=10, word_count=5)
for word in words:
dr, dc = DIRECTIONS[word.direction]
extracted = ""
r, c = word.start_row, word.start_col
for _ in range(len(word.text)):
extracted += game.grid[r][c]
r += dr
c += dc
assert extracted == word.text
def test_factory_fills_all_cells(db_session):
cat = _seed_category(db_session, "small", ["AB", "CD"])
factory = BoardFactory(db_session)
game, _ = factory.create(category_id=cat.id, board_size=8, word_count=2)
for row in game.grid:
for cell in row:
assert cell.isalpha() and cell.isupper() and len(cell) == 1
def test_factory_filters_words_too_long(db_session):
cat = _seed_category(
db_session,
"mixed",
["HIPPOPOTAMUS", "CAT", "DOG"], # HIPPOPOTAMUS won't fit in 8x8
)
factory = BoardFactory(db_session)
game, words = factory.create(category_id=cat.id, board_size=8, word_count=3)
placed_texts = [w.text for w in words]
assert "HIPPOPOTAMUS" not in placed_texts
def test_factory_clamps_word_count(db_session):
cat = _seed_category(db_session, "tiny", ["CAT", "DOG"])
factory = BoardFactory(db_session)
game, words = factory.create(category_id=cat.id, board_size=10, word_count=10)
assert len(words) <= 2