match3

package
v0.4.0-rc.1 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 14 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package match3 is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package match3 provides deterministic match-3 puzzle boards, versioned YAML level definitions, shape detection (3, 4, 5, L, and T), extensible special pieces and combinations, multi-hit blockers (jelly, ice, chain, and crate), gravity across holes and past blockers, step-by-step cascade resolutions, score-ranked hints, seeded deadlock reshuffles, saveable snapshots, and headless level simulation and solving.

Every random draw comes from a random.Stream, so identical seeds and swap sequences produce identical boards, cascades, and reshuffles on every platform.

Index

Examples

Constants

View Source
const FormatVersion = 1

FormatVersion is the current match-3 level YAML schema version.

View Source
const SchemaComment = "# yaml-language-server: $schema=" + SchemaURL

SchemaComment is the first line EncodeLevel writes so YAML language servers validate and complete match-3 level files automatically.

View Source
const SchemaURL = "https://nsgo.games/schemas/match3.v1.json"

SchemaURL is where the JSON Schema of version 1 match-3 level files is published.

View Source
const SnapshotVersion = 1

SnapshotVersion is the Snapshot schema version this package reads and writes.

Variables

View Source
var ErrInvalidSnapshot = errors.New("match3: invalid snapshot")

ErrInvalidSnapshot reports a Snapshot rejected by Board.Restore.

Functions

func Adjacent

func Adjacent(a, b Point) bool

Adjacent reports whether a and b are orthogonally adjacent.

func DefaultScore

func DefaultScore(step Step) int

DefaultScore computes standard match-3 step points: 30 per cleared piece, shape bonuses (+40 for 4-line, +120 for 5-line, +90 for L/T), +50 per additional simultaneous match, +80 per triggered special, and +20 per blocker hit, all multiplied by step.Combo.

func EncodeLevel

func EncodeLevel(l Level) ([]byte, error)

EncodeLevel validates l and writes it in canonical 2-space YAML with a yaml-language-server schema comment on the first line.

Types

type Blocker

type Blocker struct {
	Kind BlockerKind `json:"kind,omitempty" yaml:"kind,omitempty"`
	HP   int         `json:"hp,omitempty" yaml:"hp,omitempty"`
}

Blocker holds a cell's foreground blocker (ice, chain, or crate) and remaining HP.

type BlockerDoc

type BlockerDoc struct {
	// X is the zero-based column coordinate.
	X int `yaml:"x" schema:"minimum=0"`
	// Y is the zero-based row coordinate.
	Y int `yaml:"y" schema:"minimum=0"`
	// Kind is the blocker type: jelly, ice, chain, or crate.
	Kind BlockerKind `yaml:"kind" schema:"required,enum=jelly|ice|chain|crate"`
	// HP is the blocker's starting hit points (at least 1).
	HP int `yaml:"hp" schema:"required,minimum=1"`
}

BlockerDoc places one blocker or jelly underlay on a board cell.

type BlockerHit

type BlockerHit struct {
	// At is the damaged cell coordinate.
	At Point
	// Kind is jelly, ice, chain, or crate.
	Kind BlockerKind
	// Damage is the hit points removed in this hit.
	Damage int
	// RemainingHP is the blocker's remaining hit points after damage (0 when destroyed).
	RemainingHP int
	// Destroyed is true when RemainingHP reached 0.
	Destroyed bool
}

BlockerHit records damage dealt to a blocker or jelly underlay during a cascade step.

type BlockerKind

type BlockerKind string

BlockerKind identifies the behavior of a blocker placed on a board cell.

const (
	// BlockerNone indicates no foreground blocker on a cell.
	BlockerNone BlockerKind = ""
	// BlockerJelly is an underlay beneath a piece; it allows swapping, matching,
	// and gravity, and takes 1 damage when a piece on its cell is cleared or hit
	// by a special.
	BlockerJelly BlockerKind = "jelly"
	// BlockerIce encases a cell so its piece cannot swap, match, or fall; it
	// takes 1 damage from orthogonally adjacent matches or direct special hits.
	BlockerIce BlockerKind = "ice"
	// BlockerChain locks a piece in place so it cannot swap or fall, while still
	// allowing it to participate in matches; matching it or hitting it with a
	// special damages the chain by 1 instead of clearing the piece.
	BlockerChain BlockerKind = "chain"
	// BlockerCrate is a solid obstacle occupying a cell (holding no piece); it
	// blocks straight gravity and takes 1 damage from orthogonally adjacent
	// matches or direct special hits.
	BlockerCrate BlockerKind = "crate"
)

type Board

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

Board holds the complete deterministic state of a running match-3 level.

func NewBoard

