Games & Recreation API Reference

14 game engines, creative tools, and simulation services โ€” all pure Dart with no external dependencies, fully testable, and designed for Flutter widget integration via reactive state.

Architecture Pattern Every game/recreation service follows the same pattern: pure business logic in lib/core/services/, UI state bridged through providers in lib/state/providers/, and views in lib/views/. Services are framework-agnostic โ€” they manage grids, scores, and rules without any Flutter imports (except PixelArtService and SketchPadService which use dart:ui for color/offset types).

๐ŸŽฎ Classic Games

SnakeGameService

lib/core/services/snake_game_service.dart

Classic Snake on a 20ร—20 toroidal grid. The snake grows when it eats food, and the game ends on self-collision.

Key Types

TypeDescription
GridPoint(int x, int y)Immutable coordinate on the grid with value-equality
SnakeDirectionEnum: up, down, left, right

Properties

PropertyTypeDescription
snakeList<GridPoint>Snake body segments (head-first)
foodGridPointCurrent food position
directionSnakeDirectionCurrent movement direction
scoreintCurrent score
isGameOverboolWhether the game has ended

Methods

MethodSignatureDescription
newGame()voidReset grid, place snake at center, spawn food
tick()voidAdvance one frame โ€” move head, check food/collision, grow or trim tail
changeDirection(dir)voidSet direction (ignores 180ยฐ reversals)

Usage

final game = SnakeGameService(); game.newGame(); // Game loop (driven by Timer or Ticker) game.changeDirection(SnakeDirection.up); game.tick(); if (game.isGameOver) print('Score: ${game.score}');

TetrisGameService

lib/core/services/tetris_game_service.dart

Full Tetris implementation with all 7 standard tetrominoes (I, O, T, S, Z, J, L), wall-kick rotation, line clearing with scoring, and next-piece preview.

Key Types

TypeDescription
TetrominoTypeEnum of the 7 standard piece types
TetrisPoint(int x, int y)Board coordinate with value-equality and + operator
TetrominoA piece with type, rotation (0โ€“3), position, and computed cells

Properties

PropertyTypeDescription
boardList<List<int>>20ร—10 grid (0 = empty, 1โ€“7 = piece colors)
currentTetromino?Currently falling piece
nextTypeTetrominoType?Preview of the next piece
scoreintTotal score (1/3/5/8 points for 1/2/3/4 lines)
linesClearedintTotal lines cleared
levelintCurrent level (increases every 10 lines)
gameOverboolTrue when a new piece can't spawn

Methods

MethodSignatureDescription
newGame()voidClear board and start fresh
tick()voidDrop piece one row; lock if landed, clear lines, spawn next
moveLeft() / moveRight()voidHorizontal movement with collision check
rotate()voidClockwise rotation with wall-kick
hardDrop()voidInstant drop to lowest valid position

Game2048Service

lib/core/services/game_2048_service.dart

The classic 2048 sliding-tile puzzle on a 4ร—4 grid. Tiles merge when equal values collide. Spawns a 2 (90%) or 4 (10%) after each move. Win condition: reach the 2048 tile.

Properties

PropertyTypeDescription
gridList<List<int>>4ร—4 tile grid (0 = empty)
scoreintCurrent score (sum of all merges)
bestScoreintSession high score
wonboolTrue when 2048 tile reached

Methods

MethodSignatureDescription
newGame()voidReset grid, spawn 2 initial tiles
swipe(SwipeDirection)boolSlide + merge in direction; returns true if board changed
acknowledgeWin()voidAllow continued play past 2048
isGameOverbool (getter)True when no valid moves remain
Merge Algorithm Each swipe decomposes into per-row left-merges via _mergeRow(): remove zeros, scan left-to-right for adjacent equal values, merge once (no chain-merging within a single swipe), then pad with zeros. The grid is transposed/reversed as needed to reduce all 4 directions to left-merge.

๐Ÿงฉ Puzzle & Strategy

SudokuService

lib/core/services/sudoku_service.dart

Generates valid 9ร—9 Sudoku puzzles at 4 difficulty levels by first solving a blank grid via randomized backtracking, then removing cells to reach the target "givens" count.

Difficulty Levels

LevelGivens
Easy36
Medium30
Hard25
Expert20

Properties

PropertyTypeDescription
puzzleList<List<int>>Original puzzle (0 = empty)
solutionList<List<int>>Full solution for validation
playerGridList<List<int>>Player's working grid
givenList<List<bool>>Mask of non-editable cells

