Help us shape the future of Go! Take the 2026 Go Developer Survey

common

package
v1.10.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 12, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DifficultySpecs = map[string]DifficultySpec{
	"Tutorial": {
		VineCountRange:   [2]int{3, 8},
		AvgLengthRange:   [2]int{6, 8},
		MaxBlockingDepth: 0,
		ColorCountRange:  [2]int{1, 5},
		MinGridOccupancy: 0.30,
		DefaultGrace:     3,
	},
	"Seedling": {
		VineCountRange:   [2]int{4, 60},
		AvgLengthRange:   [2]int{6, 8},
		MaxBlockingDepth: 1,
		ColorCountRange:  [2]int{1, 5},
		MinGridOccupancy: 0.93,
		DefaultGrace:     3,
	},
	"Sprout": {
		VineCountRange:   [2]int{8, 80},
		AvgLengthRange:   [2]int{3, 8},
		MaxBlockingDepth: 2,
		ColorCountRange:  [2]int{1, 5},
		MinGridOccupancy: 0.93,
		DefaultGrace:     3,
	},
	"Nurturing": {
		VineCountRange:   [2]int{12, 100},
		AvgLengthRange:   [2]int{3, 8},
		MaxBlockingDepth: 3,
		ColorCountRange:  [2]int{1, 6},
		MinGridOccupancy: 0.93,
		DefaultGrace:     3,
	},
	"Flourishing": {
		VineCountRange:   [2]int{15, 150},
		AvgLengthRange:   [2]int{2, 6},
		MaxBlockingDepth: 4,
		ColorCountRange:  [2]int{1, 6},
		MinGridOccupancy: 0.93,
		DefaultGrace:     3,
	},
	"Transcendent": {
		VineCountRange:   [2]int{15, 200},
		AvgLengthRange:   [2]int{2, 6},
		MaxBlockingDepth: 4,
		ColorCountRange:  [2]int{1, 6},
		MinGridOccupancy: 0.93,
		DefaultGrace:     4,
	},
}
View Source
var GridSizeRanges = map[string]struct {
	MinW, MinH, MaxW, MaxH int
}{
	"Tutorial":     {MinW: 5, MinH: 8, MaxW: 9, MaxH: 12},
	"Seedling":     {MinW: 6, MinH: 8, MaxW: 9, MaxH: 12},
	"Sprout":       {MinW: 9, MinH: 12, MaxW: 12, MaxH: 16},
	"Nurturing":    {MinW: 9, MinH: 16, MaxW: 12, MaxH: 20},
	"Flourishing":  {MinW: 12, MinH: 20, MaxW: 16, MaxH: 24},
	"Transcendent": {MinW: 16, MinH: 28, MaxW: 24, MaxH: 40},
}

GridSizeRanges defines grid size ranges per difficulty tier.

View Source
var HeadDirections = map[string][2]int{
	"right": {1, 0},
	"left":  {-1, 0},
	"up":    {0, 1},
	"down":  {0, -1},
}

HeadDirections defines valid head directions and their deltas.

View Source
var VineColors = map[string]string{
	"default":       "#888888",
	"moss_green":    "#7CB342",
	"sunset_orange": "#FF9800",
	"golden_yellow": "#FFC107",
	"royal_purple":  "#7C4DFF",
	"sky_blue":      "#29B6F6",
	"coral_red":     "#FF6E40",
	"lime_green":    "#CDDC39",
}

VineColors defines the available vine colors.

Functions

func ComplexityForDifficulty

func ComplexityForDifficulty(difficulty string) string

ComplexityForDifficulty returns the recommended complexity level.

func ComputeOccupancy

func ComputeOccupancy(level *Level) float64

ComputeOccupancy calculates the grid occupancy percentage for a level.

func CountVinesByColor

func CountVinesByColor(vines []Vine) map[string]int

CountVinesByColor counts how many vines use each color.

func CountVinesByDirection

func CountVinesByDirection(vines []Vine) map[string]int

CountVinesByDirection counts how many vines face each direction.

func DefaultGridSize

func DefaultGridSize(difficulty string) [2]int

DefaultGridSize returns default grid size for a difficulty (used when not specified).

func DetectCircularBlocking

func DetectCircularBlocking(vines []Vine) bool

DetectCircularBlocking detects circular dependencies in blocking relationships.

func DifficultyForLevel

func DifficultyForLevel(levelID int, modules []ModuleRange) string

DifficultyForLevel determines the difficulty tier for a level ID given modules. Each module should have a progression: Seedling → Sprout → Nurturing → Flourishing → Transcendent (final level).

func EnsureDir

func EnsureDir(dirPath string) error

EnsureDir creates a directory if it doesn't exist.

func FastValidateLevelCoverage

func FastValidateLevelCoverage(level *Level) error