func NewBoard(level Level, rng *random.Stream, opts ...Option) (*Board, error)

NewBoard validates level, constructs a deterministic Board drawing from rng (or random.New(level.Seed) when rng is nil), and populates the initial grid. When level.Layout is omitted, the seeded fill guarantees no initial matches and at least one valid move whenever the board geometry permits one.

func (*Board) AdvanceTime

func (b *Board) AdvanceTime(dt time.Duration)

AdvanceTime decrements TimeLeft by dt on timed levels (clamped at 0).

func (*Board) BlockersCleared

func (b *Board) BlockersCleared(kind BlockerKind) int

BlockersCleared returns how many blockers of kind have been destroyed so far.

func (*Board) CanSwap

func (b *Board) CanSwap(a, c Point) bool

CanSwap reports whether swapping a and b is legal and produces either a match or a registered special combination, without mutating b or advancing its RNG.

func (*Board) CellAt

func (b *Board) CellAt(p Point) Cell

CellAt returns the cell at p, or a Hole cell if p is out of bounds.

func (*Board) Clone

func (b *Board) Clone() *Board

Clone returns a deep copy of b including its RNG state and RuleSet.

func (*Board) CollectedColor

func (b *Board) CollectedColor(color int) int

CollectedColor returns the number of cleared pieces of 1-based color id.

func (*Board) Dead

func (b *Board) Dead() bool

Dead reports whether b has no legal swap available.

func (*Board) EnsurePlayable

func (b *Board) EnsurePlayable() bool

EnsurePlayable checks whether b is deadlocked on an active board; if so, it calls Board.Reshuffle and reports whether a reshuffle occurred.

func (*Board) FindMatches

func (b *Board) FindMatches() []Match

FindMatches detects all horizontal, vertical, L, and T match groups on b, sorted deterministically by top-left cell coordinate.

func (*Board) Finished

func (b *Board) Finished() bool

Finished reports whether the level has ended in either a win or a loss.

func (*Board) GoalProgress

func (b *Board) GoalProgress() float64

GoalProgress returns the mean completion ratio across all level goals in [0, 1].

func (*Board) Goals

func (b *Board) Goals() []GoalProgress

Goals returns live progress for every goal defined on the level.

func (*Board) Height

func (b *Board) Height() int

Height returns the number of rows on b.

func (*Board) Hint

func (b *Board) Hint() (Move, bool)

Hint returns the highest-scoring legal swap on b, or (Move{}, false) when b is dead or finished.

func (*Board) InBounds

func (b *Board) InBounds(p Point) bool

InBounds reports whether p lies within [0, Width) x [0, Height).

func (*Board) IsExit

func (b *Board) IsExit(p Point) bool

IsExit reports whether p is an exit cell that collects bring-down items.

func (*Board) IsHole

func (b *Board) IsHole(p Point) bool

IsHole reports whether p is out of bounds or masked out as a hole.

func (*Board) ItemsCollected

func (b *Board) ItemsCollected() int

ItemsCollected returns the number of bring-down items delivered to exit cells.

func (*Board) Level

func (b *Board) Level() Level

Level returns a copy of the level definition backing b.

func (*Board) Lost

func (b *Board) Lost() bool

Lost reports whether a move or time limit expired before all goals were met.

func (*Board) MaxCombo

func (b *Board) MaxCombo() int

MaxCombo returns the highest cascade combo depth reached so far.

func (*Board) MovesLeft

func (b *Board) MovesLeft() int

MovesLeft returns the remaining swap budget (0 on time-only levels).

func (*Board) PieceAt

func (b *Board) PieceAt(p Point) Piece

PieceAt returns the piece at p, or an empty Piece if p is out of bounds or a hole.

func (*Board) RemainingJelly

func (b *Board) RemainingJelly() int

RemainingJelly returns the number of cells that still have jelly HP > 0.

func (*Board) Reshuffle

func (b *Board) Reshuffle() bool

Reshuffle deterministically rearranges movable pieces using b's random.Stream while keeping all holes, blockers (jelly, ice, chain, crate), immovable pieces, and bring-down items fixed in place. The resulting layout has no immediate matches and at least one valid move whenever the open cells permit one.

func (*Board) Reshuffles

func (b *Board) Reshuffles() int

Reshuffles returns the number of deadlock reshuffles performed so far.

func (*Board) Restore

func (b *Board) Restore(s Snapshot) error

Restore validates s and atomically replaces b's runtime state with s. If s is invalid, b is left unchanged and an error wrapping ErrInvalidSnapshot is returned.

func (*Board) Score

func (b *Board) Score() int

Score returns the cumulative score earned on b.

func (*Board) Snapshot

