Skip to content

yunniko/mosaic_generator

Repository files navigation

Mosaic Crochet Generator

A console application for generating, editing, validating, and exporting overlay mosaic crochet patterns. Built as a study project to explore pattern generation algorithms, symmetry transforms, and constraint-based design.

Overview

Overlay mosaic crochet is a technique where each row uses a single yarn color and two stitch types — Single Crochet (SC) and Double Crochet (DC) — to create colorwork patterns. A DC reaches down two rows and pulls up the color from below, visually overriding the cell in the row beneath it. This creates strict constraints: no two DCs can stack vertically in the same column on consecutive rows, and the foundation rows cannot contain DCs.

This application models the visual grid (what color each cell appears) and derives the underlying stitch map automatically. It generates random valid patterns from a checkerboard base state, supports five symmetry modes including 8-fold radial symmetry, and provides a real-time keyboard editor with constraint enforcement.

Technologies

  • C# / .NET 10.0 — Console application
  • xUnit — Unit testing framework (66 tests)
  • Raw BMP export — 24-bit bitmap image generation without external dependencies

Design Patterns and Architecture

Pattern Usage
MVC separation PatternGrid (model), PatternRenderer (view), Program/PatternEditor (controller)
Strategy SymmetryHelper.GetMirrorPositions selects transform logic based on SymmetryMode enum
Validator PatternValidator checks all mosaic crochet rules and returns violation lists
Factory method PatternGrid.CreateCheckerboard() constructs pre-configured grid instances
Command Menu's nested MenuItem record wraps Action delegates for menu items
Builder-style generation PatternGenerator.Generate builds patterns through multi-pass random deviation from a base state

Key Design Decisions

  • Visual grid as source of truth. The grid stores what color each cell appears to be. The stitch map (SC/DC) is derived on the fly via HasDC(), eliminating state synchronization bugs.
  • Checkerboard base state. All patterns start from a checkerboard grid (alternating colors on even interior rows). Deviations from this base are applied randomly under constraint checking. This produces more visually interesting patterns than starting from a blank (all-native) grid.
  • Odd dimensions enforced. Both width and height are forced to odd numbers so the checkerboard pattern is symmetric across all axes.
  • Soft constraints alongside hard constraints. Hard rules (no stacked DCs, valid foundation rows) are strictly enforced. Soft rules (avoid horizontal DC sequences > 5) are probabilistically enforced — 75% skip chance — allowing occasional long runs without eliminating them entirely.

Project Structure

MosaicCrochetGenerator/
  Program.cs              Main loop, menus, action wiring
  ProgramSettings.cs      Configuration (dimensions, symmetry, density, display)
  PatternGrid.cs          2D visual grid, native color logic, checkerboard factory
  PatternGenerator.cs     Random valid pattern generation with symmetry
  PatternValidator.cs     Mosaic crochet rule checking
  PatternRenderer.cs      Console ASCII rendering with DC markers
  PatternEditor.cs        Keyboard-driven grid editor
  PatternFileManager.cs   Save/load .mcpat data files and BMP image export
  SymmetryHelper.cs       Mirror position calculation for all symmetry modes
  Menu.cs                 Console menu system (MenuItem is a nested record)
  CellColor.cs            ColorA / ColorB enum
  SymmetryMode.cs         None / Vertical / Horizontal / Both / Radial enum

MosaicCrochetGenerator.Tests/
  PatternGridTests.cs
  PatternGeneratorTests.cs
  PatternValidatorTests.cs
  SymmetryHelperTests.cs
  PatternFileManagerTests.cs
  ProgramSettingsTests.cs

User Manual

Getting Started

Build and run:

dotnet build
dotnet run --project MosaicCrochetGenerator

Run tests:

dotnet test

On startup, you see the main menu:

Mosaic Crochet Generator
========================

Main Menu
1. Generate Pattern
2. Edit Pattern
3. Load Pattern
4. Save Pattern
5. Settings
6. Exit
Select an option:

Main Menu

1. Generate Pattern

Generates a random valid mosaic crochet pattern using the current settings (dimensions, symmetry mode, density).

  • If you have an unsaved pattern from a previous generate or edit, you will be asked to confirm before replacing it.
  • After generation, the pattern is rendered to the console along with statistics:
    • Deviation from grid — percentage of interior cells that differ from the checkerboard base (0% = pure grid, higher = more varied).
    • Max DC sequence — longest horizontal run of consecutive DCs in any row.
    • Sequences >5 — count of horizontal DC runs longer than 5 (these are harder to crochet).
  • The pattern is automatically validated against all mosaic crochet rules.

2. Edit Pattern

Opens the interactive pattern editor. If no pattern exists, a blank checkerboard grid is created using the current settings.

Editor Controls