Methods

MethodSignatureDescription
generate(difficulty)voidGenerate a new puzzle at the given difficulty
setCell(row, col, value)boolSet a cell (returns false if cell is a given)
validate()boolCheck if current grid matches solution
getHint()(int, int, int)?Returns (row, col, value) for one empty cell
hasConflict(row, col)boolCheck if a cell conflicts with row/col/box peers

MinesweeperService

lib/core/services/minesweeper_service.dart

Full Minesweeper with 3 preset difficulties, first-click safety (mines are placed after the first reveal to guarantee a safe start), flood-fill auto-reveal for zero-adjacent cells, and flag/chord support.

Difficulty Presets

LevelGridMines
Beginner9 ร— 910
Intermediate16 ร— 1640
Expert16 ร— 3099

Cell Model

class MinesweeperCell { bool hasMine; bool isRevealed; bool isFlagged; int adjacentMines; }

Methods

MethodSignatureDescription
newGame(difficulty)voidInitialize grid for the selected difficulty
reveal(row, col)voidReveal a cell (flood-fills zeros); triggers mine placement on first click
toggleFlag(row, col)voidToggle flag marker on an unrevealed cell
isWonboolTrue when all non-mine cells are revealed
isLostboolTrue when a mine was revealed

TicTacToeService

lib/core/services/tic_tac_toe_service.dart

Tic Tac Toe with two modes: local two-player and vs. AI. The AI uses minimax search to play optimally (unbeatable on a 3ร—3 board).

Properties

PropertyTypeDescription
boardList<String>9-element flat board ('', 'X', or 'O')
currentPlayerString'X' or 'O'
vsAiboolWhether playing against AI
gameOverboolWhether the game has ended
winnerString?'X', 'O', or null (draw)
isDrawboolGame over with no winner

Methods

MethodSignatureDescription
makeMove(index)boolPlace current player's mark at index 0โ€“8; triggers AI response if enabled
setVsAi(bool)voidToggle AI mode (resets the board)
reset()voidClear board and start fresh

MemoryGameService

lib/core/services/memory_game_service.dart

Emoji-based memory card matching game with 4 difficulty levels (6โ€“15 pairs). Tracks moves, elapsed time, and calculates a star rating based on performance.

Difficulty Levels

LevelPairs
Easy6
Medium8
Hard10
Expert15

Card Model

class MemoryCard { final int id; final String emoji; bool isFaceUp; bool isMatched; }

Methods

MethodSignatureDescription
newGame(difficulty)voidShuffle and deal cards for the selected difficulty
flipCard(index)FlipResultFlip a card; returns match/mismatch/waiting status
isCompleteboolAll pairs matched
statsGameStatsMoves, time, star rating (1โ€“3 stars)

๐ŸŽจ Creative Tools

PixelArtCanvas

lib/core/services/pixel_art_service.dart

Grid-based pixel art editor with configurable canvas size (default 16ร—16), full undo/redo history, fill tool, and PNG export via dart:ui.

Constructor

PixelArtCanvas({int width = 16, int height = 16})

Methods

MethodSignatureDescription
setPixel(x, y, color)voidSet a single pixel (saves undo state)
getPixel(x, y)ColorRead a pixel's color
fill(x, y, color)voidFlood-fill from point with color
clear()voidReset all pixels to transparent
undo() / redo()voidNavigate undo/redo stack
toPng(pixelSize)Future<Uint8List>Export canvas as PNG bytes at given pixel scale

SketchPadService

lib/core/services/sketch_pad_service.dart

Freehand drawing canvas that records strokes as sequences of Offset points with configurable color and stroke width. Full undo/redo support.

Stroke Model

class SketchStroke { final List<Offset> points; final Color color; final double width; }

Methods

MethodSignatureDescription
startStroke(point, color, width)voidBegin a new stroke
addPoint(point)voidExtend the current stroke
endStroke()voidFinalize the current stroke
undo() / redo()voidNavigate stroke history
clear()voidRemove all strokes

๐Ÿ”ฌ Simulations & Visualizations

GameOfLifeService

lib/core/services/game_of_life_service.dart

Conway's Game of Life on a toroidal grid (edges wrap). Supports arbitrary grid sizes, preset patterns (glider, blinker, pulsar, Gosper glider gun), randomization, and single-step or continuous simulation.

Rules (B3/S23)

Properties