func (b *Board) Snapshot() Snapshot

Snapshot returns a deep copy of b's state that shares no memory with b.

func (*Board) StateKey

func (b *Board) StateKey() string

StateKey returns a canonical deterministic string representing the board grid, blockers, jelly, score, goal counters, and remaining limits (suitable for solver visited sets).

func (*Board) Swap

func (b *Board) Swap(a, c Point) Resolution

Swap exchanges adjacent cells a and c, resolves every resulting match, special creation, special trigger chain, blocker hit, item collection, gravity fall, spawn, and subsequent cascade wave, and returns the step-by-step Resolution.

If the swap is illegal or creates neither a match nor a special combination, the board is left unchanged and Resolution.Valid is false.

Example
package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/match3"
	"github.com/nsgo-dev/game/pkg/random"
)

func main() {
	level := match3.Level{
		Version: 1,
		Width:   4,
		Height:  4,
		Colors:  []string{"ruby", "sapphire", "emerald"},
		Moves:   10,
		Layout: []string{
			"ruby ruby sapphire emerald",
			"emerald sapphire ruby emerald",
			"sapphire emerald sapphire ruby",
			"emerald sapphire ruby emerald",
		},
		Goals: []match3.GoalDoc{{Kind: match3.GoalScore, Target: 300}},
	}
	b, err := match3.NewBoard(level, random.New(1))
	if err != nil {
		fmt.Println(err)
		return
	}

	// Non-adjacent cells never swap.
	bad := b.Swap(match3.Point{X: 0, Y: 0}, match3.Point{X: 2, Y: 0})
	fmt.Println("non-adjacent valid:", bad.Valid)

	// Swapping (2,0) and (2,1) completes a 3-ruby row and resolves gravity + spawns.
	res := b.Swap(match3.Point{X: 2, Y: 0}, match3.Point{X: 2, Y: 1})
	fmt.Printf("valid: %v, first match shape: %s, cleared: %d, moves left: %d\n",
		res.Valid, res.Steps[0].Matches[0].Shape, len(res.Steps[0].Cleared), b.MovesLeft())
}
Output:
non-adjacent valid: false
valid: true, first match shape: line3, cleared: 3, moves left: 9

func (*Board) TimeLeft

func (b *Board) TimeLeft() time.Duration

TimeLeft returns the remaining time budget (0 on move-only levels).

func (*Board) TotalMatches

func (b *Board) TotalMatches() int

TotalMatches returns the total number of match groups cleared so far.

func (*Board) TotalSwaps

func (b *Board) TotalSwaps() int

TotalSwaps returns the total number of valid player swaps completed so far.

func (*Board) ValidMoves

func (b *Board) ValidMoves() []Move

ValidMoves returns every legal swap on b ranked by descending immediate step-1 score, breaking ties by combo status and then coordinate order.

func (*Board) Width

func (b *Board) Width() int

Width returns the number of columns on b.

func (*Board) Won

func (b *Board) Won() bool

Won reports whether every level goal is satisfied.

type Cell

type Cell struct {
	// Hole is true when this coordinate is masked out of the board.
	Hole bool `json:"hole,omitempty" yaml:"hole,omitempty"`
	// Piece is the piece currently occupying this cell (empty when Piece.Empty()).
	Piece Piece `json:"piece,omitempty" yaml:"piece,omitempty"`
	// Jelly is the remaining hit points of the jelly underlay beneath this cell (0 if none).
	Jelly int `json:"jelly,omitempty" yaml:"jelly,omitempty"`
	// Blocker is the foreground blocker (ice, chain, or crate) on this cell, if any.
	Blocker Blocker `json:"blocker,omitempty" yaml:"blocker,omitempty"`
}

Cell holds the complete state of one board coordinate.

func (Cell) BlocksGravity

func (c Cell) BlocksGravity() bool

BlocksGravity reports whether c stops pieces from falling vertically through it.

func (Cell) CanFall

func (c Cell) CanFall() bool

CanFall reports whether the piece on c can move under gravity.

func (Cell) CanMatch

func (c Cell) CanMatch() bool

CanMatch reports whether the piece on c can participate in a color match.

func (Cell) CanSwap

func (c Cell) CanSwap() bool

CanSwap reports whether the piece on c can be swapped by the player.

type ClearedCell

type ClearedCell struct {
	// At is the cleared cell coordinate.
	At Point
	// Piece is the piece that was removed.
	Piece Piece
}

ClearedCell records a piece removed from the board during a cascade step.

type ComboContext

type ComboContext struct {
	Board  *Board
	A      Point
	B      Point
	PieceA Piece
	PieceB Piece
}

ComboContext provides read-only board context to a ComboRule.

