game

package
v0.1.11 Latest Latest
Warning

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

Go to latest
Published: May 15, 2024 License: MIT Imports: 39 Imported by: 0

README

Game

This is the core implementation of end_of_eden. This doesn't contain any ui code, as the base game logic and ui is fully seperated in this project.

Session

The Session type is the core of a running game session. It exposes a multitude of methods that are able to mutate the game state. By only exposing methods, calling them should mutate the session from one valid game state to another valid game state. The session will (with a few exceptions) only return copies of data and no pointer so that the consumer can't mutate the state without going through the right method call.

At the moment access to a Session is expected to be single-threaded!

session := game.NewSession(/* options */)

// interact with the session

Types

  • Artifact: Base definition for an artifact
  • Card: Base definition for a card
  • StatusEffect: Base definition for a status effect
  • Event: Base definition for an event
  • Enemy: Base definition for an enemy
  • StoryTeller: Base definition for an story teller
  • ArtifactInstance: Instance of an artifact that is owned by an Actor and references its base definition via the TypeID
  • CardInstance: Instance of a card that is owned by an Actor and references its base definition via the TypeID
  • StatusEffectInstance: Instance of a status effect that is owned by an Actor and references its base definition via the TypeID
  • Actor: Instance of either the player or an enemy. If it's an enemy the TypeID references its base definition

Checkpointing

Although the game code doesn't contain any ui there is a mechanism that helps ui and animations to react to events in the game. It is possible to create checkpoints of the game state, execute one or more operations that alter the game state and then get a diff of what happened.

In case we want to see if the enemy turn resulted in damage to the player we could use checkpoints:

// Store state checkpoint before operation
before := session.MarkState()

// Finish the player turn, which means that enemies are allowed to act
session.FinishPlayerTurn()

// Check if any damage was triggered
damages := before.DiffEvent(m.Session, game.StateEventDamage)
for i := range damages {
	// Do something with the damage data -> queue animation, play audio
}

This also makes it really easy to keep track of everything that happened in a fight, so that a re-cap screen can be shown. We just need to store the state at the beginning of the fight and diff it when it ends.

Documentation

Index

Constants

View Source
const (
	CallbackOnDamage        = "OnDamage"
	CallbackOnDamageCalc    = "OnDamageCalc"
	CallbackOnHealCalc      = "OnHealCalc"
	CallbackOnCast          = "OnCast"
	CallbackOnActorDidCast  = "OnActorDidCast"
	CallbackOnInit          = "OnInit"
	CallbackOnPickUp        = "OnPickUp"
	CallbackOnTurn          = "OnTurn"
	CallbackOnPlayerTurn    = "OnPlayerTurn"
	CallbackOnStatusAdd     = "OnStatusAdd"
	CallbackOnStatusStack   = "OnStatusStack"
	CallbackOnStatusRemove  = "OnStatusRemove"
	CallbackOnRemove        = "OnRemove"
	CallbackOnActorDie      = "OnActorDie"
	CallbackOnMerchantEnter = "OnMerchantEnter"
)
View Source
const (
	// TriggerArtifact triggers for artifacts.
	TriggerArtifact = Trigger(1)

	// TriggerStatusEffect triggers for status effects.
	TriggerStatusEffect = Trigger(2)

	// TriggerEnemy triggers for enemies.
	TriggerEnemy = Trigger(4)

	// TriggerAll triggers for all objects.
	TriggerAll = Trigger(TriggerArtifact | TriggerStatusEffect | TriggerEnemy)
)
View Source
const (
	StateEventDeath           = StateEvent("Death")
	StateEventDamage          = StateEvent("Damage")
	StateEventHeal            = StateEvent("Heal")
	StateEventMoney           = StateEvent("Money")
	StateEventArtifactAdded   = StateEvent("ArtifactAdded")
	StateEventArtifactRemoved = StateEvent("ArtifactRemoved")
	StateEventCardAdded       = StateEvent("CardAdded")
	StateEventCardRemoved     = StateEvent("CardRemoved")
)
View Source
const (
	LogTypeInfo    = LogType("INFO")
	LogTypeWarning = LogType("WARNING")
	LogTypeDanger  = LogType("DANGER")
	LogTypeSuccess = LogType("SUCCESS")
)
View Source
const (
	GameStateFight    = GameState("FIGHT")
	GameStateMerchant = GameState("MERCHANT")
	GameStateEvent    = GameState("EVENT")
	GameStateRandom   = GameState("RANDOM")
	GameStateGameOver = GameState("GAME_OVER")
)
View Source
const (
	// DefaultUpgradeCost is the default cost for upgrading a card.
	DefaultUpgradeCost = 65

	// DefaultRemoveCost is the default cost for removing a card.
	DefaultRemoveCost = 50

	// PointsPerRound is the amount of points the player gets per round.
	PointsPerRound = 3

	// DrawSize is the amount of cards the player draws per round.
	DrawSize = 3
)
View Source
const (
	DecayAll  = DecayBehaviour("DecayAll")
	DecayOne  = DecayBehaviour("DecayOne")
	DecayNone = DecayBehaviour("DecayNone")
)
View Source
const (
	HookNextFightEnd = Hook("NextFightEnd")
)
View Source
const PlayerActorID = "PLAYER"

Variables

View Source
var EmptyContext = Context{}

Functions

func CopyMap added in v0.1.6

func CopyMap[K comparable, V any](m map[K]V) map[K]V

CopyMap copies a map. If the value is a pointer, the pointer is copied, not the value.

func ExposeDebug

func ExposeDebug(port int, session *Session, l *lua.LState, log *log.Logger) func() error

ExposeDebug exposes a debug interface on the given port. This interface can be used to execute lua code on the server. This is a very dangerous function, which should only be used for debugging purposes. It should never be exposed to the public.

func NewGuid

func NewGuid(tags ...string) string

NewGuid creates a new guid with the given tags. Tags are optional and only used for debugging purposes.

func SessionAdapter

func SessionAdapter(session *Session) (*lua.LState, *ludoc.Docs)

SessionAdapter creates a lua vm that is bound to the session in the given Session.

func TriggerCallback added in v0.1.8

func TriggerCallback(s *Session, callback string, who Trigger, fn func(val any, guid string, t Trigger, state TriggerCallbackState) TriggerCallbackState, addedCtx Context, ctx ...any)

TriggerCallback traverses all artifacts, status effects and enemies and calls the given callback for each object.

  • callback: The name of the callback to call.
  • who: For which objects the callback should be called.
  • fn: The function to call for each object. The function gets the current value, the guid of the object, the type of the object and the current state as arguments. The function should return the new state.
  • addedCtx: Additional context that should be added to the context.
  • ctx: Additional context that should be added to the context.

func TriggerCallbackFirst added in v0.1.8

func TriggerCallbackFirst[T any](s *Session, callback string, who Trigger, addedCtx Context, ctx ...any) T

TriggerCallbackFirst is a helper function for TriggerCallback that returns the first value of the callback.

func TriggerCallbackFirstOfStop added in v0.1.8

func TriggerCallbackFirstOfStop[T any](s *Session, callback string, who Trigger, check func(val T) bool, addedCtx Context, ctx ...any) T

TriggerCallbackFirstOfStop is a helper function for TriggerCallback that returns the first value of the callback that matches the given check function. After the first match the callback is stopped.

func TriggerCallbackFirstStop added in v0.1.8

func TriggerCallbackFirstStop[T any](s *Session, callback string, who Trigger, addedCtx Context, ctx ...any) T

TriggerCallbackFirstStop is a helper function for TriggerCallback that returns the first value of the callback and stops the callback.

func TriggerCallbackReduce added in v0.1.8

func TriggerCallbackReduce[T any](s *Session, callback string, who Trigger, reducer func(cur T, val T) T, initial T, propagatedCtxKey string, addedCtx Context, ctx ...any) T

TriggerCallbackReduce is a helper function for TriggerCallback that reduces all values of the callback to a single value.

func TriggerCallbackSimple added in v0.1.8

func TriggerCallbackSimple(s *Session, callback string, who Trigger, addedCtx Context, ctx ...any) []any

TriggerCallbackSimple is a helper function for TriggerCallback that returns all values of the callback as a slice.

func WithDebugEnabled

func WithDebugEnabled(port int) func(s *Session)

WithDebugEnabled enables the lua debugging. With lua debugging a server will be started on the given bind port. This exposes the /ws route to connect over websocket to. In essence, it exposes REPL access to the internal lua state which is helpful to debug problems. You can use the debug_r function to send data back to the websocket.

Tip: Use https://github.com/websockets/wscat to connect and talk with it.

func WithLogging

func WithLogging(logger *log.Logger) func(s *Session)

WithLogging sets the internal logger.

func WithMods

func WithMods(mods []string) func(s *Session)

WithMods sets the mods that should be loaded.

func WithOnLuaError

func WithOnLuaError(fn func(file string, line int, callback string, typeId string, err error)) func(s *Session)

WithOnLuaError sets the function that will be called when a lua error happens.

Types

type Actor

type Actor struct {
	GUID          string `lua:"guid"`
	TypeID        string
	Name          string
	Description   string
	HP            int
	MaxHP         int
	Gold          int
	Artifacts     *StringSet
	Cards         *StringSet
	StatusEffects *StringSet
}

Actor represents a player or enemy.

func NewActor

func NewActor(ID string) Actor

func (Actor) Clone

func (a Actor) Clone() Actor

func (Actor) IsNone

func (a Actor) IsNone() bool

func (Actor) Sanitize

func (a Actor) Sanitize() Actor

Sanitize ensures that the actor has all the required fields.

type Artifact

type Artifact struct {
	ID          string
	Name        string
	Description string
	Tags        []string
	Order       int
	Price       int
	Callbacks   map[string]luhelp.OwnedCallback
	Test        luhelp.OwnedCallback
	BaseGame    bool
}

func (Artifact) PublicTags added in v0.1.8

func (a Artifact) PublicTags() []string

type ArtifactInstance

type ArtifactInstance struct {
	TypeID string
	GUID   string
	Owner  string
}

type Card

type Card struct {
	ID          string
	Name        string
	Description string
	Tags        []string
	State       luhelp.OwnedCallback
	Color       string
	PointCost   int
	MaxLevel    int
	DoesExhaust bool
	DoesConsume bool
	NeedTarget  bool
	Price       int
	Callbacks   map[string]luhelp.OwnedCallback
	Test        luhelp.OwnedCallback
	BaseGame    bool
}

Card represents a playable card definition.

func (Card) PublicTags added in v0.1.8

func (c Card) PublicTags() []string

type CardInstance

type CardInstance struct {
	TypeID string
	GUID   string
	Level  int
	Owner  string
}

CardInstance represents an instance of a card owned by some actor.

func (CardInstance) IsNone

func (c CardInstance) IsNone() bool

type Context

type Context map[string]any

Context represents the context arguments for a callback.

func CreateContext

func CreateContext(args ...any) Context

CreateContext creates a new context with the given key value pairs. The number of arguments must be even. Example: CreateContext("key1", "value1", "key2", 124)

func (Context) Add added in v0.1.8

func (c Context) Add(args ...any) Context

Add adds the given key value pairs to the context. The number of arguments must be even.

func (Context) AddContext added in v0.1.8

func (c Context) AddContext(ctx Context) Context

AddContext adds the given context to the context.

type DecayBehaviour

type DecayBehaviour string

type Enemy

type Enemy struct {
	ID          string
	Name        string
	Description string
	InitialHP   int
	MaxHP       int
	Look        string
	Color       string
	Intend      luhelp.OwnedCallback
	Callbacks   map[string]luhelp.OwnedCallback
	Test        luhelp.OwnedCallback
	BaseGame    bool
}

Enemy represents a definition of a enemy that can be linked from a Actor.

type Event

type Event struct {
	ID          string
	Name        string
	Description string
	Tags        []string
	Choices     []EventChoice
	OnEnter     luhelp.OwnedCallback
	OnEnd       luhelp.OwnedCallback
	Test        luhelp.OwnedCallback
	BaseGame    bool
}

Event represents a encounter-able event.

func (Event) IsNone

func (e Event) IsNone() bool

type EventChoice

type EventChoice struct {
	Description   string
	DescriptionFn luhelp.OwnedCallback
	Callback      luhelp.OwnedCallback
}

EventChoice represents a possible choice in the Event.

type FightState

type FightState struct {
	Round         int
	Description   string
	CurrentPoints int
	Deck          []string
	Hand          []string
	Used          []string
	Exhausted     []string
}

FightState represents the current state of the fight in regard to the deck of the player.

type GameState

type GameState string

GameState represents the current state of the game.

type Hook added in v0.1.8

type Hook string

type LogEntry

type LogEntry struct {
	Time    time.Time
	Type    LogType
	Message string
}

LogEntry represents a log entry.

type LogType

type LogType string

LogType represents the type of log entry.

type LuaError

type LuaError struct {
	File     string
	Line     int
	Callback string
	Type     string
	Err      error
}

LuaError represents an error that occurred in lua.

type MerchantState

type MerchantState struct {
	Face      string
	Text      string
	Cards     []string
	Artifacts []string
}

MerchantState represents the current state of the merchant.

type Mod

type Mod struct {
	Name        string `json:"name"`
	Author      string `json:"author"`
	Description string `json:"description"`
	Version     string `json:"version"`
	URL         string `json:"url"`
}

