engine

package
v0.0.0-...-1640d1c Latest Latest
Warning

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

Go to latest
Published: Feb 9, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MaxQueueEvents = 30
)
View Source
const (
	// NumUndef is the sentinel value for "no continuation index".
	NumUndef int = -1
)

Variables

AllDirections is the list of all valid directions.

View Source
var Commands []Syntax

Commands holds the game's syntax definitions. Set by the game package during initialization and used by the parser's SyntaxCheck.

View Source
var ObjIndex map[*Object]int

ObjIndex maps each *Object in G.AllObjects to its index. Built lazily.

View Source
var Vocabulary = make(map[string]WordItem)

Vocabulary maps known words to their lexical data. Populated during initialization.

Functions

func AclauseWin

func AclauseWin(adj LexItem)

AclauseWin resolves an adjective clause by inserting the adjective into the orphaned syntax.

func AddToVocab

func AddToVocab(wrd string, typ WordTyp)

AddToVocab adds a word with its type to the global Vocabulary map.

func AnyFlagIn

func AnyFlagIn(required, actual Flags) bool

AnyFlagIn returns true if required is zero (no requirement) or if any bit in required is also set in actual.

func BuildObjIndex

func BuildObjIndex()

BuildObjIndex populates the ObjIndex map from G.AllObjects. It is idempotent and only builds the index once.

func BuildObjectTree

func BuildObjectTree()

BuildObjectTree populates each object's children from G.AllObjects.

func BuildVocabulary

func BuildVocabulary(commands []Syntax, buzzWords []string, synonyms map[string]string)

BuildVocabulary builds the vocabulary and action maps from the provided game-specific data. The game package calls this during initialization.

func CanNotOrphan

func CanNotOrphan()

CanNotOrphan prints an error when disambiguation is not possible for NPCs.

func CantUse

func CantUse(idx int)

CantUse reports that a word was used in an unrecognizable way.

func Clause

func Clause(idx int, wrd LexItem) (bool, int)

Clause parses an object clause starting at idx. Returns (ok, endIdx).

func Clocker

func Clocker() bool

Clocker runs all active clock events. Called once per turn.

func HandleNumber

func HandleNumber(idx int)

HandleNumber converts the lex item pointed to by idx into a number if possible.

func ITakeCheck

func ITakeCheck(tbl []*Object, ibits LocFlags) bool

ITakeCheck performs the implicit-take check for a list of objects.

func InitReader

func InitReader()

InitReader initializes the buffered reader from GameInput.

func IsAccessible

func IsAccessible(obj *Object) bool

IsAccessible returns if the game object can be touched by the current (winner) character. In most cases the current (winner) character is the player.

func IsFlaming

func IsFlaming(obj *Object) bool

IsFlaming returns true if the object is an active fire source.

func IsHeld

func IsHeld(obj *Object) bool

IsHeld checks if an object is held (directly or indirectly) by the winner.

func IsInGlobal

func IsInGlobal(obj1, obj2 *Object) bool

IsInGlobal checks if obj1 appears in obj2's Global list.

func IsLit

func IsLit(room *Object, rmChk bool) bool

IsLit checks if the current game room is lit.

func IsOpenable

func IsOpenable(obj *Object) bool

IsOpenable returns true if the object is a door or container.

func IsThisIt

func IsThisIt(obj *Object) bool

IsThisIt checks if the provided game object matches search parameters defined the the Search global variable.

func MainLoop

func MainLoop()

MainLoop runs the main parse-perform-clock cycle until the game ends.

func ManyCheck

func ManyCheck() bool

ManyCheck rejects multiple objects when the syntax doesn't allow them.

func NclauseWin

func NclauseWin()

NclauseWin resolves a noun clause by replacing the orphaned clause with new tokens.

func ObjToIdx

func ObjToIdx(o *Object) int

ObjToIdx returns the index of an object in G.AllObjects, or -1 if nil/unknown.

func Orphan

func Orphan(first, second *Syntax)