type ComboOutcome

type ComboOutcome struct {
	// Cells are the playable cells directly hit by the combination.
	Cells []Point
	// TargetColor records the target color when a color-clear special participates.
	TargetColor int
	// ExtraTriggers optionally schedules additional special activations (such as color + line
	// triggering a line clear at every cell of the partner's color).
	ExtraTriggers []ExtraTrigger
}

ComboOutcome describes the cells affected and any secondary special activations produced by swapping two pieces in a special combination.

type ComboRule

type ComboRule func(ctx ComboContext) ComboOutcome

ComboRule computes the effect of swapping two special pieces (or a colorless special with a piece).

type CreatedSpecial

type CreatedSpecial struct {
	// At is the cell where the special piece was placed.
	At Point
	// Piece is the spawned special piece.
	Piece Piece
	// Shape is the match shape that created it.
	Shape Shape
}

CreatedSpecial records a special piece spawned by a match.

type CreationRule

type CreationRule func(m Match) (Piece, bool)

CreationRule maps a detected Match to the special piece spawned at Match.Origin.

type ExtraTrigger

type ExtraTrigger struct {
	Origin Point
	Piece  Piece
}

ExtraTrigger schedules a synthetic special trigger at Origin during a combo resolution.

type Fall

type Fall struct {
	// From is the piece's coordinate before gravity in this step.
	From Point
	// To is the piece's coordinate after gravity in this step.
	To Point
	// Piece is the piece that moved.
	Piece Piece
}

Fall records an existing piece moving under gravity (vertically or diagonally).

type GoalDoc

type GoalDoc struct {
	// Kind is the goal type: score, collect, clear_jelly, bring_down, or clear_blocker.
	Kind GoalKind `yaml:"kind" schema:"required,enum=score|collect|clear_jelly|bring_down|clear_blocker"`
	// Target is the required count or score (omitted or 0 for clear_jelly, which clears all jelly).
	Target int `yaml:"target,omitempty" schema:"minimum=0"`
	// Color names the piece color for a collect goal.
	Color string `yaml:"color,omitempty"`
	// Blocker names the blocker kind for a clear_blocker goal.
	Blocker BlockerKind `yaml:"blocker,omitempty" schema:"enum=jelly|ice|chain|crate"`
}

GoalDoc describes one level win condition.

type GoalKind

type GoalKind string

GoalKind identifies a level win condition.

const (
	// GoalScore requires reaching at least Target total score.
	GoalScore GoalKind = "score"
	// GoalCollect requires clearing at least Target pieces of Color.
	GoalCollect GoalKind = "collect"
	// GoalClearJelly requires clearing every jelly underlay on the board.
	GoalClearJelly GoalKind = "clear_jelly"
	// GoalBringDown requires dropping at least Target bring-down items onto exit cells.
	GoalBringDown GoalKind = "bring_down"
	// GoalClearBlocker requires destroying at least Target blockers of kind Blocker.
	GoalClearBlocker GoalKind = "clear_blocker"
)

type GoalProgress

type GoalProgress struct {
	Goal     GoalDoc
	Current  int
	Target   int
	Complete bool
}

GoalProgress reports live progress toward one level goal.

type Level

type Level struct {
	// Version is the level format version and must be 1.
	Version int `yaml:"version" schema:"required,minimum=1,maximum=1"`
	// ID is an optional stable identifier for the level.
	ID string `yaml:"id,omitempty"`
	// Name is an optional display name for the level.
	Name string `yaml:"name,omitempty"`
	// Width is the number of board columns and must be at least 3.
	Width int `yaml:"width" schema:"required,minimum=3"`
	// Height is the number of board rows and must be at least 3.
	Height int `yaml:"height" schema:"required,minimum=3"`
	// Colors lists the distinct piece color names (at least 3), assigned 1-based IDs in order.
	Colors []string `yaml:"colors" schema:"required,minItems=3"`
	// Seed is the default RNG seed used when NewBoard is given a nil random.Stream.
	Seed uint64 `yaml:"seed,omitempty"`
	// Moves is the maximum number of player swaps allowed (0 when using only TimeLimit).
	Moves int `yaml:"moves,omitempty" schema:"minimum=0"`
	// TimeLimit is the maximum play duration allowed (0 when using only Moves).
	TimeLimit time.Duration `yaml:"timeLimit,omitempty"`
	// Mask defines playable cells ('.') and holes ('X'), one row string per board row.
	// When omitted, all Width*Height cells are playable.
	Mask []string `yaml:"mask,omitempty"`
	// Layout optionally specifies initial cell contents, one space-separated row per board row.
	// Tokens are '.' (empty or hole), '?' (seeded fill), 'item' (bring-down item),
	// '<color>' (normal piece), '<color>:<special>' (colored special), or 'special:<special>'
	// (colorless special such as 'special:color'). When omitted, the board uses seeded fill.
	Layout []string `yaml:"layout,omitempty"`
	// Spawners optionally configures per-column spawn rows, color weights, or disabled columns.
	Spawners []SpawnerDoc `yaml:"spawners,omitempty"`
	// Blockers places jelly underlays and foreground blockers (ice, chain, crate) with hit points.
	Blockers []BlockerDoc `yaml:"blockers,omitempty"`
	// Exits overrides the cells that collect bring-down items. When omitted, the bottom-most
	// playable cell in each column acts as an exit.
	Exits []PointDoc `yaml:"exits,omitempty"`
	// Goals lists one or more win conditions that must all be satisfied to win the level.
	Goals []GoalDoc `yaml:"goals" schema:"required,minItems=1"`
}

