Documentation
¶
Overview ¶
Package mergegame is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package mergegame holds the data and rules of a merge game: chains of tiers that two equal items merge up, generators that spend energy and charges to drop weighted items, orders that pay coins and XP for items, and a board of cells with locked regions, sell and undo, which saves to YAML after every move.
The chain, generator, order and board documents are versioned YAML that refuses unknown fields and saves the same bytes for the same value; docs/en/formats.md describes each one.
Example ¶
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/mergegame"
)
func main() {
doc, err := mergegame.Parse([]byte(`version: 1
chains:
- id: tools
tiers:
- {id: pebble, value: 1}
- {id: axe, value: 4}
- id: plants
tiers:
- {id: seed, value: 1}
- {id: sprout, value: 3}
- {id: tree, value: 10}
`))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(doc.ChainIDs(), doc.SortedChainIDs())
// Merging two items of a tier yields the next tier, until the chain's last one.
tier := "seed"
for {
next, ok := doc.Next("plants", tier)
if !ok {
fmt.Println(tier, "is the top tier")
break
}
fmt.Printf("%s -> %s (value %d)\n", tier, next.ID, next.Value)
tier = next.ID
}
}
Output: [tools plants] [plants tools] seed -> sprout (value 3) sprout -> tree (value 10) tree is the top tier
Index ¶
- Constants
- Variables
- func Encode(d Document) ([]byte, error)
- func EncodeBoard(s BoardState) ([]byte, error)
- func EncodeGenerators(g Generators) ([]byte, error)
- func EncodeOrders(o Orders) ([]byte, error)
- type Board
- func (b *Board) At(c Cell) Item
- func (b *Board) CanFill(o Order) bool
- func (b *Board) Contains(c Cell) bool
- func (b *Board) Count(it Item) int
- func (b *Board) Fill(o Order) ([]Cell, error)
- func (b *Board) FreeCellNear(c Cell) (Cell, bool)
- func (b *Board) Height() int
- func (b *Board) IsLocked(c Cell) bool
- func (b *Board) LastSale() (Sale, bool)
- func (b *Board) Lock(c Cell) error
- func (b *Board) Move(chains Document, from, to Cell) (Move, error)
- func (b *Board) Place(c Cell, it Item) error
- func (b *Board) Remove(c Cell) (Item, error)
- func (b *Board) Sell(chains Document, c Cell) (Sale, error)
- func (b *Board) State() BoardState
- func (b *Board) Tap(at Cell, gen Generator, energy, charges *idle.Meter, rng *random.Stream, ...) (Cell, Item, error)
- func (b *Board) UndoSell() (Sale, error)
- func (b *Board) Unlock(c Cell) error
- func (b *Board) Width() int
- type BoardState
- type Cell
- type Chain
- type Document
- type Generator
- type Generators
- type Item
- type Move
- type MoveKind
- type Order
- type Orders
- type Output
- type Placed
- type Request
- type Sale
- type Tier
Examples ¶
Constants ¶
const BoardVersion = 1
BoardVersion is the current board state YAML schema version.
const FormatVersion = 1
FormatVersion is the current merge-chain YAML schema version.
const GeneratorsSchemaComment = "# yaml-language-server: $schema=" + GeneratorsSchemaURL
GeneratorsSchemaComment is the first line EncodeGenerators writes, which points YAML editors at GeneratorsSchemaURL.
const GeneratorsSchemaURL = "https://nsgo.games/schemas/mergegenerators.v1.json"
GeneratorsSchemaURL is where the JSON Schema of version 1 generators files is published.
const GeneratorsVersion = 1
GeneratorsVersion is the current generators YAML schema version.
const MaxBoardSide = 64
MaxBoardSide is the largest width or height of a Board.
const OrdersSchemaComment = "# yaml-language-server: $schema=" + OrdersSchemaURL
OrdersSchemaComment is the first line EncodeOrders writes, which points YAML editors at OrdersSchemaURL.
const OrdersSchemaURL = "https://nsgo.games/schemas/mergeorders.v1.json"
OrdersSchemaURL is where the JSON Schema of version 1 orders files is published.
const OrdersVersion = 1
OrdersVersion is the current orders YAML schema version.
const SchemaComment = "# yaml-language-server: $schema=" + SchemaURL
SchemaComment is the first line Encode writes, which points YAML editors at SchemaURL.
const SchemaURL = "https://nsgo.games/schemas/mergechains.v1.json"
SchemaURL is where the JSON Schema of version 1 merge-chain files is published.
Variables ¶
var ( // ErrOutside reports a cell outside the board. ErrOutside = errors.New("mergegame: cell outside the board") // ErrLocked reports a locked cell where the action needs an unlocked one. ErrLocked = errors.New("mergegame: cell is locked") // ErrEmpty reports an empty cell where the action needs an item. ErrEmpty = errors.New("mergegame: cell is empty") // ErrOccupied reports a cell that holds an item where the action needs an empty one. ErrOccupied = errors.New("mergegame: cell is occupied") // ErrBoardFull reports that no unlocked cell is free for a new item. ErrBoardFull = errors.New("mergegame: board is full") // ErrUnknownItem reports an item that is not a tier of the chains. ErrUnknownItem = errors.New("mergegame: item is not in the chains") // ErrNotGenerator reports a tap on a cell that does not hold the generator's item. ErrNotGenerator = errors.New("mergegame: cell does not hold the generator") // ErrNoEnergy reports a tap the player's energy cannot pay for. ErrNoEnergy = errors.New("mergegame: not enough energy") // ErrNoCharge reports a tap on a generator whose charges are spent. ErrNoCharge = errors.New("mergegame: generator is recharging") // ErrMissingItems reports an order the board does not hold every item of. ErrMissingItems = errors.New("mergegame: board lacks the order's items") // ErrNoSale reports an undo with no sale to undo. ErrNoSale = errors.New("mergegame: no sale to undo") )
Errors that Board methods return, wrapped with the cell or item at fault.
Functions ¶
func Encode ¶
Encode validates d and writes its deterministic YAML representation after SchemaComment.
func EncodeBoard ¶
func EncodeBoard(s BoardState) ([]byte, error)
EncodeBoard validates s and writes its YAML representation. Lists keep their order, so encode what Board.State returns to save the same bytes for the same board.
func EncodeGenerators ¶
func EncodeGenerators(g Generators) ([]byte, error)
EncodeGenerators validates g and writes its deterministic YAML representation after GeneratorsSchemaComment.
func EncodeOrders ¶
EncodeOrders validates o and writes its deterministic YAML representation after OrdersSchemaComment.
Types ¶
type Board ¶
type Board struct {
// contains filtered or unexported fields
}
Board is a grid of cells that each hold at most one item, some of them locked until the game opens them, and the last sale, which Board.UndoSell takes back. The zero Board has no cells; make one with NewBoard or RestoreBoard.
func NewBoard ¶
NewBoard returns an empty board of width by height unlocked cells, each from 1 to MaxBoardSide.
func RestoreBoard ¶
func RestoreBoard(s BoardState) (*Board, error)
RestoreBoard returns the board s describes. It does not check that the items exist; see BoardState.Check.
func (*Board) Fill ¶
Fill takes the items order o asks for off the board, choosing cells row by row from the top left, and returns the cells it emptied. When the board lacks any of them it changes nothing and returns an error wrapping ErrMissingItems. The caller pays o.Coins and o.XP.
func (*Board) FreeCellNear ¶
FreeCellNear returns the empty unlocked cell closest to c, by straight-line distance and then by row and column, so the same board always gives the same cell. It reports false when the board has no free cell. c may lie outside the board.
func (*Board) LastSale ¶
LastSale returns the sale Board.UndoSell would take back. It reports false when there is none.
func (*Board) Lock ¶
Lock locks the empty cell c, so no item can enter it until Board.Unlock.
func (*Board) Move ¶
Move drags the item on from onto to, as the player does: onto an empty cell it moves, onto an equal item below its chain's last tier the two merge into the next tier on to, and onto any other item the two swap. Neither cell may be locked, and from must hold an item that is a tier of chains.
Example ¶
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/mergegame"
)
func main() {
chains, _ := mergegame.Parse([]byte(`version: 1
chains:
- id: plants
tiers:
- {id: seed, value: 1}
- {id: sprout, value: 3}
`))
seed := mergegame.Item{Chain: "plants", Tier: "seed"}
board, _ := mergegame.NewBoard(3, 1)
_ = board.Place(mergegame.Cell{X: 0, Y: 0}, seed)
_ = board.Place(mergegame.Cell{X: 2, Y: 0}, seed)
// Dragging one seed onto the other merges them into a sprout.
move, _ := board.Move(chains, mergegame.Cell{X: 0, Y: 0}, mergegame.Cell{X: 2, Y: 0})
fmt.Println(move.Kind, move.Item)
sale, _ := board.Sell(chains, mergegame.Cell{X: 2, Y: 0})
fmt.Println("sold for", sale.Value)
back, _ := board.UndoSell()
fmt.Println("back on", back.Cell)
// Save the board after every move.
data, _ := mergegame.EncodeBoard(board.State())
fmt.Print(string(data))
}
Output: merged plants/sprout sold for 3 back on (2,0) version: 1 width: 3 height: 1 items: - x: 2 "y": 0 chain: plants tier: sprout
func (*Board) Sell ¶
Sell removes the item on c and returns the sale, whose Value is the item's tier value in chains. The sale replaces the previous one as what Board.UndoSell takes back.
func (*Board) Tap ¶
func (b *Board) Tap(at Cell, gen Generator, energy, charges *idle.Meter, rng *random.Stream, now time.Time) (Cell, Item, error)
Tap taps the generator gen on cell at at time now: it spends gen.Energy from energy and one charge from charges, picks one of gen's outputs by weight with rng, and places it on the free cell nearest to at, which it returns with the item. It spends nothing and returns an error wrapping ErrNotGenerator, ErrBoardFull, ErrNoEnergy or ErrNoCharge when the tap cannot happen. energy may be nil when gen.Energy is 0; charges is the generator's meter, as Generator.Meter makes it.
func (*Board) UndoSell ¶
UndoSell puts the last sold item back, on its cell when that is still free and otherwise on the free cell nearest to it, and returns the sale with the cell it went to; the caller takes back the sale's Value. Only the last sale can be undone, once.
type BoardState ¶
type BoardState struct {
// Version is the format version and must be BoardVersion.
Version int `yaml:"version"`
// Width is the number of columns, from 1 to MaxBoardSide.
Width int `yaml:"width"`
// Height is the number of rows, from 1 to MaxBoardSide.
Height int `yaml:"height"`
// Locked lists the locked cells, each once, none of them holding an item.
Locked []Cell `yaml:"locked,omitempty"`
// Items lists the cells that hold an item, each once.
Items []Placed `yaml:"items,omitempty"`
// Sale is the last sale, which an undo takes back, or nil when there is none.
Sale *Sale `yaml:"sale,omitempty"`
}
BoardState is a Board in the versioned form a game saves after every move, in a save slot or a file of its own. Board.State writes its lists row by row from the top left, so the same board always saves the same bytes.
func ParseBoard ¶
func ParseBoard(data []byte) (BoardState, error)
ParseBoard decodes and validates one board state YAML document. Its errors are *loaderr.Error values naming the field at fault.
func (BoardState) Check ¶
func (s BoardState) Check(chains Document) error
Check reports the first item or sale of s that is not a tier of chains, as a *loaderr.Error naming its field.
func (BoardState) Validate ¶
func (s BoardState) Validate() error
Validate reports whether s has a supported version, a valid size, and cells on the board that are each locked or filled at most once, never both.
type Chain ¶
type Chain struct {
// ID is the chain's non-empty identifier without surrounding spaces, unique within the document.
ID string `yaml:"id" schema:"required,minLength=1"`
// Tiers lists at least two tiers from lowest to highest, each with an ID unique within the chain.
Tiers []Tier `yaml:"tiers" schema:"required,minItems=2"`
}
Chain describes the ordered tiers in one progression path.
type Document ¶
type Document struct {
// Version is the format version and must be FormatVersion.
Version int `yaml:"version" schema:"required,const=1"`
// Chains lists at least one chain, each with a unique ID.
Chains []Chain `yaml:"chains" schema:"required,minItems=1"`
}
Document is a versioned collection of merge chains.
func Parse ¶
Parse decodes and validates one canonical merge-chain YAML document. Its errors are *loaderr.Error values naming the field at fault.
func (Document) Next ¶
Next returns the tier immediately after tierID in chainID. It reports false when the tier is the chain's final tier or either ID is unknown.
func (Document) SortedChainIDs ¶
SortedChainIDs returns a stable alphabetical copy of chain IDs.
func (Document) Tier ¶
Tier returns the tier tierID of chainID. It reports false when either ID is unknown.
func (Document) Validate ¶
Validate reports whether d has a supported version and unique valid chains and tiers.
Example ¶
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/mergegame"
)
func main() {
doc := mergegame.Document{Version: 1, Chains: []mergegame.Chain{{ID: "gems", Tiers: []mergegame.Tier{{ID: "shard", Value: 2}}}}}
fmt.Println(doc.Validate())
}
Output: chains[0].tiers: mergegame: chain "gems" needs at least two tiers; fix: list at least two tiers
type Generator ¶
type Generator struct {
// Item is the board item that acts as this generator.
Item Item `yaml:",inline"`
// Energy is how much of the player's energy one tap spends, 0 or more.
Energy int `yaml:"energy" schema:"required,minimum=0"`
// Charges is how many taps the generator holds when full, at least 1.
Charges int `yaml:"charges" schema:"required,minimum=1"`
// Recharge is how long the generator takes to regain one charge, positive and a whole number of seconds; it keeps running while the game is closed.
Recharge time.Duration `yaml:"recharge" schema:"required"`
// Outputs lists at least one item the generator may drop, each with a positive weight and a different item.
Outputs []Output `yaml:"outputs" schema:"required,minItems=1"`
}
Generator is a board item that, when tapped, spends energy and one of its charges to drop one item picked by weight from its outputs.
type Generators ¶
type Generators struct {
// Version is the format version and must be GeneratorsVersion.
Version int `yaml:"version" schema:"required,const=1"`
// Generators lists at least one generator, each for a different item.
Generators []Generator `yaml:"generators" schema:"required,minItems=1"`
}
Generators is a versioned list of the board items that produce other items when tapped, as a game's data/generators.yaml holds it.
func ParseGenerators ¶
func ParseGenerators(data []byte) (Generators, error)
ParseGenerators decodes and validates one canonical generators YAML document. Its errors are *loaderr.Error values naming the field at fault. It does not check that the items exist; see Generators.Check.
func (Generators) Check ¶
func (g Generators) Check(chains Document) error
Check reports the first generator or output of g whose item is not a tier of chains, as a *loaderr.Error naming its field.
func (Generators) Generator ¶
func (g Generators) Generator(it Item) (Generator, bool)
Generator returns the generator whose item is it. It reports false when it is not a generator.
func (Generators) Validate ¶
func (g Generators) Validate() error
Validate reports whether g has a supported version and well-formed generators, each for a different item.
type Item ¶
type Item struct {
// Chain is the ID of the item's chain.
Chain string `yaml:"chain" schema:"required,minLength=1"`
// Tier is the ID of the item's tier in Chain.
Tier string `yaml:"tier" schema:"required,minLength=1"`
}
Item is one board item: a tier of a chain. The zero Item is an empty cell.
type Move ¶
type Move struct {
// Kind is what the move did.
Kind MoveKind
// Item is the item on the target cell afterwards: the merged tier after a merge.
Item Item
}
Move is the result of a Board.Move.
type Order ¶
type Order struct {
// ID is the order's non-empty identifier without surrounding spaces, unique within the document.
ID string `yaml:"id" schema:"required,minLength=1"`
// Level is the player level from which the order is offered, at least 1.
Level int `yaml:"level" schema:"required,minimum=1"`
// Items lists at least one request, each for a different item.
Items []Request `yaml:"items" schema:"required,minItems=1"`
// Coins is what filling the order pays, 0 or more.
Coins int `yaml:"coins" schema:"required,minimum=0"`
// XP is the experience filling the order grants, 0 or more.
XP int `yaml:"xp" schema:"required,minimum=0"`
}
Order asks for items and pays coins and XP once the board holds them all.
type Orders ¶
type Orders struct {
// Version is the format version and must be OrdersVersion.
Version int `yaml:"version" schema:"required,const=1"`
// Orders lists at least one order, each with a unique ID.
Orders []Order `yaml:"orders" schema:"required,minItems=1"`
}
Orders is a versioned list of the requests a player fills with board items, as a game's data/orders.yaml holds it.
func ParseOrders ¶
ParseOrders decodes and validates one canonical orders YAML document. Its errors are *loaderr.Error values naming the field at fault. It does not check that the items exist; see Orders.Check.
func (Orders) Check ¶
Check reports the first request of o whose item is not a tier of chains, as a *loaderr.Error naming its field.
type Output ¶
type Output struct {
// Item is the dropped item.
Item Item `yaml:",inline"`
// Weight is the output's relative chance, at least 1.
Weight int `yaml:"weight" schema:"required,minimum=1"`
}
Output is one item a generator may drop and its weight relative to the generator's other outputs.
type Placed ¶
type Placed struct {
// Cell is where the item is.
Cell Cell `yaml:",inline"`
// Item is the item.
Item Item `yaml:",inline"`
}
Placed is an item on a cell.
type Request ¶
type Request struct {
// Item is the requested item.
Item Item `yaml:",inline"`
// Count is how many of the item the order takes, at least 1.
Count int `yaml:"count" schema:"required,minimum=1"`
}
Request is one item an order asks for and how many of it.
type Sale ¶
type Sale struct {
// Cell is where the item was.
Cell Cell `yaml:",inline"`
// Item is the sold item.
Item Item `yaml:",inline"`
// Value is what the sale paid, the tier's value, which an undo takes back.
Value int `yaml:"value"`
}
Sale is an item the player sold, where it was and what it paid.
type Tier ¶
type Tier struct {
// ID is the tier's non-empty identifier without surrounding spaces.
ID string `yaml:"id" schema:"required,minLength=1"`
// Value is the tier's non-negative sell value.
Value int `yaml:"value" schema:"required,minimum=0"`
}
Tier is one merge progression level and its value.