deck

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: 9 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 deck is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package deck provides deterministic draw, hand, discard, and exhaust piles.

Example
package main

import (
	"fmt"
	"slices"

	"github.com/nsgo-dev/game/pkg/cards/deck"
)

func ids(cards []deck.Card) []string {
	out := make([]string, len(cards))
	for i, c := range cards {
		out[i] = c.ID
	}
	slices.Sort(out)
	return out
}

func main() {
	cards := []deck.Card{
		{ID: "strike", Cost: 1},
		{ID: "defend", Cost: 1},
		{ID: "bash", Cost: 2},
		{ID: "ghost", Keywords: map[string]bool{"ethereal": true}},
		{ID: "plan", Keywords: map[string]bool{"retain": true}},
	}
	// The same seed always shuffles the same way; the IDs are sorted here so the output does not depend on the shuffle.
	d := deck.New(cards, 42, 10)
	fmt.Println("drawn:", ids(d.Draw(5)))

	// Play two cards: one goes to the discard pile, the other leaves the deck for good.
	if err := d.Discard("strike"); err != nil {
		fmt.Println(err)
	}
	if err := d.Exhaust("bash"); err != nil {
		fmt.Println(err)
	}
	fmt.Println(d.Exhaust("bash"))

	// At the end of the turn the retained card stays, the ethereal one is exhausted and the rest are discarded.
	d.EndTurn()
	draw, discard, exhaust := d.Piles()
	fmt.Println("hand:", ids(d.Hand()))
	fmt.Println("draw:", len(draw), "discard:", ids(discard), "exhaust:", ids(exhaust))

	// An empty draw pile is refilled from the discard pile.
	fmt.Println("redrawn:", ids(d.Draw(5)))
	fmt.Println("hand size:", len(d.Hand()))
}
Output:
drawn: [bash defend ghost plan strike]
deck: card "bash" is not in hand
hand: [plan]
draw: 0 discard: [defend strike] exhaust: [bash ghost]
redrawn: [defend strike]
hand size: 3

Index

Examples

Constants

View Source
const CardSetFormatVersion = 1

CardSetFormatVersion is the version of the card-set YAML schema.

View Source
const CardSetSchemaComment = "# yaml-language-server: $schema=" + CardSetSchemaURL

CardSetSchemaComment is the first line EncodeCardSet writes so YAML language servers validate and complete card-set files automatically.

View Source
const CardSetSchemaURL = "https://nsgo.games/schemas/cardset.v1.json"

CardSetSchemaURL is where the JSON Schema of version 1 card-set files is published.

View Source
const SnapshotVersion = 1

SnapshotVersion is the version of DeckSnapshot, an in-memory value a game stores inside its own save slot rather than a standalone file format.

Variables

View Source
var ErrEmpty = errors.New("deck: no cards available")

ErrEmpty reports that neither the draw pile nor the discard pile has a card left. Draw does not return it: it returns fewer cards than asked for instead.

View Source
var ErrInvalidSnapshot = errors.New("cards/deck: invalid snapshot")

ErrInvalidSnapshot is the error Restore wraps when it refuses a snapshot, leaving the deck unchanged.

Functions

func EncodeCardSet

func EncodeCardSet(set *CardSet) ([]byte, error)

EncodeCardSet validates and writes a card-set in deterministic YAML, with a yaml-language-server schema comment on the first line.

func Operations

func Operations() []string

Operations returns the effect operations a card set may name.

func Targets

func Targets() []string

Targets returns the values Definition.Target accepts besides empty.

Types

type Card

type Card struct {
	ID       string
	Cost     int
	Keywords map[string]bool
}

Card identifies a card in a deck.

type CardSet

type CardSet struct {
	// Version is the card-set format version; only 1 is supported.
	Version int `yaml:"version"`
	// Cards are the card definitions, each with an id unique in the set.
	Cards []Definition `yaml:"cards"`
}

CardSet is a versioned collection of card definitions.

func ParseCardSet

func ParseCardSet(data []byte) (*CardSet, error)

ParseCardSet decodes and validates one card-set YAML document. Unknown fields, operations, versions and trailing documents are refused.

func (*CardSet) Validate