Level is a validated version-one match-3 level definition.

func LoadLevelFS

func LoadLevelFS(fsys fs.FS, name string) (Level, error)

LoadLevelFS reads and parses a match-3 level YAML file from fsys.

func ParseLevel

func ParseLevel(data []byte) (Level, error)

ParseLevel decodes and validates a version-one match-3 level YAML document. Unknown fields, duplicate keys, and trailing documents are refused.

Example
package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/match3"
	"github.com/nsgo-dev/game/pkg/random"
)

func main() {
	level, err := match3.ParseLevel([]byte(`version: 1
id: intro-01
width: 4
height: 4
colors: [ruby, sapphire, emerald]
seed: 7
moves: 10
goals:
  - kind: score
    target: 300
`))
	if err != nil {
		fmt.Println(err)
		return
	}
	b, err := match3.NewBoard(level, random.New(level.Seed))
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("%dx%d board, %d moves, initial matches: %d, dead: %v\n",
		b.Width(), b.Height(), b.MovesLeft(), len(b.FindMatches()), b.Dead())

	// A level with an unsupported version is refused.
	_, err = match3.ParseLevel([]byte("version: 2\nwidth: 3\nheight: 3\ncolors: [a, b, c]\nmoves: 5\ngoals:\n  - kind: score\n    target: 100\n"))
	fmt.Println(err != nil)
}
Output:
4x4 board, 10 moves, initial matches: 0, dead: false
true

func ParseLevelWith

func ParseLevelWith(data []byte, file string) (Level, error)

ParseLevelWith is ParseLevel with an optional source file name attached to errors.

func (Level) ColorID

func (l Level) ColorID(name string) int

ColorID returns the 1-based color ID for name, or 0 if name is not in l.Colors.

func (Level) ColorName

func (l Level) ColorName(id int) string

ColorName returns the color name for a 1-based color ID, or "" if out of range.

func (Level) IsHole

func (l Level) IsHole(x, y int) bool

IsHole reports whether (x, y) is a masked-out hole according to l.Mask.

func (Level) Validate

func (l Level) Validate() error

Validate checks l's version, dimensions, colors, limits, mask, spawners, blockers, layout tokens, exits, and goals.

type Match

type Match struct {
	// Shape is the classified match shape (line3, line4, line5, L, or T).
	Shape Shape
	// Orientation is horizontal, vertical, or both.
	Orientation Orientation
	// Color is the 1-based color ID of the matched pieces.
	Color int
	// Cells lists the unique coordinates in this match, sorted by Y then X.
	Cells []Point
	// Origin is the preferred cell where any special created by this match spawns.
	Origin Point
}

Match describes one detected match group and its shape.

type Move

type Move struct {
	// A and B are the adjacent cell coordinates to swap.
	A Point
	B Point
	// Score is the immediate step-1 score produced by this swap (used to rank hints).
	Score int
	// MaxShape is the strongest match shape produced by this swap, if any.
	MaxShape Shape
	// IsCombo is true when this swap activates a special-piece combination.
	IsCombo bool
}

Move describes one legal adjacent swap and its immediate score estimate.

func PolicyBestScore

func PolicyBestScore(_ *Board, moves []Move, _ *random.Stream) (Move, bool)

PolicyBestScore picks the highest-scoring legal move (equivalent to Board.Hint).

func PolicyGoalFirst

func PolicyGoalFirst(b *Board, moves []Move, _ *random.Stream) (Move, bool)

PolicyGoalFirst evaluates each legal move on a clone and prefers moves that increase goal completion progress the most, breaking ties by score.

func PolicyRandom

func PolicyRandom(_ *Board, moves []Move, rng *random.Stream) (Move, bool)

PolicyRandom picks a uniformly random legal move from rng.

