La référence API provient des commentaires de documentation Go du code source et est rédigée en anglais.
package cards
import "github.com/nsgo-dev/game/pkg/cards"Vue d’ensemble
Package cards drags cards between the slots of a board in the game view and lays them out as fanned hands, decks, piles and grids, animating every move with game/tween on game.Loop's fixed steps.
A Board holds Slots in the order they were added; each Slot owns an ordered list of Cards and arranges them with its Layout (Fan, Stack or Grid, or your own). Pointers drive drags: a card picked up under a mouse button or a finger follows it past a small slop, and on release it snaps into the slot under it when that slot accepts it (its tags, capacity, Accept predicates and the board's Accept), or tweens back to where it came from when it does not. NSGo reports the primary mouse button as finger 0 of core.TouchEvent on the desktops and every pointer as a finger on the web, so Board.OnTouch (or Board.Attach on the view holding the game's Canvas) handles mouse and touch alike, and several fingers drag several cards at once.
Boards can be written as versioned YAML (BoardDoc) with ParseBoardDoc and EncodeBoardDoc and built with LoadBoard. Nothing in the package reads the wall clock, starts goroutines or keeps package-level state: animations advance only in Board.Update, so a board replays identically under nsgotest.
Index
- Constantes
- Variables
- func EncodeBoardDoc(doc *BoardDoc) ([]byte, error)
- type Board
- func LoadBoard(doc *BoardDoc) (*Board, error)
- func (b *Board) Add(c *Card, s *Slot, index int) error
- func (b *Board) AddSlot(s *Slot) error
- func (b *Board) Attach(v *core.View)
- func (b *Board) CanDrop(c *Card, to *Slot) bool
- func (b *Board) CardAt(p math2d.Vec2) *Card
- func (b *Board) Doc() (*BoardDoc, error)
- func (b *Board) DrawOrder(dst []*Card) []*Card
- func (b *Board) DropTarget(c *Card) (*Slot, bool)
- func (b *Board) Move(c *Card, to *Slot, index int) error
- func (b *Board) OnTouch(ev core.TouchEvent)
- func (b *Board) PointerCancel(id int)
- func (b *Board) PointerDown(id int, p math2d.Vec2) bool
- func (b *Board) PointerMove(id int, p math2d.Vec2)
- func (b *Board) PointerUp(id int, p math2d.Vec2)
- func (b *Board) Relayout(s *Slot)
- func (b *Board) Remove(c *Card) error
- func (b *Board) Settle()
- func (b *Board) Size() math2d.Vec2
- func (b *Board) Slot(id string) *Slot
- func (b *Board) SlotAt(p math2d.Vec2) *Slot
- func (b *Board) Slots() []*Slot
- func (b *Board) Update(dt time.Duration)
- type BoardDoc
- type Card
- type DropEvent
- type Fan
- type FanDoc
- type GrabRule
- type Grid
- type GridDoc
- type Layout
- type LayoutDoc
- type Pose
- type RectDoc
- type ReturnEvent
- type SizeDoc
- type Slot
- type SlotDoc
- type Stack
- type StackDoc
- type VecDoc
Constantes
const (
// DefaultDragSlop is how far, in points, a pointer moves from where it pressed a card before the card starts to follow it.
DefaultDragSlop float32 = 6
// DefaultSnapDuration is how long a card takes to settle into its place after a valid drop or a layout change.
DefaultSnapDuration = 180 * time.Millisecond
// DefaultReturnDuration is how long a card rejected by a drop takes to fly back to its slot.
DefaultReturnDuration = 240 * time.Millisecond
)Defaults a Board uses for its zero fields.
const FormatVersion = 1FormatVersion is the BoardDoc schema version this package reads and writes.
Variables
var (
// ErrSlotID reports a slot with an empty ID or one the board already holds.
ErrSlotID = errors.New("cards: slot ID is empty or already on the board")
// ErrSlotOwned reports a slot that already belongs to a board, or that does not belong to this one.
ErrSlotOwned = errors.New("cards: slot belongs to another board")
// ErrCardOwned reports adding a card that is already on a board.
ErrCardOwned = errors.New("cards: card is already on a board")
// ErrNoCard reports a card that is not on this board.
ErrNoCard = errors.New("cards: card is not on this board")
)Errors returned by Board's methods.
var DefaultCardSize = math2d.Vec2{X: 63, Y: 88}DefaultCardSize is a poker card's 63×88 aspect at one point per millimeter, used while Board.CardSize is zero.
var ErrCustomLayout = errors.New("cards: a custom layout cannot be written to a BoardDoc")ErrCustomLayout reports encoding a slot whose Layout is not a Fan, Stack or Grid.
Fonctions
func EncodeBoardDoc(doc *BoardDoc) ([]byte, error)EncodeBoardDoc validates doc and writes it as 2-space YAML with its fields in a fixed order.
Types
type Board struct {
// CardSize is every card's width and height in board coordinates; zero uses DefaultCardSize.
CardSize math2d.Vec2
// DragSlop is how far a pointer moves from its press before the card follows it; 0 uses DefaultDragSlop and a negative value starts the drag on the first move.
DragSlop float32
// SnapDuration is how long a card takes to settle after a valid drop, a Move or a layout change; 0 uses DefaultSnapDuration and a negative value settles at once.
SnapDuration time.Duration
// ReturnDuration is how long a rejected card takes to fly back; 0 uses DefaultReturnDuration and a negative value returns at once.
ReturnDuration time.Duration
// Curve eases every move; the zero value is core.Linear, and core.EaseOut gives a softer landing.
Curve core.Curve
// MapPoint, when set, maps a touch's position in the view hearing it to board coordinates, as for a camera or a scaled viewport; returning false ignores the point. Nil uses the view's coordinates as they are.
MapPoint func(core.Point) (math2d.Vec2, bool)
// Accept, when set, also has to admit every drop of card c from slot from onto slot to other than back into from.
Accept func(c *Card, from, to *Slot) bool
// OnPickUp runs when a card starts following a pointer.
OnPickUp func(c *Card)
// OnTap runs when a pointer presses and releases a card without dragging it.
OnTap func(c *Card)
// OnDrop runs after a card lands in a slot that accepted it.
OnDrop func(DropEvent)
// OnReturn runs after a dragged card is sent back to its slot.
OnReturn func(ReturnEvent)
// contains filtered or unexported fields
}Board holds slots of cards and drags cards between them with pointers, tweening every move. Step it with Update on each game.Loop step.
The zero value is ready to use; zero tuning fields use the Default constants.
func LoadBoard(doc *BoardDoc) (*Board, error)LoadBoard validates doc and returns a Board with its card size and its slots, empty and in order. The board's other fields are left for the game to set.
func (b *Board) Add(c *Card, s *Slot, index int) errorAdd puts c into s at index (appending when index is negative or past the end) and settles s at once, without tweening: for dealing the opening position. Add ignores the slot's rules.
func (b *Board) AddSlot(s *Slot) errorAddSlot adds s on top of the slots already on the board: where slots overlap, the later one takes pointer drops.
func (b *Board) Attach(v *core.View)Attach wires b.OnTouch onto v, the view holding the game's Canvas, chaining any OnTouch v already has after the board's.
func (b *Board) CanDrop(c *Card, to *Slot) boolCanDrop reports whether slot to would accept c dropped onto it now: its own slot always does; another needs room under Capacity, a tag in Accepts when that is set, and the approval of to.Accept and Board.Accept when they are set.
func (b *Board) CardAt(p math2d.Vec2) *CardCardAt returns the topmost card drawn under p, following each card's rotation, or nil.
func (b *Board) Doc() (*BoardDoc, error)Doc returns the board's card size and slots as a BoardDoc, writing the default grab rule by omitting it. A slot's Accept function and the board's callbacks and tuning are code and are not written; a slot whose Layout is not a Fan, Stack or Grid (or a pointer to one) fails with ErrCustomLayout.
func (b *Board) DrawOrder(dst []*Card) []*CardDrawOrder appends the board's cards to dst in the order to draw them, bottom first, and returns the extended slice: each slot's cards in slot order, then the cards that are held or flying, in the order they were lifted.
func (b *Board) DropTarget(c *Card) (*Slot, bool)DropTarget returns the slot a held card would drop onto if released now, and whether that slot accepts it, so a game can highlight it. It returns nil and false for a card no pointer is dragging, and nil and false while the card is over no slot.
func (b *Board) Move(c *Card, to *Slot, index int) errorMove sends c into slot to at index (appending when index is negative or past the end), tweening it over SnapDuration and drawing it above the slots until it lands. A drag holding c is cancelled. Move ignores the slot's rules, as a game dealing or undoing does.
func (b *Board) OnTouch(ev core.TouchEvent)OnTouch feeds a core.TouchEvent to the board, each finger that changed being its own pointer by Touch.ID; desktops report the primary mouse button as finger 0 and the web every pointer as a finger, so this handles the mouse too. A finger lifting where MapPoint refuses its point is cancelled.
func (b *Board) PointerCancel(id int)PointerCancel ends pointer id without a drop, as when the system takes the touches: a card it was dragging flies back to its slot.
func (b *Board) PointerDown(id int, p math2d.Vec2) boolPointerDown presses pointer id at p, in board coordinates, and reports whether it took a card: the topmost card under p that is not Locked, not already pressed by another pointer and that its slot's Grab rule lets go. The card follows the pointer once it moves past DragSlop.
func (b *Board) PointerMove(id int, p math2d.Vec2)PointerMove moves pointer id to p, dragging its card once it has moved past DragSlop from its press.
func (b *Board) PointerUp(id int, p math2d.Vec2)PointerUp releases pointer id at p: a card it was dragging drops into the slot under it when that slot accepts it and flies back otherwise, and a card it pressed without dragging is tapped.
func (b *Board) Relayout(s *Slot)Relayout tweens the cards of s to its layout, as after changing its Rect or Layout. Held cards keep following their pointers.
func (b *Board) Remove(c *Card) errorRemove takes c off the board, cancelling a drag holding it, and tweens the rest of its slot closed.
func (b *Board) Settle()Settle finishes every tween at once, leaving held cards where their pointers put them.
func (b *Board) Size() math2d.Vec2Size returns the card size the board uses.
func (b *Board) Slot(id string) *SlotSlot returns the slot named id, or nil.
func (b *Board) SlotAt(p math2d.Vec2) *SlotSlotAt returns the topmost slot whose Rect holds p, or nil.
func (b *Board) Slots() []*SlotSlots returns a copy of the board's slots in the order they were added.
func (b *Board) Update(dt time.Duration)Update advances every card's tween by dt. Call it once per game.Loop.Update step.
type BoardDoc struct {
// Version must equal FormatVersion.
Version int `yaml:"version"`
// CardSize is every card's width and height; both must be positive.
CardSize SizeDoc `yaml:"card_size"`
// Slots are the board's slots, bottom first; their IDs must be unique.
Slots []SlotDoc `yaml:"slots,omitempty"`
}BoardDoc is a board's slots written as YAML: a schema version, the card size and each slot's area, layout and rules.
version: 1
card_size:
w: 63
h: 88
slots:
- id: hand
rect:
x: 40
"y": 400
w: 560
h: 120
layout:
fan:
arc: 24
sag: 14
- id: discard
rect:
x: 360
"y": 200
w: 63
h: 88
layout:
stack:
offset:
x: 0
"y": -0.5
depth: 6
accepts:
- red
- black
grab: top
ParseBoardDoc refuses unknown fields, and EncodeBoardDoc writes the fields in a fixed order and in block style, as above. A file in that form, as EncodeBoardDoc writes it, is unchanged when read and written again; a hand-written file in flow style comes back in block style the first time.
func ParseBoardDoc(data []byte) (*BoardDoc, error)ParseBoardDoc decodes one YAML BoardDoc and validates it. Unknown fields and trailing documents are refused.
func (doc *BoardDoc) Validate() errorValidate checks doc against the version 1 schema: positive finite sizes, finite coordinates, unique non-empty slot IDs, exactly one layout per slot with non-negative counts and a Fan arc under 360 degrees, unique non-empty tags, a non-negative capacity and a known grab rule.
type Card struct {
// ID names the card for the game; the board does not require it to be unique.
ID string
// Tags are matched against Slot.Accepts.
Tags []string
// Locked keeps the card from being picked up by a pointer; programmatic moves still apply.
Locked bool
// Data is the game's payload for the card.
Data any
// contains filtered or unexported fields
}Card is one card on a Board. Its exported fields are the game's; the board owns where it is and how it moves.
func (c *Card) HasTag(tag string) boolHasTag reports whether tag is one of the card's Tags.
func (c *Card) Held() boolHeld reports whether a pointer is dragging the card.
func (c *Card) Index() intIndex returns the card's place in its slot, 0 being the first (bottom) card, or -1 when it is not on a board.
func (c *Card) Moving() boolMoving reports whether the card is tweening to a pose.
func (c *Card) Slot() *SlotSlot returns the slot holding the card, or nil when it is not on a board.
type DropEvent struct {
Card *Card
// From and FromIndex are where the card was; To and Index where it is now. From equals To when a card was reordered within its slot.
From, To *Slot
FromIndex, Index int
}DropEvent reports a card dropped into a slot that accepted it.
type Fan struct {
// Spacing is the distance in points between neighboring cards' centers; 0 uses 60% of the card's width.
Spacing float32
// Arc is the rotation in degrees from the leftmost to the rightmost card of a full-width hand; 0 keeps every card upright.
Arc float32
// Sag is how many points the end cards of a full-width hand sit below the middle one (negative raises them).
Sag float32
}Fan lays a hand out in a row centered in the slot, tilting and dropping the cards toward its ends as a hand held in a fan.
Cards sit Spacing apart, closer when the row would not fit the slot's width. A card's tilt and drop grow with its distance from the middle relative to half the room the slot has, so a full-width hand reaches ±Arc/2 at its ends and a short hand stays nearly flat.
func (f Fan) Arrange(area math2d.Rect, card math2d.Vec2, n int, dst []Pose) []PoseArrange implements Layout.
func (f Fan) InsertIndex(area math2d.Rect, card math2d.Vec2, n int, p math2d.Vec2) intInsertIndex implements Layout: the place in the row, once it holds n+1 cards, nearest to p horizontally.
type FanDoc struct {
Spacing float32 `yaml:"spacing,omitempty"`
Arc float32 `yaml:"arc,omitempty"`
Sag float32 `yaml:"sag,omitempty"`
}FanDoc is a Fan; Arc is in degrees.
type GrabRule uint8GrabRule says which cards of a slot a pointer may pick up.
const (
// GrabAny lets any card of the slot be dragged, as from a hand.
GrabAny GrabRule = iota
// GrabTop lets only the last (topmost) card be dragged, as from a deck or a discard pile.
GrabTop
// GrabNone keeps every card of the slot in place.
GrabNone
)func (g GrabRule) String() stringString returns the rule's name: "any", "top" or "none". BoardDoc writes "top" and "none" and leaves GrabAny out.
type Grid struct {
// Columns is how many cards fill a row; 0 fits as many as the slot's width holds (at least one).
Columns int
// Gap is the space in points between neighboring cards, across (X) and down (Y).
Gap math2d.Vec2
}Grid lays cards out in rows from the slot's top-left corner, left to right and then top to bottom, as a board of cells or an inventory.
func (g Grid) Arrange(area math2d.Rect, card math2d.Vec2, n int, dst []Pose) []PoseArrange implements Layout.
func (g Grid) InsertIndex(area math2d.Rect, card math2d.Vec2, n int, p math2d.Vec2) intInsertIndex implements Layout: the cell under p, kept within the n+1 cells the slot then fills.
type GridDoc struct {
Columns int `yaml:"columns,omitempty"`
Gap VecDoc `yaml:"gap,omitempty"`
}GridDoc is a Grid.
type Layout interface {
// Arrange appends the poses of n cards of size card laid out in area to dst, first card first, and returns the extended slice. It must append exactly n poses (none for n <= 0) and depend only on its arguments.
Arrange(area math2d.Rect, card math2d.Vec2, n int, dst []Pose) []Pose
// InsertIndex returns where, in [0, n], a card dropped with its center at p goes among the n cards already laid out in area.
InsertIndex(area math2d.Rect, card math2d.Vec2, n int, p math2d.Vec2) int
}Layout arranges the cards of a slot inside the slot's rectangle. Fan, Stack and Grid implement it; a game may supply its own.
type LayoutDoc struct {
Fan *FanDoc `yaml:"fan,omitempty"`
Stack *StackDoc `yaml:"stack,omitempty"`
Grid *GridDoc `yaml:"grid,omitempty"`
}LayoutDoc names a slot's layout: exactly one of its fields is set.
type Pose struct {
Pos math2d.Vec2
Rot float32
}Pose places a card: Pos is its center in board coordinates and Rot its rotation in radians around that center, turning from +X toward +Y (clockwise on NSGo's Y-down canvas).
func (p Pose) Lerp(q Pose, t float32) PoseLerp returns the pose t of the way from p to q, interpolating the center and the rotation linearly.
type RectDoc struct {
X float32 `yaml:"x"`
Y float32 `yaml:"y"`
W float32 `yaml:"w"`
H float32 `yaml:"h"`
}RectDoc is a rectangle in board coordinates, its origin at the top-left corner.
type ReturnEvent struct {
Card *Card
// Slot is the slot the card returns to.
Slot *Slot
// Rejected is the slot that refused the drop, or nil when the card was released over no slot or its pointer was cancelled.
Rejected *Slot
}ReturnEvent reports a dragged card going back to its slot.
type SizeDoc struct {
W float32 `yaml:"w"`
H float32 `yaml:"h"`
}SizeDoc is a width and a height in board coordinates.
type Slot struct {
// ID names the slot; it must be unique on its board.
ID string
// Rect is the slot's area in board coordinates: where its layout places cards and where a pointer drops onto it.
Rect math2d.Rect
// Layout arranges the slot's cards; nil stacks them all at Rect's top-left corner, as Stack{}.
Layout Layout
// Accepts, when not empty, admits only cards with at least one of these tags.
Accepts []string
// Capacity, when positive, is how many cards the slot holds at most.
Capacity int
// Grab says which of the slot's cards a pointer may pick up.
Grab GrabRule
// Accept, when set, also has to admit a card dropped from slot from.
Accept func(c *Card, from *Slot) bool
// contains filtered or unexported fields
}Slot is a place on a Board that holds cards in order and lays them out in Rect.
func (s *Slot) Board() *BoardBoard returns the board holding the slot, or nil.
func (s *Slot) Card(i int) *CardCard returns the slot's i-th card, 0 being the first (bottom) one, or nil when i is out of range.
func (s *Slot) Cards() []*CardCards returns a copy of the slot's cards in order.
func (s *Slot) Top() *CardTop returns the slot's last card, or nil when it is empty.
type SlotDoc struct {
ID string `yaml:"id"`
Rect RectDoc `yaml:"rect"`
Layout LayoutDoc `yaml:"layout"`
Accepts []string `yaml:"accepts,omitempty"`
Capacity int `yaml:"capacity,omitempty"`
Grab string `yaml:"grab,omitempty"`
}SlotDoc is one Slot: Grab is "top" or "none", or omitted for GrabAny; "any" itself is refused so the default has a single form.
type Stack struct {
// Offset moves each card from the one before it, in points.
Offset math2d.Vec2
// Depth caps how many distinct offsets show: cards past the first Depth sit where the Depth-th does, so a tall deck keeps its footprint. 0 means no cap.
Depth int
}Stack piles cards from the slot's top-left corner, each Offset from the one below it: a small offset makes a deck, a card-height fraction makes a pile whose cards all show, as a solitaire column.
func (s Stack) Arrange(area math2d.Rect, card math2d.Vec2, n int, dst []Pose) []PoseArrange implements Layout.
func (s Stack) InsertIndex(_ math2d.Rect, _ math2d.Vec2, n int, _ math2d.Vec2) intInsertIndex implements Layout: a stack only grows on top.
type StackDoc struct {
Offset VecDoc `yaml:"offset,omitempty"`
Depth int `yaml:"depth,omitempty"`
}StackDoc is a Stack.
type VecDoc struct {
X float32 `yaml:"x"`
Y float32 `yaml:"y"`
}VecDoc is a 2D offset in board coordinates.