FastValidateLevelCoverage performs fast structural checks on a level. It verifies:

  • grid size is positive
  • each vine path is contiguous (Manhattan adjacency)
  • no self-intersections within a vine
  • head direction matches the first segment (head -> neck)
  • all coordinates are in-bounds
  • every grid cell is assigned to exactly one vine or masked (full coverage)

func FileExists

func FileExists(filePath string) bool

FileExists checks if a file exists.

func GenerateLevelID

func GenerateLevelID(baseDir string, start int) int

GenerateLevelID generates a unique level ID.

func GetAverageVineLength

func GetAverageVineLength(vines []Vine) float64

GetAverageVineLength computes average vine length.

func GetLevelFilePath

func GetLevelFilePath(levelID int, baseDir string) string

GetLevelFilePath returns the expected file path for a level.

func GetMaximumVineLength

func GetMaximumVineLength(vines []Vine) int

GetMaximumVineLength returns the longest vine length.

func GetMinimumVineLength

func GetMinimumVineLength(vines []Vine) int

GetMinimumVineLength returns the shortest vine length.

func GraceForDifficulty

func GraceForDifficulty(difficulty string) int

GraceForDifficulty returns the default grace value for a difficulty.

func GridSizeForLevel

func GridSizeForLevel(levelID int, difficulty string) [2]int

GridSizeForLevel determines grid dimensions based on level ID and difficulty.

func ParsePointKey

func ParsePointKey(key string) (x, y int)

ParsePointKey parses a point key back to coordinates.

func PointKey

func PointKey(pt Point) string

PointKey creates a unique key for a point (used in maps).

func ResolveModulesPath

func ResolveModulesPath(configPath string) string

ResolveModulesPath resolves the modules.json file path.

func WriteLevel

func WriteLevel(filePath string, level *Level, overwrite bool) error

WriteLevel writes a level to a JSON file. Returns error if file exists and overwrite is false.

Types

type DifficultySpec

type DifficultySpec struct {
	VineCountRange   [2]int
	AvgLengthRange   [2]int
	MaxBlockingDepth int
	ColorCountRange  [2]int
	MinGridOccupancy float64
	DefaultGrace     int
}

DifficultySpec defines constraints for a difficulty tier.

type GeneratorConfig

type GeneratorConfig struct {
	MaxSeedRetries    int // retries to find a seed that can grow
	LocalRepairRadius int // radius for local repair tiles
	RepairRetries     int // number of local repair attempts per stuck region
}

GeneratorConfig holds generation algorithm tuning parameters and safety caps.

func GetGeneratorConfigForDifficulty

func GetGeneratorConfigForDifficulty(difficulty string) GeneratorConfig

GetGeneratorConfigForDifficulty returns tuned generator parameters for a difficulty tier.

type Level

type Level struct {
	ID         int    `json:"id"`
	Name       string `json:"name"`
	Difficulty string `json:"difficulty"` // "Tutorial", "Seedling", "Sprout", "Nurturing", "Flourishing", "Transcendent"
	GridSize   [2]int `json:"grid_size"`  // [width, height]
	Mask       *Mask  `json:"mask"`
	Vines      []Vine `json:"vines"`
	MaxMoves   int    `json:"max_moves"`
	MinMoves   int    `json:"min_moves"`
	Complexity string `json:"complexity"` // "tutorial", "low", "medium", "high", "extreme"
	Grace      int    `json:"grace"`      // 3 or 4
	// Generation metadata persisted for reproducibility & diagnostics
	GenerationSeed      int64   `json:"generation_seed,omitempty"`
	GenerationAttempts  int     `json:"generation_attempts,omitempty"`
	GenerationElapsedMS int64   `json:"generation_elapsed_ms,omitempty"`
	GenerationScore     float64 `json:"generation_score,omitempty"`
	// These are populated during validation but not persisted
	OccupancyPercent  float64             `json:"-"`
	ColorDistribution map[string]float64  `json:"-"`
	BlockingGraph     map[string][]string `json:"-"`
}

Level represents a complete game level.

func ReadLevel

func ReadLevel(filePath string) (*Level, error)

ReadLevel reads a single level from a JSON file.

func ReadLevelsFromDir

func ReadLevelsFromDir(dirPath string) ([]*Level, error)

ReadLevelsFromDir reads all level files from a directory.

func (*Level) GetGridHeight

func (l *Level) GetGridHeight() int

GetGridHeight returns the height of the grid.

func (*Level) GetGridWidth

func (l *Level) GetGridWidth() int

GetGridWidth returns the width of the grid.

func (*Level) GetOccupiedCells

func (l *Level) GetOccupiedCells() int

GetOccupiedCells returns the total number of cells occupied by vines.

func (*Level) GetTotalCells

func (l *Level) GetTotalCells() int

GetTotalCells returns the total number of cells in the grid.

func (*Level) Validate

func (l *Level) Validate() (violations, warnings []string)

Validate performs complete validation on a level.