type Option

type Option func(*boardConfig)

Option configures NewBoard.

func WithRules

func WithRules(rules *RuleSet) Option

WithRules configures a custom RuleSet for special creation, triggers, combinations, and scoring. When omitted, DefaultRules is used.

type Orientation

type Orientation string

Orientation identifies whether a match runs horizontally, vertically, or both.

const (
	// OrientationNone indicates an unset orientation.
	OrientationNone Orientation = ""
	// OrientationHorizontal indicates a horizontal run.
	OrientationHorizontal Orientation = "horizontal"
	// OrientationVertical indicates a vertical run.
	OrientationVertical Orientation = "vertical"
	// OrientationBoth indicates intersecting horizontal and vertical runs (L or T).
	OrientationBoth Orientation = "both"
)

type Piece

type Piece struct {
	// Color is the 1-based color ID (0 for empty, drop items, or colorless specials like SpecialColor).
	Color int `json:"color,omitempty" yaml:"color,omitempty"`
	// Special identifies a special piece effect, or SpecialNone for a regular piece.
	Special SpecialKind `json:"special,omitempty" yaml:"special,omitempty"`
	// Item marks a bring-down collectible item that cannot match by color and is collected at exits.
	Item bool `json:"item,omitempty" yaml:"item,omitempty"`
}

Piece is the occupant of a playable board cell.

func (Piece) Empty

func (p Piece) Empty() bool

Empty reports whether p represents an unoccupied cell.

type Point

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

Point identifies a cell by its zero-based column (X) and row (Y). Row 0 is the top edge; gravity pulls pieces toward increasing Y.

type PointDoc

type PointDoc struct {
	// X is the zero-based column coordinate.
	X int `yaml:"x" schema:"minimum=0"`
	// Y is the zero-based row coordinate.
	Y int `yaml:"y" schema:"minimum=0"`
}

PointDoc is a zero-based cell coordinate in YAML.

type Policy

type Policy func(b *Board, moves []Move, rng *random.Stream) (Move, bool)

Policy chooses one move from the board's ranked valid moves during Simulate.

type Resolution

type Resolution struct {
	// Valid is true when the swap was legal and produced matches or a special activation.
	Valid bool
	// A and B are the swapped cell coordinates.
	A Point
	B Point
	// Steps is the ordered list of cascade waves produced by the swap.
	Steps []Step
	// TotalScore is the sum of Score across all Steps.
	TotalScore int
}

Resolution is the complete deterministic outcome of one Board.Swap call.

type RuleSet

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

RuleSet holds game-registered rules for special creation, special triggers, special-swap combinations, and step scoring.

func DefaultRules

func DefaultRules() *RuleSet

DefaultRules returns a fresh RuleSet preloaded with standard match-3 rules:

  • ShapeLine4 -> SpecialLineH (horizontal) / SpecialLineV (vertical)
  • ShapeL and ShapeT -> SpecialArea (3x3 blast)
  • ShapeLine5 -> SpecialColor (color clear)
  • Combinations: line+line (cross), line+area (3-row+3-col cross), area+area (5x5), color+normal (color clear), color+line/area (activate special on every cell of that color), and color+color (full board wipe).

func NewRuleSet

func NewRuleSet() *RuleSet

NewRuleSet returns an empty RuleSet with only default scoring configured.

func (*RuleSet) Clone

func (r *RuleSet) Clone() *RuleSet

Clone returns an independent copy of r.

func (*RuleSet) RegisterCombo

func (r *RuleSet) RegisterCombo(a, b SpecialKind, rule ComboRule)

RegisterCombo registers the combination rule when swapping specials a and b (order-independent). Use SpecialNone for b to handle swapping a colorless special (such as SpecialColor) with a regular colored piece. Passing nil removes the combo rule.

func (*RuleSet) RegisterCreation

func (r *RuleSet) RegisterCreation(shape Shape, rule CreationRule)

RegisterCreation registers a rule that creates a special piece for shape. Passing nil removes the rule for shape.

func (*RuleSet) RegisterSpecial

func (r *RuleSet) RegisterSpecial(kind SpecialKind, rule TriggerRule)

RegisterSpecial registers the activation rule for special kind. Passing nil removes the rule for kind.

func (*RuleSet) SetScoring

func (r *RuleSet) SetScoring(fn ScoreFunc)

SetScoring sets the step scoring function. Passing nil restores DefaultScore.

type ScoreFunc

type ScoreFunc func(step Step) int

ScoreFunc computes the points awarded for one cascade step.

type Shape

type Shape string

Shape classifies a detected match group.

const (
	// ShapeLine3 is a straight run of 3 matching pieces.
	ShapeLine3 Shape = "line3"
	// ShapeLine4 is a straight run of 4 matching pieces.
	ShapeLine4 Shape = "line4"
	// ShapeLine5 is a straight run of 5 or more matching pieces (or a compound match containing one).
	ShapeLine5 Shape = "line5"
	// ShapeL is an intersecting horizontal and vertical run meeting at a corner endpoint of both runs.
	ShapeL Shape = "L"
	// ShapeT is an intersecting horizontal and vertical run meeting at a non-corner (T or + cross).
	ShapeT Shape = "T"
)

type SimOptions

type SimOptions struct {
	// Trials is the number of independent seeded runs to execute (default 1).
	Trials int
	// Seed is the base seed from which each trial derives a deterministic stream.
	Seed uint64
	// Policy selects each swap (default PolicyGoalFirst).
	Policy Policy
	// Rules optionally overrides [DefaultRules].
	Rules *RuleSet
	// MaxSwaps caps swaps per trial on time-only levels (default 500).
	MaxSwaps int
	// StepTime is the simulated time elapsed per swap on timed levels (default 2s).
	StepTime time.Duration
}

SimOptions configures headless level difficulty testing via Simulate.

type SimReport

type SimReport struct {
	Trials        int
	Wins          int
	Losses        int
	WinRate       float64
	MinMoves      int
	MaxMoves      int
	AvgMoves      float64
	MedianMoves   float64
	MinScore      int
	MaxScore      int
	AvgScore      float64
	AvgReshuffles float64
	AvgMaxCombo   float64
	Runs          []TrialResult
}

SimReport aggregates difficulty metrics across all trials of Simulate.

func Simulate

func Simulate(level Level, opts SimOptions) (SimReport, error)

Simulate runs deterministic headless playthroughs of level to measure win rate, move distribution, reshuffle frequency, and score spread for level tuning and playtest difficulty checks.

type Snapshot

type Snapshot struct {
	// Version must equal SnapshotVersion.
	Version int `json:"version" yaml:"version"`
	// Width and Height must match the target Board's dimensions.
	Width  int `json:"width" yaml:"width"`
	Height int `json:"height" yaml:"height"`
	// Cells holds all Width*Height cells in row-major order.
	Cells []Cell `json:"cells" yaml:"cells"`
	// Score is the cumulative score.
	Score int `json:"score" yaml:"score"`
	// MovesLeft is the remaining swap budget.
	MovesLeft int `json:"movesLeft" yaml:"movesLeft"`
	// TimeLeft is the remaining time budget on timed levels.
	TimeLeft time.Duration `json:"timeLeft,omitempty" yaml:"timeLeft,omitempty"`
	// MaxCombo is the highest cascade combo depth reached.
	MaxCombo int `json:"maxCombo,omitempty" yaml:"maxCombo,omitempty"`
	// TotalMatches is the total number of match groups cleared.
	TotalMatches int `json:"totalMatches,omitempty" yaml:"totalMatches,omitempty"`
	// TotalSwaps is the total number of completed swaps.
	TotalSwaps int `json:"totalSwaps,omitempty" yaml:"totalSwaps,omitempty"`
	// Reshuffles is the number of deadlock reshuffles performed.
	Reshuffles int `json:"reshuffles,omitempty" yaml:"reshuffles,omitempty"`
	// Collected maps 1-based color IDs to cleared piece counts.
	Collected map[int]int `json:"collected,omitempty" yaml:"collected,omitempty"`
	// BlockersCleared maps blocker kinds to destroyed counts.
	BlockersCleared map[BlockerKind]int `json:"blockersCleared,omitempty" yaml:"blockersCleared,omitempty"`
	// ItemsCollected is the number of bring-down items delivered to exits.
	ItemsCollected int `json:"itemsCollected,omitempty" yaml:"itemsCollected,omitempty"`
	// RNG captures the exact random.Stream state.
	RNG random.State `json:"rng" yaml:"rng"`
}

Snapshot is a JSON- and YAML-serializable point-in-time capture of a Board, including its RNG stream state so restoring resumes bit-identical cascades.

type SolveOptions

type SolveOptions struct {
	// MaxStates caps distinct board states explored (default 10,000).
	MaxStates int
	// MaxDepth caps swap depth explored (default b.MovesLeft() when > 0, else 25).
	MaxDepth int
	// BeamWidth optionally keeps only the top BeamWidth states per depth ranked by
	// goal progress and score. When 0, Solve performs exact breadth-first search.
	BeamWidth int
	// StepTime is applied via AdvanceTime after each swap on timed levels.
	StepTime time.Duration
}

SolveOptions bounds headless search in Solve.

type SolveResult