func ModDescription

func ModDescription(folder string) (Mod, error)

type ResourcesManager

type ResourcesManager struct {
	Artifacts     map[string]*Artifact
	Cards         map[string]*Card
	Events        map[string]*Event
	Enemies       map[string]*Enemy
	StatusEffects map[string]*StatusEffect
	StoryTeller   map[string]*StoryTeller
	// contains filtered or unexported fields
}

ResourcesManager can load Artifacts, Cards, Events, Enemy and StoryTeller data from lua. The manager will walk the ./scripts directory and evaluate all found .lua files.

func NewResourcesManager

func NewResourcesManager(state *lua.LState, docs *ludoc.Docs, logger *log.Logger) *ResourcesManager

func (*ResourcesManager) MarkBaseGame added in v0.1.6

func (man *ResourcesManager) MarkBaseGame()

MarkBaseGame marks all currently registered resources as base game resources.

type SavedState

type SavedState struct {
	State            GameState
	Actors           map[string]Actor
	Instances        map[string]any
	StagesCleared    int
	CurrentEvent     string
	CurrentFight     FightState
	Merchant         MerchantState
	EventHistory     []string
	StateCheckpoints []StateCheckpoint
	CtxData          map[string]any
	LoadedMods       []string
}

SavedState represents a save file that don't contain any pointer so the lua runtime or other pointer.

type Session

type Session struct {
	Logs []LogEntry
	// contains filtered or unexported fields
}

Session represents the state inside a game session.

func NewSession

func NewSession(options ...func(s *Session)) *Session

NewSession creates a new game session.

func (*Session) ActiveTeller

func (s *Session) ActiveTeller() *StoryTeller

ActiveTeller returns the active storyteller. The storyteller is responsible for deciding what enemies or events the player will encounter next.

func (*Session) ActorAddHP

func (s *Session) ActorAddHP(id string, val int)

ActorAddHP adds HP to an actor.

func (*Session) ActorAddMaxHP

func (s *Session) ActorAddMaxHP(id string, val int)

ActorAddMaxHP adds max hp to an actor.

func (*Session) AddActor

func (s *Session) AddActor(actor Actor)

AddActor adds an actor to the session.

func (*Session) AddActorFromEnemy

func (s *Session) AddActorFromEnemy(id string) string

AddActorFromEnemy adds an actor to the session from an enemy base.

func (*Session) AddHook added in v0.1.8

func (s *Session) AddHook(hook Hook, callback func())

AddHook adds a hook to the session.

func (*Session) AddMerchantArtifact

func (s *Session) AddMerchantArtifact()

AddMerchantArtifact adds another artifact to the wares of the merchant.

func (*Session) AddMerchantCard

func (s *Session) AddMerchantCard()

AddMerchantCard adds another card to the wares of the merchant.

func (*Session) AddStatusEffectStacks

func (s *Session) AddStatusEffectStacks(guid string, stacks int)

AddStatusEffectStacks increases the stacks of a certain status effect by guid.

func (*Session) BuyRemoveCard

func (s *Session) BuyRemoveCard(guid string) bool

BuyRemoveCard removes a card by its GUID.

func (*Session) BuyUpgradeCard

func (s *Session) BuyUpgradeCard(guid string) bool

BuyUpgradeCard upgrades a card by its GUID.

func (*Session) CastCard

func (s *Session) CastCard(guid string, target string) bool

CastCard calls the OnCast callback for a card, casting it.

func (*Session) CleanUpFight

func (s *Session) CleanUpFight()

CleanUpFight resets the fight state.

func (*Session) Close

func (s *Session) Close()

Close closes the internal lua state and everything else.

func (*Session) DealDamage

func (s *Session) DealDamage(source string, card string, target string, damage int, flat bool) int

DealDamage deals damage to a target. If flat is true it will not trigger any callbacks which modify the damage.

func (*Session) DealDamageMulti

func (s *Session) DealDamageMulti(source string, card string, targets []string, damage int, flat bool) []int

DealDamageMulti will deal damage to multiple targets and return the amount of damage dealt to each target. If flat is true it will not trigger any OnDamageCalc callbacks which modify the damage.

func (*Session) EnemyTurn

func (s *Session) EnemyTurn()

EnemyTurn lets all enemies act. This will also trigger the OnTurn callbacks of all status effects and artifacts. If a status effect or artifact returns true, the enemy turn will be skipped. This is used for example by the "FEAR" status effect.

func (*Session) Fetch

func (s *Session) Fetch(key string) any

Fetch retrieves a value from the session context.

func (*Session) FinishEvent