type Mask

type Mask struct {
	Mode   string `json:"mode"`   // "show-all", "hide", "show"
	Points []any  `json:"points"` // [][]int or []Point
}

Mask represents the visual masking configuration for a level.

func (*Mask) IsMasked added in v0.31.0

func (m *Mask) IsMasked(x, y int) bool

IsMasked returns true if the given point should be masked (hidden) based on the mask mode.

type Module

type Module struct {
	ID            int      `json:"id"`
	Name          string   `json:"name"`
	LevelRange    [2]int   `json:"level_range"`
	Parable       *Parable `json:"parable"`
	UnlockMessage string   `json:"unlock_message"`
}

Module represents a module with parable content and level range.

type ModuleData

type ModuleData struct {
	Version           string                 `json:"version"`
	Modules           []Module               `json:"modules"`
	ColorDistribution map[string]interface{} `json:"color_distribution"`
	BlockingGraph     map[string]interface{} `json:"blocking_graph"`
}

ModuleData represents the complete modules.json structure.

type ModuleRange

type ModuleRange struct {
	ID    int
	Name  string
	Start int
	End   int
}

ModuleRange represents a difficulty tier range with module context.

func FindModuleForLevel

func FindModuleForLevel(levelID int, modules []ModuleRange) *ModuleRange

FindModuleForLevel finds the module containing the given level ID.

func GetModuleRange

func GetModuleRange(moduleName string, modules []ModuleRange) *ModuleRange

GetModuleRange returns the difficulty range for a module.

func LoadModules

func LoadModules(path string) ([]ModuleRange, error)

LoadModules loads module definitions from a JSON file. Falls back to default ranges if file not found.

type Parable

type Parable struct {
	Title           string `json:"title"`
	Scripture       string `json:"scripture"`
	Content         string `json:"content"`
	Reflection      string `json:"reflection"`
	BackgroundImage string `json:"background_image"`
}

Parable represents the parable content for a module.

type Point

type Point struct {
	X int `json:"x"`
	Y int `json:"y"`
}

Point represents a coordinate in the game grid.

func (Point) String

func (p Point) String() string

String returns a string representation of the point.

type Solver

type Solver struct {
	// contains filtered or unexported fields
}

Solver provides solvability checking for levels.

func NewSolver

func NewSolver(level *Level) *Solver

NewSolver creates a new solver for a level.

func (*Solver) IsSolvableBFS

func (s *Solver) IsSolvableBFS() bool

IsSolvableBFS checks solvability using a thorough BFS algorithm. This is the gold standard for validation but slower.

func (*Solver) IsSolvableGreedy

func (s *Solver) IsSolvableGreedy() bool

IsSolvableGreedy checks solvability using a fast greedy algorithm. This is used during level generation for speed.

type ValidationResult

type ValidationResult struct {
	Filename   string
	Violations []string
	Warnings   []string
	Valid      bool
	Timestamp  time.Time
}

ValidationResult holds the results of level validation.

type Validator

type Validator struct {
	// contains filtered or unexported fields
}

Validator validates level structure and constraints.

type VarietyProfile

type VarietyProfile struct {
	LengthMix  map[string]float64 // keys: "short","medium","long" => relative weights
	TurnMix    float64            // 0..1 proportion of turns (bendiness)
	RegionBias string             // "edge","center","balanced"
	DirBalance map[string]float64 // desired head dir distribution (right,left,up,down)
}

VarietyProfile controls shape and distribution characteristics for generated levels.

func GetPresetProfile

func GetPresetProfile(difficulty string) VarietyProfile

GetPresetProfile returns a VarietyProfile tuned for the given difficulty tier.

type Vine

type Vine struct {
	ID            string   `json:"id"`
	HeadDirection string   `json:"head_direction"` // "up", "down", "left", "right"
	OrderedPath   []Point  `json:"ordered_path"`
	VineColor     string   `json:"vine_color"`
	Blocks        []string `json:"blocks"`
}

Vine represents a single vine in the level.

func FindVineByID

func FindVineByID(vines []Vine, id string) *Vine

FindVineByID finds a vine by its ID.

func ShuffleVines

func ShuffleVines(vines []Vine, seed int64) []Vine

ShuffleVines randomly shuffles a slice of vines using a deterministic seed.

func SortVinesByID

func SortVinesByID(vines []Vine) []Vine

SortVinesByID returns vines sorted by ID.

func (*Vine) GetHead

func (v *Vine) GetHead() Point

GetHead returns the head segment (first point) of the vine.

func (*Vine) GetNeck

func (v *Vine) GetNeck() Point

GetNeck returns the neck segment (second point) of the vine.

func (*Vine) GetTail

func (v *Vine) GetTail() Point

GetTail returns the tail segment (last point) of the vine.

func (*Vine) Length

func (v *Vine) Length() int

Length returns the number of segments in the vine.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL