GitHubGet started

package roomstate

import "github.com/nsgo-dev/game/pkg/online/netplay/roomstate"

Overview

Package roomstate is experimental: its API and documented formats may change in a minor release. See the API stability policy. is experimental: its API and documented formats may change in a minor release. See the API stability policy. Package roomstate provides deterministic, view-filtered room state deltas: the non-entity state of a room (scores, timers, player names, ready flags, hands of cards) as named fields, each with a visibility, and JSON deltas of the fields changed since a version, filtered for one viewer at encode time.

Index

Types

type Field struct {
	Value any
	View  View
	Owner string
	Team  string
}

Field is one state value and its visibility contract.

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

State stores JSON-compatible fields and the version each last changed at. The zero value is ready to use. A State is not safe for concurrent use.

func New() *State

New returns an empty state.

func (s *State) Delete(name string)

Delete removes a field; the next delta carries a null marker for it to the viewers that could see it. Deleting a field that does not exist does nothing.

func (s *State) Delta(after uint64, owner, team string) ([]byte, uint64, error)

Delta returns deterministic JSON holding the fields changed after version after that the viewer with the given owner ID and team may see, as {"version":V,"fields":{...}} with keys in sorted order, and the current version V to pass as after next time. A field the viewer could see before and cannot now (deleted, or moved out of its view) appears as null. A field the viewer has never been able to see is omitted, so neither its value nor its existence reaches the viewer. Pass after 0 for a full state.

func (s *State) Set(name string, value any, view View, owner, team string)

Set publishes a field value and marks it dirty. Values must be JSON-marshalable; Set keeps value as given, so a slice or map mutated after Set is not marked dirty until Set is called again. Changing a field's view, owner or team sends a removal to the viewers that could see it before and can no longer.

func (s *State) Version() uint64

Version returns the version of the latest change.

type View uint8

View selects which recipients may see a field.

const (
	// ViewAll fields are sent to every viewer.
	ViewAll View = iota
	// ViewOwner fields are sent only to the viewer whose owner ID equals the field's non-empty Owner.
	ViewOwner
	// ViewTeam fields are sent only to viewers whose team equals the field's non-empty Team.
	ViewTeam
	// ViewServer fields are never sent to any viewer.
	ViewServer
)