func (set *CardSet) Validate() error

Validate checks schema values, registered operations and that every upgrade names a card in the set.

type Deck

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

Deck manages deterministic draw and discard piles.

func New

func New(cards []Card, seed uint64, handLimit int) *Deck

New creates a deck from cards.

func (*Deck) Discard

func (d *Deck) Discard(id string) error

Discard moves the first card in hand with id to the discard pile.

func (*Deck) Draw

func (d *Deck) Draw(n int) []Card

Draw draws cards from the deck.

func (*Deck) EndTurn

func (d *Deck) EndTurn()

EndTurn applies end-of-turn pile transitions.

func (*Deck) Energy

func (d *Deck) Energy() int

Energy reports the energy available for the current turn.

func (*Deck) Exhaust

func (d *Deck) Exhaust(id string) error

Exhaust moves the first card in hand with id to the exhaust pile, out of future draws.

func (*Deck) Hand

func (d *Deck) Hand() []Card

Hand returns a copy of the cards currently held.

func (*Deck) Piles

func (d *Deck) Piles() (draw, discard, exhaust []Card)

Piles returns copies of the draw, discard, and exhaust piles.

func (*Deck) Play

func (d *Deck) Play(id string) error

Play removes a card from the hand and applies its keyword move. Once SetEnergy or StartTurn has turned energy on, Play pays the card's cost and refuses a card that costs more than the energy left, including any costed card on a zero-energy turn.

func (*Deck) Restore

func (d *Deck) Restore(s DeckSnapshot) error

Restore validates and atomically replaces the deck state.

func (*Deck) SetEnergy

func (d *Deck) SetEnergy(energy int)

SetEnergy turns energy on and sets the energy available for the current turn; a negative value counts as 0. A deck whose energy was never set, by SetEnergy or StartTurn, plays every card for free, so the pile-only API stays unrestricted for callers that do not use turns.

func (*Deck) Snapshot

func (d *Deck) Snapshot() DeckSnapshot

Snapshot returns a deep copy of the current deck state.

func (*Deck) StartTurn

func (d *Deck) StartTurn(energy, draw int) []Card

StartTurn draws cards for the turn after refreshing energy to energy, which turns energy on as SetEnergy does; a negative energy leaves energy as it is.

type DeckSnapshot

type DeckSnapshot struct {
	Version   int
	Draw      []Card
	Hand      []Card
	Discard   []Card
	Exhaust   []Card
	Limit     int
	Energy    int
	MaxEnergy int
	// EnergyOn reports whether SetEnergy or StartTurn had turned energy on, so Play charges card costs after Restore.
	EnergyOn bool
	Random   random.State
}

DeckSnapshot is a serializable mid-turn deck state.

type Definition

type Definition struct {
	// ID identifies the card, unique within the set; upgrade and the game's decks name cards by it.
	ID string `yaml:"id"`
	// Name is the card's display name or the localization key of it, such as card.strike.
	Name string `yaml:"name"`
	// Cost is the energy Deck.Play pays for the card once energy is on; 0 or more.
	Cost int `yaml:"cost"`
	// Type is the game's card type, such as attack, skill or power.
	Type string `yaml:"type"`
	// Rarity is the game's rarity tier, such as common, uncommon or rare.
	Rarity string `yaml:"rarity"`
	// Target is who the card's effects aim at: self, one_enemy, all_enemies or random; empty leaves it to the game.
	Target string `yaml:"target"`
	// Keywords are the card's keywords, such as exhaust, retain or ethereal.
	Keywords []string `yaml:"keywords,omitempty"`
	// Upgrade is the id of the card in the same set this card becomes when upgraded.
	Upgrade string `yaml:"upgrade,omitempty"`
	// Effects are the operations playing the card performs, in order.
	Effects []Effect `yaml:"effects,omitempty"`
}

Definition describes a card independently of a running deck.

type Effect

type Effect struct {
	// Op is the operation: damage, block, draw or apply.
	Op string `yaml:"op"`
	// Args are the operation's named arguments, such as amount, which the game's handler reads.
	Args map[string]any `yaml:"args,omitempty"`
}

Effect is a registered card operation and its named arguments.

Jump to

Keyboard shortcuts

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