PropertyTypeDescription
gridList<List<bool>>Current cell states (defensive copy)
rows / colsintGrid dimensions
generationintSteps elapsed since last reset
liveCellCountintNumber of currently alive cells

Methods

MethodSignatureDescription
step()boolAdvance one generation; returns true if any cell changed
toggleCell(row, col)voidToggle a cell's state
randomize({density})voidFill grid randomly (default 30% alive)
loadPreset(name)voidLoad a named pattern (glider, pulsar, etc.)
resize(rows, cols)voidChange grid dimensions (clears state)
clear()voidKill all cells, reset generation counter
Toroidal Topology Neighbor counting wraps around grid edges using modular arithmetic, so patterns like gliders can traverse the entire grid without hitting walls.

SortVisualizerService

lib/core/services/sort_visualizer_service.dart

Step-by-step visualization of 5 sorting algorithms. Generates an array of SortStep snapshots that record comparisons, swaps, and sorted regions โ€” designed for animated playback.

Supported Algorithms

AlgorithmTimeSpace
Bubble SortO(nยฒ)O(1)
Selection SortO(nยฒ)O(1)
Insertion SortO(nยฒ)O(1)
Merge SortO(n log n)O(n)
Quick SortO(n log n)*O(log n)

Step Model

class SortStep { final List<int> array; // snapshot of array at this step final int? comparing1, comparing2; // indices being compared final Set<int> sorted; // indices known to be in final position final String description; // human-readable step explanation }

Methods

MethodSignatureDescription
generate(algorithm, size)List<SortStep>Generate all steps for the algorithm on a random array of given size
generateFromArray(algorithm, array)List<SortStep>Generate steps for a specific input array

๐ŸŽฒ Party & Fun

HangmanService

lib/core/services/hangman_service.dart

Classic Hangman word guessing game with a built-in word bank of 25+ words, each with a hint. 6 incorrect guesses allowed before game over.

Methods

MethodSignatureDescription
newGame()voidPick a random word and reset state
guessLetter(letter)boolGuess a letter; returns true if it appears in the word
displayWordStringCurrent word with unguessed letters as underscores
hintStringHint for the current word
isWon / isLostboolWin/loss state
wrongGuessesintNumber of incorrect guesses (max 6)

SimonSaysService

lib/core/services/simon_says_service.dart

Memory game where the computer plays an ever-growing sequence of colored buttons that the player must reproduce. Each successful round adds one flash. 4 buttons (green, red, yellow, blue).

Methods

MethodSignatureDescription
startNewGame()voidReset and begin with a 1-element sequence
playerInput(buttonIndex)InputResultSubmit a button press; returns correct/wrong/round-complete
sequenceList<int>Current computer sequence (for playback)
roundintCurrent round number
highScoreintBest score this session

RpsService

lib/core/services/rps_service.dart

Rock Paper Scissors with full history tracking, win/loss/draw stats, streak tracking, and a CPU opponent that plays randomly.

Types

TypeValues
RpsMoverock, paper, scissors
RpsOutcomewin, lose, draw

Methods

MethodSignatureDescription
play(RpsMove)RpsRoundPlay a round and get result (player move, CPU move, outcome)
statsRpsStatsCumulative stats: total rounds, wins, losses, draws, streaks, win rate
historyList<RpsRound>Full round history (most recent first)
reset()voidClear all history and stats

SpinWheelService

lib/core/services/spin_wheel_service.dart

Customizable spin wheel / random picker with preset configurations, history tracking, and option management. Great for decision-making or party games.

Methods

MethodSignatureDescription
addOption(text)voidAdd an option to the wheel
removeOption(text)voidRemove an option
loadPreset(preset)voidLoad a preset wheel configuration
spin()SpinResultSpin and return a random result
historyList<SpinResult>Previous spin results

ReactionTimeService

lib/core/services/reaction_time_service.dart

Reaction time testing with history (up to 100 results), average/best/worst stats, and session tracking. The UI handles the visual stimulus; this service manages scoring.

Methods

MethodSignatureDescription
addResult(result)voidRecord a reaction time measurement
averageMsdouble?Average reaction time across all results
bestMsint?Fastest reaction time
worstMsint?Slowest reaction time
clearHistory()voidReset all recorded results

Testing All game services are covered by tests in test/. Because services are pure Dart with no Flutter widget dependencies, they can be tested with flutter test using standard expect() assertions โ€” no widget pump or mock framework needed.

Last updated: April 2026 ยท Back to documentation home