Orphan saves the current parse state for later disambiguation.

func OrphanMerge

func OrphanMerge()

OrphanMerge merges the current input with a previously orphaned (incomplete) command.

func Parse

func Parse() bool

Parse reads player input, tokenizes it, and resolves verb, objects, and syntax. Returns true if a valid command was parsed.

func PickOne

func PickOne(data RndSelect) string

PickOne selects a random string from data without repeating until all have been used.

func Printf

func Printf(format string, a ...interface{})

Printf writes formatted output to the game's output writer.

func Prob

func Prob(base int, isLooser bool) bool

Prob returns true with the given probability (0-100).

func Quit

func Quit()

Quit signals that the game should exit.

func RFatal

func RFatal() bool

RFatal signals a fatal action result (equivalent to ZIL's <RFATAL>).

func ResetGameState

func ResetGameState()

ResetGameState creates a fresh GameState with all defaults and restores the object tree. Tests and restart use this to get a clean game.

func ResetObjectTree

func ResetObjectTree()

ResetObjectTree restores every object to its original state and rebuilds the children tree. Used by tests to get a fresh game state.

func SnarfObjects

func SnarfObjects() bool

SnarfObjects resolves token clauses into concrete object lists.

func SyntaxCheck

func SyntaxCheck() bool

SyntaxCheck tries to find a matching syntax based on the parsed syntax.

func TakeCheck

func TakeCheck() bool

TakeCheck verifies that objects requiring possession are held or can be taken.

func ThingPrint

func ThingPrint(isDirect, isThe bool)

ThingPrint outputs the textual description of the parsed object clause.

func Tokenize

func Tokenize(buf string) []string

Tokenize splits raw input into whitespace-delimited tokens, separating letters, digits, and punctuation.

func UnknownWord

func UnknownWord(idx int)

UnknownWord reports an unrecognized word and records it for OOPS.

func Verify

func Verify() bool

Verify checks the integrity of the game file.

func WhichPrint

func WhichPrint(isDirect bool, tbl []*Object)

WhichPrint outputs all of the possible matches when the game parser matches multiple game objects.

func Zprob

func Zprob(base int) bool

Zprob is the "loser" version of Prob that accounts for the Lucky flag.

Types

type Action

type Action func(ActionArg) bool

Action is a handler function attached to a game object, invoked with a context argument.

type ActionArg

type ActionArg int

ActionArg represents an argument enum that is passed to Action functions.

const (
	ActUnk ActionArg = iota
	ActBegin
	ActEnter
	ActLook
	ActFlash
	ActObjDesc
	ActEnd

	// Combat modes — passed to NPC Action handlers by the fight system.
	ActBusy        // villain acts alone (player not present)
	ActDead        // villain has been killed
	ActUnconscious // villain knocked unconscious
	ActConscious   // villain regains consciousness
	ActFirst       // villain's first-strike check
)

type ActionVerb

type ActionVerb struct {
	Norm string
	Orig string
}

ActionVerb stores both the normalized and original forms of the current verb.

type AgainProps

type AgainProps struct {
	Buf    []LexItem
	Dir    Direction
	HasDir bool
}

AgainProps stores the previous command for AGAIN / G repetition.

type CDir

type CDir func() bool

CDir is a conditional exit check that returns true if passage is allowed.

type ClauseProps

type ClauseProps struct {
	Type ClauseTyp
	Syn  LexItem
	Adj  LexItem
}

ClauseProps describes an adjective-disambiguating clause for the parser.

func (ClauseProps) IsSet

func (cp ClauseProps) IsSet() bool

IsSet returns true if this clause has been populated.

type ClauseTyp

type ClauseTyp int

ClauseTyp identifies which object clause is being resolved.

const (
	// ClauseUnk means no clause is active.
	ClauseUnk ClauseTyp = iota
	// Clause1 refers to the first object clause.
	Clause1
	// Clause2 refers to the second object clause.
	Clause2
)

type ClockEvent

type ClockEvent struct {
	Key  string      // unique identifier for this event
	Run  bool        // whether the event is active
	Tick int         // countdown; fires when it reaches 0
	Fn   func() bool // the function to call when the event fires
}

ClockEvent represents a timed or daemon interrupt in the game's event queue.

func Queue

func Queue(key string, tick int) *ClockEvent

Queue finds (or creates) a clock event by key and sets its tick value.

func QueueInt

func QueueInt(key string, dmn bool) *ClockEvent

QueueInt finds an existing clock event by key, or allocates a new slot. If dmn is true, the event is a daemon (always ticked, even on bad parses).

type CombatData

type CombatData struct {
	Strength int // combat strength (higher = tougher)
}

CombatData holds properties specific to NPCs that participate in combat.

type Direction

type Direction int

Direction represents a compass direction or vertical movement.

const (
	North Direction = iota
	South
	East
	West
	NorthEast
	NorthWest
	SouthEast
	SouthWest
	Up
	Down
	In
	Out
	Land
	NumDirections // sentinel — must be last
)

func StringToDir

func StringToDir(s string) (Direction, bool)

StringToDir maps a direction name to a Direction value. Returns the direction and true if found, or -1 and false if not.

func (Direction) String

func (d Direction) String() string

String returns the canonical name of the direction.

type ExitProps

type ExitProps struct {
	NExit    string
	UExit    bool
	RExit    *Object
	FExit    FDir
	CExit    CDir
	CExitStr string
	DExit    *Object
	DExitStr string
}

ExitProps describes how a room exit works (unconditional, conditional, etc.).

func (ExitProps) IsSet

func (dp ExitProps) IsSet() bool

IsSet returns true if any exit data has been configured.

type FDir

type FDir func() *Object

FDir is a function-based room exit that computes the destination dynamically.

type FindProps

type FindProps struct {
	ObjFlags Flags
	LocFlags LocFlags
	Syn      LexItem
	Adj      LexItem
}

FindProps holds the current search criteria for object resolution.

type FindTyp

type FindTyp int

FindTyp controls the depth of object tree searches.

const (
	// FindAll searches the entire subtree.
	FindAll FindTyp = iota
	// FindTop searches only direct children.
	FindTop
	// FindBottom searches only nested (non-direct) children.
	FindBottom
)

type Flags

type Flags uint64

Flags represents a bitfield of properties that game objects can have.

const (
	// FlgUnk means the value is undefined (zero value, no bits set).
	FlgUnk Flags = 0

	// FlgTake means the object can be picked up by the player.
	FlgTake Flags = 1 << iota
	// FlgTryTake means the object shouldn't be implicitly taken.
	FlgTryTake
	// FlgCont means the object can contain other objects.
	FlgCont
	// FlgDoor means the object is a door.
	FlgDoor
	// FlgOpen means the object can be opened.
	FlgOpen
	// FlgSurf refers to objects such as table, desk, countertop.
	FlgSurf
	// FlgLock means the object is locked and can't be implicitly opened.
	FlgLock
	// FlgWear means the object can be worn by the player.
	FlgWear
	// FlgWorn means the object is currently being worn by the player.
	FlgWorn
	// FlgRead means the object can be read.
	FlgRead
	// FlgLight means the object can be turned on/off.
	FlgLight
	// FlgOn means the object's properties such as Light or Flame are turned on.
	FlgOn
	// FlgFlame means the object can be a source of fire.
	FlgFlame
	// FlgBurn means the object can be burnt.
	FlgBurn
	// FlgTrans means the objects inside can be seen even when it's closed.
	FlgTrans
	// FlgNoDesc means the object shouldn't be described.
	FlgNoDesc
	// FlgInvis means the object shouldn't be found.
	FlgInvis
	// FlgTouch means the object has interacted with the player.
	FlgTouch
	// FlgSearch means to find anything in the object the parser should look as deep as possible.
	FlgSearch
	// FlgVeh means the object can transport the player.
	FlgVeh
	// FlgPerson means the object is a character.
	FlgPerson
	// FlgFemale means the object is a female character.
	FlgFemale
	// FlgVowel means the object's description starts with a vowel.
	FlgVowel
	// FlgNoArt means the object's description doesn't work with articles.
	FlgNoArt
	// FlgPlural means the object's description is a plural noun.
	FlgPlural
	// FlgLand means the object is a dry land room.
	FlgLand
	// FlgWater means the object is a water room.
	FlgWater
	// FlgAir means the object is a room mid-air.
	FlgAir
	// FlgOut means the object is an outdoors room.
	FlgOut
	// FlgIntegral means the object is an integral part of another object.
	FlgIntegral
	// FlgBodyPart means the object is a body part.
	FlgBodyPart
	// FlgNotAll means the object shouldn't be taken when taking all.
	FlgNotAll
	// FlgDrop means if dropping objects in the vehicle the object should stay in the vehicle.
	FlgDrop
	// FlgIn means the player should stay in the vehicle rather than on.
	FlgIn
	// FlgKludge is a syntax flag which can be used to support a syntax VERB PREPOSITION without any object.
	FlgKludge
	// FlgFight means the character is actively engaged in combat.
	FlgFight
	// FlgStaggered means the character is recovering from a blow and will skip their next attack.
	FlgStaggered
	// FlgSacred means the object is protected and cannot be stolen by the thief.
	FlgSacred
	// FlgTool means the object can be used as an implement (e.g. for digging, inflating, locking).
	FlgTool
	// FlgNonLand means the room is a non-land area.
	FlgNonLand
	// FlgMaze means the room is a maze.
	FlgMaze
	// FlgClimb means the object can be climbed.
	FlgClimb
	// FlgWeapon means the object is a weapon.
	FlgWeapon
	// FlgDrink means the object can be drunk.
	FlgDrink
	// FlgFood means the object can be eaten.
	FlgFood
	// FlgTurn means the object can be turned.
	FlgTurn
	// FlgDestroyed means the room is munged/destroyed.
	FlgDestroyed
	// FlgRLand means the room becomes dry land conditionally.
	FlgRLand
	// FlgActor means the object is an actor.
	FlgActor
)

type GameState

type GameState struct {
	// ---- Core references ----
	Here   *Object
	Winner *Object
	Player *Object

	// ---- Current command (set by parser / Perform) ----
	DirObj            *Object
	IndirObj          *Object
	ActVerb           ActionVerb
	DirObjPossibles   []*Object
	IndirObjPossibles []*Object
	DetectedSyntx     *Syntax

	// ---- Game progress ----
	Moves     int
	Score     int
	BaseScore int
	Lit       bool

	// ---- Settings ----
	SuperBrief bool
	Verbose    bool
	Lucky      bool

	// ---- Parser internals ----
	ParserOk      bool
	Script        bool
	PerformFatal  bool
	QuitRequested bool
	AlwaysLit     bool
	Search        FindProps
	ParsedSyntx   ParseTbl
	OrphanedSyntx ParseTbl
	Params        ParseProps
	NotHere       NotHereProps
	LexRes        []LexItem
	Reserv        ReserveProps
	Again         AgainProps
	Oops          OopsProps

	// ---- Clock / interrupt queue ----
	QueueItms [MaxQueueEvents]ClockEvent
	QueueInts int
	QueueDmns int
	ClockWait bool

	// ---- I/O ----
	GameOutput     io.Writer
	GameInput      io.Reader
	Reader         *bufio.Reader
	InputExhausted bool

	// ---- RNG ----
	Rand RNG

	// ---- Save/Restore/Restart function hooks ----
	Save    func() error
	Restore func() error
	Restart func() error

	// ---- Well-known objects (set by game during init) ----
	AllObjects     []*Object // complete list of all game objects
	RoomsObj       *Object   // container for all rooms
	GlobalObj      *Object   // global objects container
	LocalGlobalObj *Object   // local globals container
	NotHereObj     *Object   // sentinel for "not here" objects
	PseudoObj      *Object   // pseudo object for pseudo-object actions
	ItPronounObj   *Object   // the "it" pronoun object
	MeObj          *Object   // the "me" player-reference object
	HandsObj       *Object   // the player's hands object

	// ---- Vocabulary registries (populated by BuildVocabulary) ----
	Actions    map[string]VerbAction
	PreActions map[string]VerbAction
	NormVerbs  map[string]string

	// ---- Clock function registry (populated by game) ----
	ClockFuncs map[string]func() bool

	// ---- Game-specific callbacks (set by game during init) ----
	// ITakeFunc is the implicit-take handler called by the parser.
	ITakeFunc func(vb bool) bool

	// ---- Game-specific extension data ----
	// The game package stores its own state struct here and accesses
	// it via a type assertion (e.g. G.GameData.(*ZorkData)).
	GameData interface{}
}

GameState holds all mutable state for a single game session. Engine-generic fields live here directly; game-specific extensions are stored in the GameData field.

var G *GameState

G is the current game state. All mutable game state is accessed through this pointer, making it easy to create fresh instances for tests or save/restore without relying on scattered global variables.

func NewGameState

func NewGameState() *GameState

NewGameState creates a fresh GameState with all default values set.

type GetObjTyp

type GetObjTyp int

GetObjTyp controls how the parser resolves object references.

const (
	// GetUndef means no explicit quantifier was given.
	GetUndef GetObjTyp = iota
	// GetAll means the player said "all" / "everything".
	GetAll
	// GetOne means the player said "one" / "a".
	GetOne
	// GetInhibit suppresses object resolution.
	GetInhibit
)

type ItemData

type ItemData struct {
	Size     int // weight / bulk of the object
	Value    int // base point value (awarded on first take)
	TValue   int // remaining point value (zeroed after scoring)
	Capacity int // how many child objects this container can hold
}

ItemData holds properties specific to takeable items and containers. Only objects that can be picked up, scored, or hold other objects need this.

type LexItem

type LexItem struct {
	Norm  string
	Orig  string
	Types WordTypes
}

LexItem is an object that is returned after lexing

func Lex

func Lex(toks []string) []LexItem

Lex looks up each token in the Vocabulary and returns tagged LexItem entries.

func Read

func Read() (string, []LexItem)

Read reads input from the game input, tokenizes the input and tags parts-of-speech.

func (*LexItem) Clear

func (e *LexItem) Clear()

Clear resets the item to its zero state.

func (*LexItem) Is

func (e *LexItem) Is(wrd string) bool

Is returns true if the normalized form equals wrd.

func (*LexItem) IsAny

func (e *LexItem) IsAny(wrds ...string) bool

IsAny returns true if the normalized form matches any of the given words.

func (*LexItem) IsSet

func (e *LexItem) IsSet() bool

IsSet returns true if the item has been populated with data.

func (*LexItem) Matches

func (e *LexItem) Matches(itm LexItem) bool

Matches returns true if both items have the same norm and types.

func (*LexItem) Set

func (e *LexItem) Set(itm LexItem)

Set copies another LexItem's data into this one.

type LocFlag

type LocFlag uint8

LocFlag represents a single location constraint for parser object resolution.

const (
	// LocHeld means the object must be directly held by the actor.
	LocHeld LocFlag = 1 << iota
	// LocCarried means the object must be carried (held or in a carried container).
	LocCarried
	// LocInRoom means the object must be in the current room.
	LocInRoom
	// LocOnGrnd means the object must be on the ground.
	LocOnGrnd
	// LocTake means the parser may attempt an implicit take.
	LocTake
	// LocMany means multiple direct objects are allowed.
	LocMany
	// LocHave means the object must already be possessed.
	LocHave
)

func (LocFlag) In

func (lf LocFlag) In(flgs LocFlags) bool

In returns true if this flag appears in the given flag set.

type LocFlags

type LocFlags uint8

LocFlags is a set of LocFlag constraints.

func LocSet

func LocSet(flags ...LocFlag) LocFlags

LocSet builds a LocFlags bitset from a list of flags.

func (*LocFlags) All

func (lfs *LocFlags) All() LocFlags

All replaces the set with every possible LocFlag value.

func (LocFlags) HasAll

func (lfs LocFlags) HasAll() bool

HasAll returns true if all LocFlag values are present.

type NotHereProps

type NotHereProps struct {
	Syn LexItem
	Adj LexItem
}

NotHereProps stores synonym/adjective data for the "not here" object.

type ObjProp

type ObjProp struct {
	ObjFlags Flags
	LocFlags LocFlags
	HasObj   bool
}

ObjProp describes the expected properties of an object slot in a syntax definition.

type Object

type Object struct {
	// ---- Core identity (all objects) ----
	Flags      Flags
	In         *Object
	Children   []*Object
	Synonyms   []string
	Adjectives []string
	Desc       string
	LongDesc   string
	FirstDesc  string
	Text       string

	// ---- Behavior ----
	Action  Action
	ContFcn Action
	DescFcn Action

	// ---- Scope / parser hints ----
	Global []*Object
	Pseudo []PseudoObj

	// ---- Room data ----
	Exits map[Direction]ExitProps

	// ---- Optional facets (nil when not applicable) ----
	Item    *ItemData    // non-nil for takeable items / containers
	Combat  *CombatData  // non-nil for NPCs that fight
	Vehicle *VehicleData // non-nil for vehicles
}

Object represents a game object which can be a character, room, vehicle etc. Role-specific data is stored in optional facet pointers that are nil when not applicable, keeping the core struct lean.

func ButMerge

func ButMerge(tbl []*Object) []*Object

ButMerge filters an object list, keeping only those that appear in the "but" exclusion list.

func DoSL

func DoSL(obj *Object, f1, f2 LocFlag) []*Object

DoSL performs a specific game object search based on the provided location flags and parameters defined in the Search global variable.

func FindWhatIMean

func FindWhatIMean(objFlags Flags, locFlags LocFlags, prep string) *Object

FindWhatIMean attempts to resolve a single object from context when the player omitted a noun. Returns nil if the resolution is ambiguous or fails.

func GetObject

func GetObject(isDirect, vrb bool) []*Object

GetObject resolves the current search criteria into matching objects.

func GlobalCheck

func GlobalCheck() []*Object

GlobalCheck looks through global objects if any match the parameters defined in the Search global variable

func IdxToObj

func IdxToObj(idx int) *Object

IdxToObj returns the object at the given index in G.AllObjects, or nil if out of range.

func MetaLoc

func MetaLoc(obj *Object) *Object

MetaLoc returns the game objects top most location in the object's hierarchy tree which can either be a room or the GlobalObjects.

func Random

func Random(tbl []*Object) *Object

Random returns a uniformly random element from the given object slice.

func SearchList

func SearchList(obj *Object, typ FindTyp) []*Object

SearchList traverses the game object tree down and looks for game objects that match search parameters defined in the Search global variable. It returns a list of all found game objects.

func Snarfem

func Snarfem(isDirect bool, wrds []LexItem) []*Object

Snarfem resolves a single token clause into a list of matching objects.

func (*Object) AddChild

func (o *Object) AddChild(child *Object)

AddChild adds a child to this object's children list (no-op if already present).

func (*Object) GetCapacity

func (o *Object) GetCapacity() int

GetCapacity returns the container capacity, or 0 if the object has no ItemData.

func (*Object) GetExit

func (o *Object) GetExit(d Direction) (ExitProps, bool)

GetExit returns the direction properties for the given direction.

func (*Object) GetSize

func (o *Object) GetSize() int

GetSize returns the item size, or 0 if the object has no ItemData.

func (*Object) GetStrength

func (o *Object) GetStrength() int

GetStrength returns the combat strength, or 0 if the object has no CombatData.

func (*Object) GetTValue

func (o *Object) GetTValue() int

GetTValue returns the treasure value, or 0 if the object has no ItemData.

func (*Object) GetValue

func (o *Object) GetValue() int

GetValue returns the scoring value, or 0 if the object has no ItemData.

func (*Object) GetVehType

func (o *Object) GetVehType() Flags

GetVehType returns the vehicle type flags, or 0 if the object has no VehicleData.

func (*Object) Give

func (o *Object) Give(f Flags)

Give sets the given flag bits on the object.

func (*Object) Has

func (o *Object) Has(f Flags) bool

Has returns true if any of the given flag bits are set.

func (*Object) HasChildren

func (o *Object) HasChildren() bool

HasChildren checks if the game object has any children

func (*Object) Is

func (o *Object) Is(wrd string) bool

Is returns true if wrd appears in the object's synonyms or adjectives.

func (*Object) IsIn

func (o *Object) IsIn(loc *Object) bool

IsIn returns true if the object's direct parent is loc.

func (*Object) Location

func (o *Object) Location() *Object

Location returns the object's parent (container or room).

func (*Object) MoveTo

func (o *Object) MoveTo(dest *Object)

MoveTo removes the object from its current parent and places it inside dest.

func (*Object) Remove

func (o *Object) Remove()

Remove detaches the object from its parent.

func (*Object) RemoveChild

func (o *Object) RemoveChild(obj *Object)

RemoveChild removes a direct child from this object's children list.

func (*Object) SetCapacity

func (o *Object) SetCapacity(v int)

SetCapacity sets the container capacity, allocating ItemData if needed.

func (*Object) SetExit

func (o *Object) SetExit(d Direction, dp ExitProps)

SetExit sets exit properties for a direction, initializing the map if needed.

func (*Object) SetSize

func (o *Object) SetSize(v int)

SetSize sets the item size, allocating ItemData if needed.

func (*Object) SetStrength

func (o *Object) SetStrength(v int)

SetStrength sets the combat strength, allocating CombatData if needed.

func (*Object) SetTValue

func (o *Object) SetTValue(v int)

SetTValue sets the treasure value, allocating ItemData if needed.

func (*Object) SetValue

func (o *Object) SetValue(v int)

SetValue sets the scoring value, allocating ItemData if needed.

func (*Object) SetVehType

func (o *Object) SetVehType(v Flags)

SetVehType sets the vehicle type flags, allocating VehicleData if needed.

func (*Object) Take

func (o *Object) Take(f Flags)

Take clears the given flag bits on the object.

type OopsProps

type OopsProps struct {
	Unk    int
	UnkSet bool
	Idx    int
}

OopsProps tracks the unknown word for OOPS correction.

type ParseProps

type ParseProps struct {
	ObjOrClauseCnt int
	EndOnPrep      bool
	Number         int
	ShldOrphan     bool
	HasMerged      bool
	HasAnd         bool
	ItObj          *Object
	GetType        GetObjTyp
	AdjClause      ClauseProps
	Buts           []*Object
	OneObj         LexItem
	Continue       int
	InQuotes       bool
	BufLen         int
	WalkDir        Direction
	HasWalkDir     bool
}

ParseProps holds persistent parser state across turns.

type ParseTbl

type ParseTbl struct {
	Verb         LexItem
	Prep1        LexItem
	ObjOrClause1 []LexItem
	Obj1Start    int
	Obj1End      int
	Prep2        LexItem
	ObjOrClause2 []LexItem
}

ParseTbl holds the tokens and structure extracted from the player's input.

func (*ParseTbl) Clear

func (pt *ParseTbl) Clear()

Clear resets the ParseTbl to its zero state.

func (*ParseTbl) Set

func (pt *ParseTbl) Set(tbl ParseTbl)

Set copies the contents of another ParseTbl into this one.

type PerformResult

type PerformResult int

PerformResult represents the result of a Perform call.

const (
	// PerfNotHndld means no handler claimed the action.
	PerfNotHndld PerformResult = iota
	// PerfHndld means a handler processed the action.
	PerfHndld
	// PerfFatal means the action caused a fatal condition (e.g. player death).
	PerfFatal
	// PerfQuit means the player requested to quit.
	PerfQuit
)

func Perform

func Perform(a ActionVerb, o, i *Object) PerformResult

Perform dispatches an action through the handler chain (winner, room, pre-action, indirect, container, direct, and verb action handlers).

type PseudoObj

type PseudoObj struct {
	Synonym string
	Action  Action
}

PseudoObj are special game objects which only have a single synonym and an action.

type RNG

type RNG interface {
	Intn(n int) int
}

RNG abstracts random number generation so tests can inject a deterministic source. The single method matches math/rand.Rand.Intn.

type ReserveProps

type ReserveProps struct {
	Idx    int
	IdxSet bool
	Buf    []LexItem
}

ReserveProps holds a buffered continuation for multi-command input.

type RndSelect

type RndSelect struct {
	Unselected []string
	Selected   []string
}

RndSelect supports non-repeating random selection from a pool of strings.

type Syntax

type Syntax struct {
	NormVerb  string
	Verb      string
	VrbPrep   string
	Obj1      ObjProp
	ObjPrep   string
	Obj2      ObjProp
	Action    VerbAction
	PreAction VerbAction
}

Syntax defines a single command syntax pattern (verb + prepositions + object slots).

func (*Syntax) GetActionVerb

func (s *Syntax) GetActionVerb() string

GetActionVerb returns the full verb string including its preposition.

func (*Syntax) GetNormVerb

func (s *Syntax) GetNormVerb() string

GetNormVerb returns the normalized verb key for action dispatch.

func (*Syntax) IsObjPrep

func (s *Syntax) IsObjPrep(prep string) bool

IsObjPrep returns true if the object preposition matches.

func (*Syntax) IsVrbPrep

func (s *Syntax) IsVrbPrep(prep string) bool

IsVrbPrep returns true if the verb preposition matches.

func (*Syntax) NumObjects

func (s *Syntax) NumObjects() int

NumObjects returns how many object slots this syntax expects (0, 1, or 2).

type VehicleData

type VehicleData struct {
	Type Flags // e.g. FlgNonLand for boats
}

VehicleData holds properties specific to vehicles the player can ride.

type VerbAction

type VerbAction func(ActionArg) bool

VerbAction is a handler function invoked when a verb is performed.

type WordItem

type WordItem struct {
	Norm  string
	Types WordTypes
}

WordItem is the vocabulary entry for a known word.

type WordTyp

type WordTyp int

WordTyp represents the part-of-speech type of a word.

const (
	// WordUnk is the zero value for an unrecognized word.
	WordUnk WordTyp = iota
	// WordDir indicates a compass direction (north, south, etc.).
	WordDir
	// WordVerb indicates a verb (take, open, etc.).
	WordVerb
	// WordPrep indicates a preposition (in, on, with, etc.).
	WordPrep
	// WordAdj indicates an adjective (brass, large, etc.).
	WordAdj
	// WordObj indicates a noun / object name (lamp, sword, etc.).
	WordObj
	// WordBuzz indicates a filler word that is ignored (the, a, etc.).
	WordBuzz
)

type WordTypes

type WordTypes []WordTyp

WordTypes is a list of part-of-speech tags for a single word.

func (WordTypes) Equals

func (wt WordTypes) Equals(tt WordTypes) bool

Equals returns true if both type lists contain the same elements.

func (WordTypes) Has

func (wt WordTypes) Has(typ WordTyp) bool

Has returns true if typ appears in the list.

func (WordTypes) Len

func (wt WordTypes) Len() int

Len implements sort.Interface.

func (WordTypes) Less

func (wt WordTypes) Less(i, j int) bool

Less implements sort.Interface.

func (WordTypes) Swap

func (wt WordTypes) Swap(i, j int)

Swap implements sort.Interface.

Jump to

Keyboard shortcuts

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