Files
rgoue/game/game.go
clawbot 3a01283358 fix: take the signal-time autosave on the game goroutine (closes #24)
The SIGHUP/SIGTERM handler gob-encoded the live game tree from the signal
goroutine while the game goroutine was mid-turn mutating it, and AutoSave
removed the save file before encoding — so the failure mode was not a
stale save but a deleted one followed by a possibly torn replacement,
with a window in which the player had neither. The suite has run under
-race since 2026-08-09 and was green because nothing had ever driven the
turn loop concurrently with a signal: evidence of untested, not of safe.

The handler no longer writes anything. AutoSaveOnSignal posts a request,
wakes the input read, and waits up to signalSaveTimeout for the game
goroutine to take it; the encode runs on the goroutine that owns the
state, at the three points where that goroutine can sit: between turns
(command), on waking from a blocked readchar, and while parked in the `!`
shell escape (runShellEscape, which now runs the shell on a helper
goroutine so a hangup during it still rescues the game).

Blocked on input is the case that matters — a dropped connection lands
while the player is thinking, so a flag checked only between turns would
never be looked at. Terminal.ReadChar therefore returns (byte, bool),
with ok false meaning "woken by Interrupt, no key", and term.Tcell posts
a tcell.EventInterrupt onto tcell's own event queue to unpark PollEvent.
readchar services the request and reads again, so no caller sees it.

Running the shell on a helper goroutine would also have moved
term.Tcell.ShellEscape's panic on a failed Screen.Resume onto it, and a
panic at the top of any goroutine terminates the process without running
the deferred calls of the others — including cmd/rogue/main.go's
`defer t.Fini()`. The tty would have been left raw on precisely the path
where the terminal is already broken, which is issue #12's failure on a
path this change created. runShellEscape therefore recovers the helper's
panic and re-raises it on the game goroutine, whose stack has the restore
in it, so "every path restores the terminal via Terminal.Fini before
exiting" stays true.

saveFile writes a temporary file in the save's own directory, fsyncs it
and renames it over the target instead of truncating in place, so a save
that fails — or never happens because the deadline ran out — leaves the
player's previous save whole.

What the handoff guarantees is stated exactly rather than flatteringly:
the encode runs on the state-owning goroutine, so the snapshot is
internally consistent and restorable, but it is not necessarily taken
between commands. Only the check at the top of command is; the other two
service points both sit inside a command call already under way. readchar
is reached from mid-command prompts (--More--, askOverwrite, getStr, the
direction and pack prompts) with the command's mutations already applied,
and runShellEscape is reached from shell, an ordinary '!' command handler
dispatched inside command, with that turn's DoDaemons(Before) and
DoFuses(Before) already fired and its AFTER pass not yet. Restoring
re-enters playit at the top of command, so either way the rest of that
command is lost and a fresh BEFORE pass runs on top of the one in the
snapshot.

The SIGINT/SIGQUIT no-save decision and the single-signal-read ordering
guarantee are untouched. pendingSaver reads the game out from under its
mutex rather than delegating with it held, because the delegated call now
blocks until the save is taken.
2026-08-09 07:50:23 +00:00

308 lines
9.4 KiB
Go

//nolint:mnd // C-faithful literals; names hurt C-greppability (approved 2026-07-07)
package game
// ItemLore is the per-game item identity state: the randomized appearance
// names and the seven mutable ObjInfo tables (extern.c/init.c).
type ItemLore struct {
PotColors [NumPotionTypes]string // p_colors: colors of the potions
ScrNames [NumScrollTypes]string // s_names: names of the scrolls
RingStones [NumRingTypes]string // r_stones: stone settings of the rings
WandMade [NumWandTypes]string // ws_made: what sticks are made of
WandType [NumWandTypes]string // ws_type: "wand" or "staff"
Things [NumThings]ObjInfo
Potions [NumPotionTypes]ObjInfo
Scrolls [NumScrollTypes]ObjInfo
Rings [NumRingTypes]ObjInfo
Sticks [NumWandTypes]ObjInfo
Weapons [NumWeaponTypes + 1]ObjInfo
Armors [NumArmorTypes]ObjInfo
Group int // group number for the next stack of missiles (weapons.c `group`)
}
// Options are the user-settable game options (options.c optlist).
type Options struct {
Terse bool // terse: shorter messages
FightFlush bool // flush: flush typeahead during battle
Jump bool // jump: show position only at end of run
SeeFloor bool // seefloor: show the lamp-illuminated floor
PassGo bool // passgo: follow turnings in passageways
Tombstone bool // tombstone: print tombstone when killed
InvType int // inven: inventory style (InvOver/InvSlow/InvClear)
}
// Params carries everything needed to construct a game.
type Params struct {
Seed int32 // dungeon number; caller derives it (time+pid or SEED)
Name string // player name (overridden by ROGUEOPTS name=)
RogueOpts string // the ROGUEOPTS environment string
Home string // home directory (save file default location)
ScorePath string // scoreboard file; empty disables scoring
Wizard bool // enable debug commands (implies NoScore)
Term Terminal // the display/input device; nil runs headless
}
// RogueGame is one complete game of Rogue: every piece of state that was a
// global (or file-scope static) in the C sources, plus the terminal it is
// played on. Construct with New, then call Run.
//
// The struct grows with the port; fields appear in the phase that ports the
// code owning them.
type RogueGame struct {
// identity / RNG
Rng *Rng
Dnum int // dungeon number
Whoami string // name of player
Fruit string // favorite fruit
Home string // user's home directory
FileName string // save file name
Wizard bool // true if allows wizard commands
NoScore bool // was a wizard sometime
// the world
Player Player
Level Level
Depth int // C `level`: what level she is on
MaxDepth int // C `max_level`: deepest player has gone
HasAmulet bool // C `amulet`: he found the amulet
SeenStairs bool // have seen the stairs (for lsd)
// turn/command engine
Playing bool // true until he quits
After bool // true if we want after daemons
Again bool // repeating the last command
Count int // number of times to repeat command
NoCommand int // number of turns asleep
NoMove int // number of turns held in place
Quiet int // number of quiet turns
Running bool // true if player is running
RunCh byte // direction player is running
DoorStop bool // stop running when we pass a door
Firstmove bool // first move after setting door_stop
MoveOn bool // next move shouldn't pick up items
ToDeath bool // fighting is to the death!
Kamikaze bool // to_death really to DEATH
HasHit bool // has a "hit" message pending in msg
MaxHit int // max damage done to her in to_death
Take byte // thing she is taking
Delta Coord
DirCh byte
LastComm byte
LastDir byte
LLastComm byte
LLastDir byte
LastPick *Object
LLastPick *Object
lastDelt Coord // misc.c get_dir static last_delt
// command.c statics
countCh byte
direction byte
newCount bool
// dungeon generation working state
maze mazeState // rooms.c maze statics
pnum int // passages.c passnum statics
newpnum bool
chRet Coord // chase.c static ch_ret: where chasing takes you
// daemons/fuses
Daemons DaemonList
// screen / messages
scr *Screen
Msgs MessageLine
statusCache statusCache
invPage invPage // things.c discovery-list pagination statics
// UI state
StatMsg bool // should status() print as a msg()
InvDescribe bool // say which way items are being used
QComm bool // are we executing a 'Q' command?
InShell bool // true if executing a shell
Oldpos Coord // position before last look() call
Oldrp *Room
NObjs int // # items listed in inventory() call
// options and item identity
Options Options
Items ItemLore
// Monsters is the per-game copy of the bestiary: the C code mutates
// the venus flytrap's damage string during play, and the table is
// part of the save state.
Monsters [26]MonsterKind
// scores
LastScore int
AllScore bool
ScorePath string
rogueOpts string // the ROGUEOPTS string, re-parsed by playit as in C
restored bool // game came from a save file; Run skips setup
// sigSave carries signal-triggered autosave requests from the signal
// goroutine to the game goroutine, which is the only one allowed to
// touch the state above (issue #24). Buffered by one: the handler
// reads exactly one signal, so there is never more than one request.
// See AutoSaveOnSignal and serviceAutoSaveRequest in save.go.
sigSave chan *autoSaveRequest
// data is the game's copy of the static tables (extern.c and friends).
data *gameData
}
// New builds a game from params, seeds the RNG, and randomizes the item
// appearance tables (the front half of main.c main(); the player roll-up
// and first level arrive with later porting phases).
func New(params Params) *RogueGame {
g := &RogueGame{
data: newGameData(),
Rng: &Rng{Seed: params.Seed},
Dnum: int(params.Seed),
Whoami: params.Name,
Fruit: "slime-mold",
Home: params.Home,
Wizard: params.Wizard,
NoScore: params.Wizard,
Playing: true,
Depth: 1,
ScorePath: params.ScorePath,
LastScore: -1,
sigSave: make(chan *autoSaveRequest, 1),
}
g.Options = Options{
SeeFloor: true,
Tombstone: true,
InvType: InvOver,
}
g.InvDescribe = true
g.Msgs.SaveMsg = true
g.scr = NewScreen(params.Term)
g.Msgs.attach(g.scr, g.look, g.readchar)
g.FileName = params.Home + "/rogue.save"
g.rogueOpts = params.RogueOpts
if params.Wizard {
g.Player.Flags.Set(SenseMonsters)
}
if params.RogueOpts != "" {
g.ParseOpts(params.RogueOpts)
}
g.Monsters = g.data.monsterTable
g.Items.Group = 2 // weapons.c: int group = 2
for i := range g.Level.Passages {
g.Level.Passages[i].Flags = Gone | Dark
}
g.initProbs() // set up prob tables for objects
g.initPlayer() // set up initial player stats
g.initNames() // set up names of scrolls
g.initColors() // set up colors of potions
g.initStones() // set up stone settings of rings
g.initMaterials() // set up materials of wands
return g
}
// Run plays the game to its end: the back half of main.c main() plus
// playit(). It does not return — the game ends by exiting the process
// (see myExit); one game run is one process.
func (g *RogueGame) Run() {
g.startLevel()
g.playit()
}
// startLevel draws the first level and starts the standing daemons and
// fuses for a fresh game; a restored game brings its own (the back half
// of main.c main()).
func (g *RogueGame) startLevel() {
if g.restored {
return
}
g.NewLevel() // draw current level
// Start up daemons and fuses
g.StartDaemon(DRunners, 0, After)
g.StartDaemon(DDoctor, 0, After)
g.Fuse(DSwander, 0, wanderTime(g), After)
g.StartDaemon(DStomach, 0, After)
}
// playit is the main loop of the program (main.c playit).
func (g *RogueGame) playit() {
g.prePlay()
for g.Playing {
g.command() // command execution
}
g.endit()
}
// prePlay does the option and position setup at the top of playit,
// before the command loop (main.c playit). It is split out so tests can
// drive a bounded number of turns; the loop itself never returns,
// because game-over exits the process.
func (g *RogueGame) prePlay() {
// set up defaults for modern terminals: curses' md_hasclreol() is
// always true, so the C default inventory style applies
if !g.restored {
g.Options.InvType = InvClear
}
// parse environment declaration of options (C parses ROGUEOPTS again
// here, letting it override the terminal defaults)
if g.rogueOpts != "" {
g.ParseOpts(g.rogueOpts)
}
g.Oldpos = g.Player.Pos
g.Oldrp = g.roomIn(g.Player.Pos)
}
// endit exits the game (main.c endit).
func (g *RogueGame) endit() {
g.fatal("Okay, bye bye!\n")
}
// fatal prints a message and leaves (main.c fatal).
func (g *RogueGame) fatal(s string) {
g.mvaddstr(NumLines-2, 0, s)
g.refresh()
g.myExit()
}
// quit has the player make certain, then exits (main.c quit). The final
// scoring display arrives with the endgame phase.
func (g *RogueGame) quit(int) {
// Reset the message position in case we got here via an interrupt
if !g.QComm {
g.Msgs.Mpos = 0
}
oy, ox := g.scr.Std.GetYX()
g.msg("really quit?")
if g.readchar() == 'y' {
g.clear()
g.scr.Std.MvPrintwf(NumLines-2, 0, "You quit with %d gold pieces", g.Player.Purse)
g.move(NumLines-1, 0)
g.refresh()
g.score(g.Player.Purse, 1, 0)
g.myExit()
return
}
g.move(0, 0)
g.clrtoeol()
g.status()
g.move(oy, ox)
g.refresh()
g.Msgs.Mpos = 0
g.Count = 0
g.ToDeath = false
}