Documentation
¶
Index ¶
- Constants
- Variables
- func AclauseWin(adj LexItem)
- func AddToVocab(wrd string, typ WordTyp)
- func AnyFlagIn(required, actual Flags) bool
- func BuildObjIndex()
- func BuildObjectTree()
- func BuildVocabulary(commands []Syntax, buzzWords []string, synonyms map[string]string)
- func CanNotOrphan()
- func CantUse(idx int)
- func Clause(idx int, wrd LexItem) (bool, int)
- func Clocker() bool
- func HandleNumber(idx int)
- func ITakeCheck(tbl []*Object, ibits LocFlags) bool
- func InitReader()
- func IsAccessible(obj *Object) bool
- func IsFlaming(obj *Object) bool
- func IsHeld(obj *Object) bool
- func IsInGlobal(obj1, obj2 *Object) bool
- func IsLit(room *Object, rmChk bool) bool
- func IsOpenable(obj *Object) bool
- func IsThisIt(obj *Object) bool
- func MainLoop()
- func ManyCheck() bool
- func NclauseWin()
- func ObjToIdx(o *Object) int
- func Orphan(first, second *Syntax)
- func OrphanMerge()
- func Parse() bool
- func PickOne(data RndSelect) string
- func Printf(format string, a ...interface{})
- func Prob(base int, isLooser bool) bool
- func Quit()
- func RFatal() bool
- func ResetGameState()
- func ResetObjectTree()
- func SnarfObjects() bool
- func SyntaxCheck() bool
- func TakeCheck() bool
- func ThingPrint(isDirect, isThe bool)
- func Tokenize(buf string) []string
- func UnknownWord(idx int)
- func Verify() bool
- func WhichPrint(isDirect bool, tbl []*Object)
- func Zprob(base int) bool
- type Action
- type ActionArg
- type ActionVerb
- type AgainProps
- type CDir
- type ClauseProps
- type ClauseTyp
- type ClockEvent
- type CombatData
- type Direction
- type ExitProps
- type FDir
- type FindProps
- type FindTyp
- type Flags
- type GameState
- type GetObjTyp
- type ItemData
- type LexItem
- type LocFlag
- type LocFlags
- type NotHereProps
- type ObjProp
- type Object
- func ButMerge(tbl []*Object) []*Object
- func DoSL(obj *Object, f1, f2 LocFlag) []*Object
- func FindWhatIMean(objFlags Flags, locFlags LocFlags, prep string) *Object
- func GetObject(isDirect, vrb bool) []*Object
- func GlobalCheck() []*Object
- func IdxToObj(idx int) *Object
- func MetaLoc(obj *Object) *Object
- func Random(tbl []*Object) *Object
- func SearchList(obj *Object, typ FindTyp) []*Object
- func Snarfem(isDirect bool, wrds []LexItem) []*Object
- func (o *Object) AddChild(child *Object)
- func (o *Object) GetCapacity() int
- func (o *Object) GetExit(d Direction) (ExitProps, bool)
- func (o *Object) GetSize() int
- func (o *Object) GetStrength() int
- func (o *Object) GetTValue() int
- func (o *Object) GetValue() int
- func (o *Object) GetVehType() Flags
- func (o *Object) Give(f Flags)
- func (o *Object) Has(f Flags) bool
- func (o *Object) HasChildren() bool
- func (o *Object) Is(wrd string) bool
- func (o *Object) IsIn(loc *Object) bool
- func (o *Object) Location() *Object
- func (o *Object) MoveTo(dest *Object)
- func (o *Object) Remove()
- func (o *Object) RemoveChild(obj *Object)
- func (o *Object) SetCapacity(v int)
- func (o *Object) SetExit(d Direction, dp ExitProps)
- func (o *Object) SetSize(v int)
- func (o *Object) SetStrength(v int)
- func (o *Object) SetTValue(v int)
- func (o *Object) SetValue(v int)
- func (o *Object) SetVehType(v Flags)
- func (o *Object) Take(f Flags)
- type OopsProps
- type ParseProps
- type ParseTbl
- type PerformResult
- type PseudoObj
- type RNG
- type ReserveProps
- type RndSelect
- type Syntax
- type VehicleData
- type VerbAction
- type WordItem
- type WordTyp
- type WordTypes
Constants ¶
const (
MaxQueueEvents = 30
)
const ( // NumUndef is the sentinel value for "no continuation index". NumUndef int = -1 )
Variables ¶
var AllDirections = []Direction{ North, South, East, West, NorthEast, NorthWest, SouthEast, SouthWest, Up, Down, In, Out, Land, }
AllDirections is the list of all valid directions.
var Commands []Syntax
Commands holds the game's syntax definitions. Set by the game package during initialization and used by the parser's SyntaxCheck.
var ObjIndex map[*Object]int
ObjIndex maps each *Object in G.AllObjects to its index. Built lazily.
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 ¶
AddToVocab adds a word with its type to the global Vocabulary map.
func AnyFlagIn ¶
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 ¶
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 HandleNumber ¶
func HandleNumber(idx int)
HandleNumber converts the lex item pointed to by idx into a number if possible.
func ITakeCheck ¶
ITakeCheck performs the implicit-take check for a list of objects.
func IsAccessible ¶
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 IsInGlobal ¶
IsInGlobal checks if obj1 appears in obj2's Global list.
func IsOpenable ¶
IsOpenable returns true if the object is a door or container.
func IsThisIt ¶
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 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 ¶
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 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 ¶
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 WhichPrint ¶
WhichPrint outputs all of the possible matches when the game parser matches multiple game objects.
Types ¶
type Action ¶
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 ¶
ActionVerb stores both the normalized and original forms of the current verb.
type AgainProps ¶
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 ¶
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 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.
func StringToDir ¶
StringToDir maps a direction name to a Direction value. Returns the direction and true if found, or -1 and false if not.
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.).
type FDir ¶
type FDir func() *Object
FDir is a function-based room exit that computes the destination dynamically.
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 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 ¶
LexItem is an object that is returned after lexing
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 )
type LocFlags ¶
type LocFlags uint8
LocFlags is a set of LocFlag constraints.
type NotHereProps ¶
NotHereProps stores synonym/adjective data for the "not here" object.
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 ¶
ButMerge filters an object list, keeping only those that appear in the "but" exclusion list.
func DoSL ¶
DoSL performs a specific game object search based on the provided location flags and parameters defined in the Search global variable.
func FindWhatIMean ¶
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 GlobalCheck ¶
func GlobalCheck() []*Object
GlobalCheck looks through global objects if any match the parameters defined in the Search global variable
func IdxToObj ¶
IdxToObj returns the object at the given index in G.AllObjects, or nil if out of range.
func MetaLoc ¶
MetaLoc returns the game objects top most location in the object's hierarchy tree which can either be a room or the GlobalObjects.
func SearchList ¶
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 (*Object) AddChild ¶
AddChild adds a child to this object's children list (no-op if already present).
func (*Object) GetCapacity ¶
GetCapacity returns the container capacity, or 0 if the object has no ItemData.
func (*Object) GetStrength ¶
GetStrength returns the combat strength, or 0 if the object has no CombatData.
func (*Object) GetTValue ¶
GetTValue returns the treasure value, or 0 if the object has no ItemData.
func (*Object) GetVehType ¶
GetVehType returns the vehicle type flags, or 0 if the object has no VehicleData.
func (*Object) HasChildren ¶
HasChildren checks if the game object has any children
func (*Object) MoveTo ¶
MoveTo removes the object from its current parent and places it inside dest.
func (*Object) RemoveChild ¶
RemoveChild removes a direct child from this object's children list.
func (*Object) SetCapacity ¶
SetCapacity sets the container capacity, allocating ItemData if needed.
func (*Object) SetExit ¶
SetExit sets exit properties for a direction, initializing the map if needed.
func (*Object) SetStrength ¶
SetStrength sets the combat strength, allocating CombatData if needed.
func (*Object) SetVehType ¶
SetVehType sets the vehicle type flags, allocating VehicleData if needed.
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.
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 RNG ¶
RNG abstracts random number generation so tests can inject a deterministic source. The single method matches math/rand.Rand.Intn.
type ReserveProps ¶
ReserveProps holds a buffered continuation for multi-command input.
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 ¶
GetActionVerb returns the full verb string including its preposition.
func (*Syntax) GetNormVerb ¶
GetNormVerb returns the normalized verb key for action dispatch.
func (*Syntax) NumObjects ¶
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 ¶
VerbAction is a handler function invoked when a verb is performed.
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 )