func (s *Session) FinishEvent(choice int)

FinishEvent finishes an event with the given choice. If the game state is not in the EVENT state this does nothing.

func (*Session) FinishFight

func (s *Session) FinishFight() bool

FinishFight tries to finish the fight. This will return true if the fight is really over.

func (*Session) FinishPlayerTurn

func (s *Session) FinishPlayerTurn()

FinishPlayerTurn signals that the player is done with its turn. All enemies act now, status effects are evaluated, if the fight is over is checked and if not this will advance to the next round and draw cards for the player.

func (*Session) GetActor

func (s *Session) GetActor(id string) Actor

GetActor returns an actor.

func (*Session) GetActorIntend

func (s *Session) GetActorIntend(guid string) string

GetActorIntend returns the intend of an actor.

func (*Session) GetActorStatusEffects

func (s *Session) GetActorStatusEffects(guid string) []string

GetActorStatusEffects returns the guids of all the status effects a certain actor owns.

func (*Session) GetActors

func (s *Session) GetActors() []string

GetActors returns all actors.

func (*Session) GetArtifact

func (s *Session) GetArtifact(guid string) (*Artifact, ArtifactInstance)

GetArtifact returns an artifact, and instance by guid or type id. If a type id is given only the Artifact will be returned.

func (*Session) GetArtifactOrder

func (s *Session) GetArtifactOrder(guid string) int

GetArtifactOrder returns the order value of a certain artifact by guid.

func (*Session) GetArtifacts

func (s *Session) GetArtifacts(owner string) []string

GetArtifacts returns all artifacts owned by a actor.

func (*Session) GetCard

func (s *Session) GetCard(guid string) (*Card, CardInstance)

GetCard returns a card, and instance by guid or type id. If a type id is given only the Card will be returned. If the card is not found, nil is returned.

func (*Session) GetCardState

func (s *Session) GetCardState(guid string) string

GetCardState returns the state of a card.

func (*Session) GetCards

func (s *Session) GetCards(owner string) []string

GetCards returns all cards owned by a actor.

func (*Session) GetEnemy

func (s *Session) GetEnemy(typeId string) *Enemy

GetEnemy returns the enemy with the given type id.

func (*Session) GetEvent

func (s *Session) GetEvent() *Event

GetEvent returns the event definition of the current event. Will be nil if no event is present. It is not allowed to change the Event data, as this points to the event data created in lua!

func (*Session) GetEventChoiceDescription

func (s *Session) GetEventChoiceDescription(i int) string

func (*Session) GetEventHistory

func (s *Session) GetEventHistory() []string

GetEventHistory returns the ordered list of all events encountered so far.

func (*Session) GetEventID added in v0.1.6

func (s *Session) GetEventID() string

GetEventID returns the id of the current event.

func (*Session) GetFight

func (s *Session) GetFight() FightState

GetFight returns the fight state. This will return a fight state even if no fight is active at the moment.

func (*Session) GetFightRound

func (s *Session) GetFightRound() int

GetFightRound returns the current round of the fight.

func (*Session) GetFormerState

func (s *Session) GetFormerState(index int) *Session

GetFormerState iterates backwards over the states, so index == -1 means the last state and so on.

func (*Session) GetGameState

func (s *Session) GetGameState() GameState

GetGameState returns the current game state.

func (*Session) GetInstance

func (s *Session) GetInstance(guid string) any

GetInstance returns an instance by guid. An instance is a CardInstance or ArtifactInstance.

func (*Session) GetInstances

func (s *Session) GetInstances() []string

GetInstances returns all instances in the session.

func (*Session) GetLoadedMods

func (s *Session) GetLoadedMods() []string

GetLoadedMods returns the list of loaded mods.

func (*Session) GetMerchant

func (s *Session) GetMerchant() MerchantState

GetMerchant return the merchant state.

func (*Session) GetMerchantGoldMax

func (s *Session) GetMerchantGoldMax() int

GetMerchantGoldMax returns what the max cost of a artifact or card is that the merchant might offer.

func (*Session) GetOpponentByIndex

func (s *Session) GetOpponentByIndex(viewpoint string, i int) Actor

GetOpponentByIndex returns the opponent at the given index from the given viewpoint.

func (*Session) GetOpponentCount

func (s *Session) GetOpponentCount(viewpoint string) int

GetOpponentCount returns the number of opponents from the given viewpoint.

func (*Session) GetOpponentGUIDs

func (s *Session) GetOpponentGUIDs(viewpoint string) []string

GetOpponentGUIDs returns the guids of the opponents from the given viewpoint.

func (*Session) GetOpponents

func (s *Session) GetOpponents(viewpoint string) []Actor

GetOpponents returns the opponents from the given viewpoint.

func (*Session) GetPlayer

func (s *Session) GetPlayer() Actor

GetPlayer returns the player.

func (*Session) GetRandomArtifact

func (s *Session) GetRandomArtifact(maxGold int) string

GetRandomArtifact returns the type id of a random artifact with a price lower than the given value.

func (*Session) GetRandomCard

func (s *Session) GetRandomCard(maxGold int) string

GetRandomCard returns the type id of a random card with a price lower than the given value.

func (*Session) GetResources

func (s *Session) GetResources() *ResourcesManager

GetResources returns the resources manager.

func (*Session) GetStagesCleared

func (s *Session) GetStagesCleared() int

GetStagesCleared returns the amount of stages cleared so far. Each fight represent a stage.

func (*Session) GetStatusEffect

func (s *Session) GetStatusEffect(guid string) *StatusEffect

GetStatusEffect returns status effect by guid.

func (*Session) GetStatusEffectInstance

func (s *Session) GetStatusEffectInstance(guid string) StatusEffectInstance

GetStatusEffectInstance returns status effect instance by guid.

func (*Session) GetStatusEffectOrder

func (s *Session) GetStatusEffectOrder(guid string) int

GetStatusEffectOrder returns the order value of a status effect by guid.

func (*Session) GetStatusEffectState

func (s *Session) GetStatusEffectState(guid string) string

GetStatusEffectState returns the rendered state of the status effect.

func (*Session) GiveArtifact

func (s *Session) GiveArtifact(typeId string, owner string) string

GiveArtifact gives an artifact to an actor.

func (*Session) GiveCard

func (s *Session) GiveCard(typeId string, owner string) string

GiveCard gives a card to an actor. Returns the guid of the new card.

func (*Session) GivePlayerGold

func (s *Session) GivePlayerGold(amount int)

GivePlayerGold gives the player the given amount of gold.

func (*Session) GiveStatusEffect

func (s *Session) GiveStatusEffect(typeId string, owner string, stacks int) string

GiveStatusEffect gives the owner a status effect of a certain type. Status effects are singleton per actor, so if the actor already has the status effect the stacks will be increased.

func (*Session) GobDecode

func (s *Session) GobDecode(data []byte) error

func (*Session) GobEncode

func (s *Session) GobEncode() ([]byte, error)

func (*Session) HadEvent

func (s *Session) HadEvent(id string) bool

HadEvent checks if the given event already happened in this run.

func (*Session) HadEvents

func (s *Session) HadEvents(ids []string) bool

HadEvents checks if the given events already happened in this run.

func (*Session) HadEventsAny

func (s *Session) HadEventsAny(ids []string) bool

HadEventsAny checks if at least one of the given events already happened in this run.

func (*Session) Heal

func (s *Session) Heal(source string, target string, heal int, flat bool) int

Heal will heal the target for the given amount from source to target and return the amount healed. If flat is true it will not trigger any OnHealCalc callbacks which modify the heal.

func (*Session) LeaveMerchant

func (s *Session) LeaveMerchant()

LeaveMerchant finishes the merchant state and lets the storyteller decide what to do next.

func (*Session) LetTellerDecide

func (s *Session) LetTellerDecide()

LetTellerDecide lets the currently active storyteller decide what the next game state will be.

func (*Session) LoadSavedState

func (s *Session) LoadSavedState(save SavedState)

LoadSavedState applies a saved state to the session. This will overwrite all game related data, but not the lua state, logging etc. This also means that for a save file to work the same lua scripts should be loaded or the state could be corrupted.

func (*Session) Log

func (s *Session) Log(t LogType, msg string)

Log adds a log entry to the session.

func (*Session) LuaDocs

func (s *Session) LuaDocs() *ludoc.Docs

LuaDocs returns the documentation of the lua state.

func (*Session) LuaErrors

func (s *Session) LuaErrors() chan LuaError

LuaErrors returns a channel that will receive all lua errors that happen during the session. Only a single channel is used for all errors, so be wary when using this in multiple goroutines.

func (*Session) MarkState

func (s *Session) MarkState() StateCheckpointMarker

MarkState creates a checkpoint of the session state that can be used to diff and see what happened between two points in time.

func (*Session) PlayerBuyArtifact

func (s *Session) PlayerBuyArtifact(t string) bool

PlayerBuyArtifact buys the artifact with the given type id. The artifact needs to be in the wares of the merchant.

func (*Session) PlayerBuyCard

func (s *Session) PlayerBuyCard(t string) bool

PlayerBuyCard buys the card with the given type id. The card needs to be in the wares of the merchant.

func (*Session) PlayerCastHand

func (s *Session) PlayerCastHand(i int, target string) error

PlayerCastHand casts a card from the players hand.

func (*Session) PlayerDrawCard

func (s *Session) PlayerDrawCard(amount int)

PlayerDrawCard draws a card from the deck.

func (*Session) PlayerGiveActionPoints

func (s *Session) PlayerGiveActionPoints(amount int)

PlayerGiveActionPoints gives the player action points.

func (*Session) PushRandomHistory added in v0.1.5

func (s *Session) PushRandomHistory(id string)

func (*Session) PushState

func (s *Session) PushState(events map[StateEvent]any)

PushState pushes a new state to the session. New states are relevant information like damage done, money received, actor death etc.

func (*Session) RemoveActor

func (s *Session) RemoveActor(id string)

RemoveActor removes an actor from the session.

func (*Session) RemoveAllStatusEffects

func (s *Session) RemoveAllStatusEffects()

RemoveAllStatusEffects clears all present status effects.

func (*Session) RemoveArtifact

func (s *Session) RemoveArtifact(guid string)

RemoveArtifact removes an artifact by guid.

func (*Session) RemoveCard

func (s *Session) RemoveCard(guid string)

RemoveCard removes a card by guid.

func (*Session) RemoveNonPlayer

func (s *Session) RemoveNonPlayer()

RemoveNonPlayer removes all actors that are not the player.

func (*Session) RemoveStatusEffect

func (s *Session) RemoveStatusEffect(guid string)

RemoveStatusEffect removes a status effect by guid.

func (*Session) SetEvent

func (s *Session) SetEvent(id string)

SetEvent changes the active event, but won't set the game state to EVENT. So this can be used to set the next event even before a fight or merchant interaction is over.

func (*Session) SetFightDescription

func (s *Session) SetFightDescription(description string)

SetFightDescription sets the description of the fight.

func (*Session) SetGameState

func (s *Session) SetGameState(state GameState)

SetGameState sets the game state and applies all needed setups for the new state to be valid.

func (*Session) SetOnLuaError

func (s *Session) SetOnLuaError(fn func(file string, line int, callback string, typeId string, err error))

SetOnLuaError sets the function that will be called when a lua error happens.

func (*Session) SetStatusEffectStacks

func (s *Session) SetStatusEffectStacks(guid string, stacks int)

SetStatusEffectStacks sets the stacks of a certain status effect by guid.

func (*Session) SetupFight

func (s *Session) SetupFight()

SetupFight setups the fight state, which means removing all leftover status effects, cleaning the state drawing the initial hand size and trigger the first wave of OnPlayerTurn callbacks.

Additionally, this will create a save file as this is a clean state to save.

func (*Session) SetupMerchant

func (s *Session) SetupMerchant()

SetupMerchant sets up the merchant, which means generating a new face, text and initial wares.

func (*Session) SimulateDealDamage added in v0.1.8

func (s *Session) SimulateDealDamage(source string, target string, damage int, flat bool) int

SimulateDealDamage will simulate damage to a target. If flat is true it will not trigger any callbacks which modify the damage.

func (*Session) Store

func (s *Session) Store(key string, value any)

Store stores a value in the session context.

func (*Session) ToSVG

func (s *Session) ToSVG() ([]byte, string, error)

ToSVG creates an SVG representation from the internal state. The returned string is the d2 representation of the SVG (https://d2lang.com/).

func (*Session) ToSavedState

func (s *Session) ToSavedState() SavedState

ToSavedState creates a saved state of the session that can be serialized with Gob.

func (*Session) TraverseArtifactsStatus

func (s *Session) TraverseArtifactsStatus(guids []string, artifact func(instance ArtifactInstance, artifact *Artifact), status func(instance StatusEffectInstance, statusEffect *StatusEffect))

TraverseArtifactsStatus traverses all artifacts and status effects in the session and calls the given functions for each instance. The instances are sorted by their order value. The order value is based on the order that is specified in the game data. This allows the game data to control the order of effects.

func (*Session) TriggerHooks added in v0.1.8

func (s *Session) TriggerHooks(hook Hook)

TriggerHooks triggers all hooks of a certain type.

func (*Session) UpdateActor

func (s *Session) UpdateActor(id string, update func(actor *Actor) bool)

UpdateActor updates an actor. If the update function returns true the actor will be updated.

func (*Session) UpdatePlayer

func (s *Session) UpdatePlayer(update func(actor *Actor) bool)

UpdatePlayer updates the player using a update function.

func (*Session) UpgradeCard

func (s *Session) UpgradeCard(guid string) bool

UpgradeCard upgrades a card by its GUID.

func (*Session) UpgradeRandomCard

func (s *Session) UpgradeRandomCard(owner string) bool

UpgradeRandomCard upgrades a random card of the given owner.

type StateCheckpoint

type StateCheckpoint struct {
	Session *Session

	// Events describe the events that
	Events map[StateEvent]any
}

StateCheckpoint saves the state of a session at a certain point. This can be used to retroactively check what happened between certain actions.

type StateCheckpointMarker

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

StateCheckpointMarker is a saved state of a checkpoint log.

func (StateCheckpointMarker) Diff

func (sm StateCheckpointMarker) Diff(session *Session) []StateCheckpoint

Diff returns the new states that happened between the marker and a new session.

func (StateCheckpointMarker) DiffEvent

func (sm StateCheckpointMarker) DiffEvent(session *Session, event StateEvent) []StateCheckpoint

DiffEvent returns the new states that happened between the marker and a new session that contain a certain event.

type StateEvent

type StateEvent string

type StateEventArtifactAddedData added in v0.1.8

type StateEventArtifactAddedData struct {
	Owner  string
	GUID   string
	TypeID string
}

type StateEventArtifactRemovedData added in v0.1.8

type StateEventArtifactRemovedData struct {
	Owner  string
	GUID   string
	TypeID string
}

type StateEventCardAddedData added in v0.1.8

type StateEventCardAddedData struct {
	Owner  string
	GUID   string
	TypeID string
}

type StateEventCardRemovedData added in v0.1.8

type StateEventCardRemovedData struct {
	Owner  string
	GUID   string
	TypeID string
}

type StateEventDamageData

type StateEventDamageData struct {
	Source string
	Target string
	Damage int
}

type StateEventDeathData

type StateEventDeathData struct {
	Source string
	Target string
	Damage int
}

type StateEventHealData

type StateEventHealData struct {
	Target string
	Damage int
}

type StateEventMoneyData

type StateEventMoneyData struct {
	Target string
	Money  int
}

type StatusEffect

type StatusEffect struct {
	ID          string
	Name        string
	Description string
	State       luhelp.OwnedCallback
	Look        string
	Foreground  string
	Order       int
	CanStack    bool
	Decay       DecayBehaviour
	Rounds      int
	Callbacks   map[string]luhelp.OwnedCallback
	Test        luhelp.OwnedCallback
	BaseGame    bool
}

type StatusEffectInstance

type StatusEffectInstance struct {
	GUID         string
	TypeID       string
	Owner        string
	Stacks       int
	RoundsLeft   int
	RoundEntered int
}

type StoryTeller

type StoryTeller struct {
	ID       string
	Active   luhelp.OwnedCallback
	Decide   luhelp.OwnedCallback
	BaseGame bool
}

type StringSet

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

StringSet represents a string set that can be serialized by Gob.

Note: As the GobDecode needs to overwrite its receiver we need to have the map behind a struct pointer.

func NewStringSet

func NewStringSet() *StringSet

func (*StringSet) Add

func (s *StringSet) Add(val string)

func (*StringSet) Append

func (s *StringSet) Append(vals ...string)

func (*StringSet) Clear

func (s *StringSet) Clear()

func (*StringSet) Clone

func (s *StringSet) Clone() *StringSet

func (*StringSet) GobDecode

func (s *StringSet) GobDecode(data []byte) error

func (*StringSet) GobEncode

func (s *StringSet) GobEncode() ([]byte, error)

func (*StringSet) Has

func (s *StringSet) Has(val string) bool

func (*StringSet) Remove

func (s *StringSet) Remove(val string)

func (*StringSet) ToSlice

func (s *StringSet) ToSlice() []string

type Trigger added in v0.1.8

type Trigger int

Trigger represents for which objects a event should be triggered.

type TriggerCallbackState added in v0.1.8

type TriggerCallbackState struct {
	Callback string
	Who      Trigger
	AddedCtx Context
	Ctx      []any
	Done     bool
}

TriggerCallbackState represents the internal state of a trigger callback.

func (TriggerCallbackState) SetAddedCtx added in v0.1.8

func (TriggerCallbackState) SetCtx added in v0.1.8

func (TriggerCallbackState) SetDone added in v0.1.8

Jump to

Keyboard shortcuts

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