Key Action
Arrow Up Move cursor up one row
Arrow Down Move cursor down one row
Arrow Left Move cursor left one column
Arrow Right Move cursor right one column
Space Toggle the cell under the cursor
Q / Esc Exit editor and return to main menu

Editor Behavior

  • The cursor is highlighted with a yellow [] marker.
  • Symmetry auto-apply: When you toggle a cell, all mirror positions are toggled simultaneously based on the active symmetry mode. For example, in Vertical mode toggling column 3 also toggles column (width - 3).
  • Constraint enforcement: The editor blocks invalid toggles and shows a red status message explaining why:
    • Cannot toggle foundation row (row 1) or top row.
    • Cannot toggle if it would create stacked DCs (vertically adjacent non-native cells).
    • In Radial mode: cannot toggle boundary columns or cells with horizontal non-native neighbors.
  • A validation summary is shown at the bottom of the screen.

3. Load Pattern

Loads a previously saved pattern from a .mcpat data file.

  • Enter the filename without the .mcpat extension.
  • The pattern's symmetry mode is restored from the file.
  • After loading, the pattern is rendered and validated.
  • Press Enter with no input to cancel.

4. Save Pattern

Saves the current pattern as both a data file (.mcpat) and a bitmap image (.bmp).

  • A default filename is suggested in the format YYYYMMDD_HHMMSS_Symmetry_W_H (e.g., 20260308_143022_Radial_27_27). Press Enter to accept or type a custom name.
  • Overwrite protection: If files with the given name already exist, you are prompted to:
    1. Overwrite the existing files
    2. Choose a different name
    3. Cancel

Data File Format (.mcpat)

Plain text. First line: width height symmetryMode. Following lines: one row per line, 0 for ColorA, 1 for ColorB. Row 0 (foundation) is the first data line.

Image Export (.bmp)

24-bit BMP with no external dependencies:

  • Each cell is 15×15 pixels.
  • 1px gray grid lines between all cells.
  • Row numbers on the left side, column numbers below the grid.
  • ColorA = dark navy, ColorB = white.
  • DC markers: a circular dot in the opposite color at the center of cells where a DC stitch is performed.

5. Settings

Opens the settings submenu. The menu loops until you select Back, at which point any loaded pattern is re-rendered with the updated settings.

Settings (W:27 H:27 Sym:Radial Den:3 Display:██░░)
1. Set Width
2. Set Height
3. Set Symmetry
4. Set Density
5. Set Display Characters
6. Back

Width and Height

  • Range: 5 to 99 (odd numbers only — adjusted automatically if an even value is entered).
  • In Radial mode, the generator forces a square grid using the larger dimension.

Symmetry Modes

Mode Description
None No symmetry enforced.
Vertical Left-right mirror along the center column.
Horizontal Top-bottom mirror along the center row.
Both Vertical + Horizontal combined (4 quadrants).
Radial 8-fold symmetry: 4 mirrors + 4 rotations. Requires a square grid. Produces kaleidoscope-like patterns.

Density (1-5)

Controls how much the generated pattern deviates from the checkerboard base:

Density Behavior Typical Deviation
1 Sparse — mostly grid pattern ~11%
2 Light variation ~25%
3 Moderate (default) ~40%
4 Dense variation ~55%
5 Maximum density ~64%

Higher density means more passes over the grid with higher per-cell probability of deviation.

Display Characters

Choose from 4 presets for console rendering:

# ColorA ColorB Look
1 ██ ░░ Default, high contrast
2 ░░ ██ Inverted
3 @@ .. Distinctive
4 .. @@ Inverted

Exiting Settings re-renders the current pattern with the new characters if one is loaded.

6. Exit

Exits the application immediately.

Console Rendering

The pattern is displayed bottom-up (row 1 at the bottom, matching crochet working direction). Row numbers are shown on the left, column numbers below the grid.

Tips

  • Quick iteration: Generate several patterns rapidly to find one you like, then use the editor to fine-tune specific cells.
  • Start with Radial: The default 27x27 Radial mode produces striking kaleidoscope patterns that are satisfying to crochet.
  • Watch DC sequences: Patterns with lower "Max DC sequence" values are easier to crochet. Long horizontal DC runs can be tedious. Adjust density downward if sequences are too long.
  • Use Save often: The timestamp-based default filename makes it easy to save multiple variations without naming conflicts.
  • BMP for printing: The exported BMP includes grid lines and numbers, making it suitable for printing as a crochet chart.

Development

This project was developed collaboratively with Claude Code (Claude Opus 4.6, Anthropic's AI coding assistant). The entire codebase — architecture, implementation, tests, and documentation — was produced through iterative human-AI pair programming sessions, with the human providing requirements, domain knowledge about mosaic crochet, and design direction.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages