Spaces:
Running
# Battlewords: Implementation Requirements
This document breaks down the tasks to build Battlewords using the game rules described in specs.md. It is organized in phases: a minimal Proof of Concept (POC), a Beta Version (0.5.0), and a Full Version (1.0.0).
Assumptions
- Tech stack: Python 3.10+, Streamlit for UI, matplotlib for radar, numpy for tick helpers, Pillow for animated GIFs.
- Single-player, local state stored in Streamlit session state for POC.
- Grid is always 12x12 with exactly six words: two 4-letter, two 5-letter, two 6-letter words; horizontal/vertical only; no shared letters or overlaps in POC; shared-letter overlaps allowed in Beta; no overlaps in Full.
- Entry point is
app.py.
Streamlit key components (API usage plan)
- State & caching
st.session_stateforpuzzle,grid_size,revealed,guessed,score,last_action,can_guess.st.session_state.points_by_wordfor per-word score breakdown.st.session_state.letter_mapderived from puzzle.st.session_state.selected_wordlistfor sidebar picker.st.session_state.radar_gif_pathfor session-persistent radar animation.st.cache_datato load and filter the word list.
- Layout & structure
st.title,st.subheader,st.markdownfor headers/instructions.st.columns(12)to render the 12×12 grid;st.containerfor grouping;st.sidebarfor secondary controls/help.st.expanderfor inline help/intel tips.
- Widgets (interaction)
st.buttonfor each grid cell (144 total) with uniquekeyto handle reveals.st.form+st.text_input+st.form_submit_button("OK")for controlled word guessing (disabled until a reveal).st.button("New Game")to reset state; sidebarselectboxfor wordlist selection andSort Wordlistbutton (length+alpha).st.metricto show score.
- Visualization
- Animated radar using matplotlib
FuncAnimation+PillowWritersaved to GIF. - Scope overlay image generated once and reused; metallic gradient background.
- Radar plot uses inverted Y so (0,0) is top-left.
- Animated radar using matplotlib
- Control flow
- App reruns on interaction; uses
st.rerun()after state changes (reveal, guess);st.stop()after game over summary to freeze UI.
- App reruns on interaction; uses
Folder Structure
app.py– Streamlit entry pointbattlewords/– Python package__init__.pymodels.py– data models and typesword_loader.py– load/validate/cached word lists (usesbattlewords/words/wordlist.txtwith fallback)generator.py– word placement; imports fromword_loader; avoids duplicate wordslogic.py– game mechanics (reveal, guess, scoring, tiers)ui.py– Streamlit UI composition; animated radar; immediate rerender on reveal/guess viast.rerun(); inverted radar Ywords/wordlist.txt– candidate words
specs/– documentation (this file andspecs.md)tests/– unit tests
Phase 1: Proof of Concept (0.1.0) Goal: A playable, single-session game demonstrating core rules, scoring, and radar without persistence or advanced UX.
- Data Models
- Define
Coord(x:int, y:int). - Define
Word(text:str, start:Coord, direction:str{"H","V"}, cells:list[Coord]). - Define
Puzzle(words:list[Word], radar:list[Coord])– radar holds last-letter coordinates. - Define
GameState(grid_size:int=12, puzzle:Puzzle, revealed:set[Coord], guessed:set[str], score:int, last_action:str, can_guess:bool).
Acceptance: Types exist and are consumed by generator/logic; simple constructors and validators.
- Word List
- Add an English word list filtered to alphabetic uppercase, lengths in {4,5,6}.
- Ensure words contain no special characters; maintain reasonable difficulty.
- Streamlit:
st.cache_datato memoize loading/filtering. - Loader is centralized in
word_loader.pyand used by generator and UI.
Acceptance: Loading function returns lists by length with >= 25 words per length or fallback minimal lists.
- Puzzle Generation (Placement)
- Randomly place 2×4, 2×5, 2×6 letter words on a 12×12 grid.
- Constraints (POC):
- Horizontal (left→right) or Vertical (top→down) only.
- No overlapping letters between different words (cells must be unique).
- Compute radar pulses as the last cell of each word.
- Retry strategy with max attempts; raise a controlled error if generation fails.
Acceptance: Generator returns a valid Puzzle passing validation checks (no collisions, in-bounds, correct counts, no duplicates).
- Game Mechanics
- Reveal:
- Click a covered cell to reveal; if the cell is part of a word, show the letter; else mark empty (CSS class
empty). - After a reveal action, set
can_guess=True.
- Click a covered cell to reveal; if the cell is part of a word, show the letter; else mark empty (CSS class
- Guess:
- Accept a guess only if
can_guessis True and input length ∈ {4,5,6}. - Match guess case-insensitively against unguessed words in puzzle.
- If correct: add base points = word length; bonus points = count of unrevealed cells in that word at guess time; mark all cells of the word as revealed; add to
guessed. - If incorrect: no points awarded.
- After any guess, set
can_guess=Falseand require another reveal before next guess. - Exception: in default mode a correct guess allows chaining (
can_guess=True); other modes may disable chaining. - Streamlit:
with st.form("guess"):+st.text_input("Your guess")+st.form_submit_button("OK", disabled=not can_guess); after guess, callst.rerun().
- Accept a guess only if
- End of game when all 6 words are guessed or all word letters are revealed; display summary and tier, then
st.stop().
Acceptance: Unit tests cover scoring, guess gating, and reveal behavior.
- UI (Streamlit)
- Layout:
- Title and brief instructions via
st.title,st.subheader,st.markdown. - Left: 12×12 grid using
st.columns(12). - Right: Animated radar, Correct/Try Again indicator, guess form, and score panel.
- Sidebar: New Game, wordlist selectbox, Sort Wordlist action, Game Mode selector.
- Title and brief instructions via
- Visuals:
- Covered vs revealed styles; revealed empty cells use CSS class
empty. - Completed word cells styled with
bw-cell-complete; cell tooltips show coordinates.
- Covered vs revealed styles; revealed empty cells use CSS class
Acceptance: Users can play end-to-end; radar shows exactly 6 pulses; reveal and guess update via rerun; completed words are visually distinct.
- Scoring Tiers
- After game ends, compute tier:
- Good: 34–37
- Great: 38–41
- Fantastic: 42+
- Basic Tests
- Placement validity (bounds, overlap, counts, no duplicate words).
- Scoring logic and bonus calculation.
- Guess gating (reveal required except chaining after correct guess when enabled).
Current Deltas (0.1.3 → 0.1.10)
- 0.1.3
- Sidebar wordlist select; sorting persists length-then-alpha ordering; auto new-game after 5s notice.
- Score panel improvements; per-word points; final score styling.
- 0.1.4
- Animated radar GIF with metallic gradient and scope overlay; session reuse via
radar_gif_path. - Mobile layout improvements; tighter grid spacing and horizontal scroll per row.
- Animated radar GIF with metallic gradient and scope overlay; session reuse via
- 0.1.5
- Hit/Miss indicator derived from
last_action. - Completed word cells render as non-buttons with tooltips.
- Helper functions for scope image and stable letter map rebuild.
- Hit/Miss indicator derived from
- 0.1.10
- Game Mode selector (
standard,too easy); chaining allowed only instandard. - Guess feedback indicator switched to Correct/Try Again.
- Version footer shows commit/Python/Streamlit; ocean background effect.
- Word list default/persistence fixes and sort action persists after delay.
- Game Mode selector (
Known Issues / TODO
- Word list selection bug: improper list fetched/propagated in some runs.
- Verify
get_wordlist_files()returns correct filenames andselected_wordlistpersists across_new_game(). - Ensure
load_word_list(selected_wordlist)loads the chosen file and matchesgenerate_puzzle(words_by_len=...)expected shape. - Add tests for selection, sorting, and fallback behavior.
- Verify
Phase 1.5: Storage and Sharing (0.3.0) - NEW
Goal: Add persistent storage, high scores, and game sharing capabilities.
A) Storage Module
- Create
battlewords/storage.pywith:GameStorageclass for saving/loading game results and high scoresGameResultandHighScoreEntrydataclasses- JSON-based local storage in
~/.battlewords/data/
- Update
models.pyto includegame_idin Puzzle (based on word list) - Update
generator.pyto:- Generate game_id from sorted word list
- Accept optional
target_wordsparameter for replay
- Integrate storage into game flow:
- Save result on game completion
- Display high scores in sidebar Acceptance:
- Game results saved to local JSON files
- High scores correctly filtered and sorted
- Game IDs generated deterministically
B) Game Sharing
- Parse
game_idfrom query params (?game_id=ABC123) - Generate puzzle from game_id (same words, different positions)
- "Share Challenge" button creates shareable URL
- Display game_id in UI to show shared challenges Acceptance:
- URL with game_id loads same word set
- Share button generates correct URL
- Game ID visible to players
C) High Score Display
- Sidebar expander for high scores
- Filter by: All-time, Current Wordlist, Current Mode
- Top 10 entries with: Rank, Player, Score, Tier, Time
- Player name input (optional, defaults to "Anonymous") Acceptance:
- High scores display correctly
- Filters work as expected
- Player names saved with results
D) Tests
- Unit tests for storage operations
- Test game ID generation consistency
- Test save/load result flow
- Test high score filtering and ranking
Milestones and Estimates (High-level)
- Phase 1 (POC): 2–4 days
- Phase 1.5 (Storage & Sharing): 2–3 days ⏳ IN PROGRESS
- Beta (0.5.0): 3–5 days (overlaps, responsive UI, keyboard, deterministic seed)
- Phase 2 (Full): 1–2 weeks depending on features selected
Definitions of Done (per task)
- Code merged with tests and docs updated.
- No regressions in existing tests; coverage maintained or improved for core logic.
- Manual playthrough validates rules: reveal/guess gating, scoring, radar pulses, end state and tiers.
v0.2.20 Update: Game Sharing with Shortened game_id URL
Game Sharing Feature
- On game completion, save a JSON file to the storage server named by a unique
uid. - The JSON file contains: word_list, score, time, game_mode, grid_size, and puzzle options.
- Generate a shortened URL for this file; use it as the
game_idin the shareable link. - When a user loads a game with a
game_idquery string, fetch the JSON file and apply all settings for the session.
Implementation Notes
- The game_id is a shortened URL referencing the JSON file.
- The app applies all settings from the file for a true replay.
- No direct encoding of game data in the query string; only the reference is shared.
Phase 1.6: Remote Storage & Sharing (0.2.20)
Goal
- Persist per-game settings and highscores on a storage server (Hugging Face Hub repo).
- Use a shortened
game_id(sid) that resolves to settings.json for replay/sharing.
A) Storage Server Integration
- Use modules from OpenBadge
modules/storage.py:upload_files_to_repo(...)to write JSON toHF_REPO_IDgen_full_url(...)for shortener lookups/creation backed byshortener.json
- Create per-game folder
games/{uid}/and write:settings.jsonwith: word_list, score, time, game_mode, grid_size, puzzle options- (optional)
result.jsonwith additional details for analytics
- Maintain
highscores/highscores.jsonfor top scores - Env vars (.env):
HF_API_TOKEN(orHF_TOKEN),CRYPTO_PK,HF_REPO_ID,SPACE_NAME
B) Sharing Link (game_id)
- After upload of
settings.json, callgen_full_url(full_url=...)to obtain a short id (sid) - Shareable link:
https://<SPACE_NAME>/?game_id=<sid> - On app load with
game_id, callgen_full_url(short_url=sid), fetch JSON, apply settings
C) App Behavior
- When
game_idexists:- Apply
game_mode,grid_size,puzzle_optionsdirectly - Load
word_listas the target set; positions remain randomized unless later extended - Ignore
score/timefor gameplay; those are metadata only
- Apply
- Continue to support local JSON storage for users without HF credentials
D) Dependencies
- Add
huggingface_hubandpython-dotenvto requirements - Ensure
requestsremains present for HTTP fetch fallback if needed
E) Acceptance
- A completed game produces a working share link with
game_idsid - Visiting the link reconstructs the session settings from storage server JSON
- Highscores JSON updates in the repo
- Documentation updated with env vars, repo structure, and flows
F) Implementation Notes
- Do not replace
battlewords/storage.pynow; introduce a separate integration wrapper (e.g.,battlewords/hf_storage.py) in the next PR - Consider a private repo for write access; shortener JSON and settings JSONs can be public read
Challenge Mode & Remote Storage
- The app must support remote storage of challenge results using Hugging Face datasets.
- The leaderboard for a shared challenge (
game_id) must display all user results. - Sorting: Results are sorted by highest score (descending), then by fastest time (ascending).
- Each user result is appended to the challenge's
usersarray in the remote JSON. - The UI must allow submitting results to an existing challenge or creating a new one.