type SolveResult struct {
	// Solved is true when a winning swap sequence was found within the search budget.
	Solved bool
	// Moves is the sequence of swaps that wins the board.
	Moves []Move
	// FinalScore is the board score after executing Moves.
	FinalScore int
	// StatesExplored is the number of distinct states visited.
	StatesExplored int
	// HitLimit is true when search terminated early due to MaxStates.
	HitLimit bool
}

SolveResult reports the outcome of Solve.

func Solve

func Solve(b *Board, opts SolveOptions) SolveResult

Solve searches deterministically from a snapshot of b (leaving b unchanged) for a sequence of swaps that satisfies every level goal. When opts.BeamWidth is 0, Solve runs breadth-first search and returns a shortest winning swap sequence.

type Spawn

type Spawn struct {
	// From is the virtual starting coordinate above the spawner (Y < spawner row) for smooth drop-in animation.
	From Point
	// To is the landing board coordinate.
	To Point
	// Column is the spawner column index that produced the piece.
	Column int
	// Piece is the spawned piece.
	Piece Piece
}

Spawn records a newly generated piece entering from a column spawner.

type SpawnerDoc

type SpawnerDoc struct {
	// Column is the zero-based column index.
	Column int `yaml:"column" schema:"minimum=0"`
	// Row is the zero-based row at which pieces enter (default 0).
	Row int `yaml:"row,omitempty" schema:"minimum=0"`
	// Disabled stops this column from spawning new pieces when true.
	Disabled bool `yaml:"disabled,omitempty"`
	// Weights optionally assigns positive integer spawn weights per color name.
	// When omitted, all colors spawn with equal weight.
	Weights map[string]int `yaml:"weights,omitempty"`
}

SpawnerDoc configures how pieces spawn in one column.

type SpecialKind

type SpecialKind string

SpecialKind identifies a special piece's activation behavior.

const (
	// SpecialNone indicates a regular non-special piece.
	SpecialNone SpecialKind = ""
	// SpecialLineH clears every playable cell in the piece's row.
	SpecialLineH SpecialKind = "line_h"
	// SpecialLineV clears every playable cell in the piece's column.
	SpecialLineV SpecialKind = "line_v"
	// SpecialArea clears the 3x3 area centered on the piece.
	SpecialArea SpecialKind = "area"
	// SpecialColor clears every piece matching the target color (colorless special).
	SpecialColor SpecialKind = "color"
)

type Step

type Step struct {
	// Combo is the 1-based cascade depth (1 for the initial swap, 2 for the first refill cascade, ...).
	Combo int
	// Matches lists all match groups detected in this step.
	Matches []Match
	// SpecialsCreated lists special pieces spawned by matches in this step.
	SpecialsCreated []CreatedSpecial
	// SpecialsTriggered lists specials and special combinations activated in this step, in trigger order.
	SpecialsTriggered []TriggeredSpecial
	// Cleared lists all pieces removed in this step, sorted by Y then X.
	Cleared []ClearedCell
	// BlockerDamage lists all blocker and jelly hits in this step, sorted by Y, X, Kind.
	BlockerDamage []BlockerHit
	// ItemsCollected lists bring-down items collected at exit cells during this step.
	ItemsCollected []Point
	// Falls lists existing pieces displaced by gravity in this step.
	Falls []Fall
	// Spawns lists newly generated pieces entering the board in this step.
	Spawns []Spawn
	// Score is the total points awarded for this step (including the Combo multiplier).
	Score int
}

Step is one cascade wave within a Resolution.

type TrialResult

type TrialResult struct {
	Seed         uint64
	Won          bool
	Moves        int
	Score        int
	MaxCombo     int
	Reshuffles   int
	GoalProgress float64
}

TrialResult records the outcome of one simulated playthrough.

type TriggerContext

type TriggerContext struct {
	Board       *Board
	Origin      Point
	Piece       Piece
	TargetColor int
}

TriggerContext provides read-only board context to a TriggerRule.

type TriggerRule

type TriggerRule func(ctx TriggerContext) []Point

TriggerRule returns the cells affected when a special piece activates.

type TriggeredSpecial

type TriggeredSpecial struct {
	// Origin is the cell from which the special triggered.
	Origin Point
	// Kind is the activated special kind.
	Kind SpecialKind
	// Partner is non-empty when this trigger was a swap combination with another special.
	Partner SpecialKind
	// TargetColor is the target color cleared (used by SpecialColor activations).
	TargetColor int
	// Cells lists the unique playable cells targeted by this activation, sorted by Y then X.
	Cells []Point
}

TriggeredSpecial records one special activation or special-swap combination.

Jump to

Keyboard shortcuts

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