aboutsummaryrefslogtreecommitdiff
path: root/internal/game/cmd_room_insert.go
blob: 713e6b349091f7f80ce7038b9d55a86ee59daf33 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package game

import (
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	"gopkg.in/yaml.v3"
	"thehouseoficarus/internal/behavior"
	"thehouseoficarus/internal/net"
	"thehouseoficarus/internal/world"
)

func (g *Game) roomInsert(sess *net.Session, args []string) {
	p := sess.Player
	if p == nil {
		return
	}

	if len(args) == 0 {
		sess.WriteLine("Usage: room insert <direction> [name]")
		return
	}

	dir := g.World.ResolveExit(args[0])
	if dir == "" {
		sess.WriteLine("Invalid direction. Use n/s/e/w/ne/nw/se/sw/u/d.")
		return
	}

	curPath, ok := g.World.GetRoomPath(p.RoomID)
	if !ok {
		sess.WriteLine("Error: can't find current room file.")
		return
	}

	curRoom, err := g.World.LoadRoom(p.RoomID)
	if err != nil {
		sess.WriteLine("Error loading current room.")
		return
	}

	exitDef, hasExit := curRoom.Exits[dir]
	if !hasExit {
		sess.WriteLine(fmt.Sprintf("There is no exit to the %s from here.", dir))
		return
	}

	targetID := exitDef.Room
	targetRoom, err := g.World.LoadRoom(targetID)
	if err != nil {
		sess.WriteLine(fmt.Sprintf("Target room %d not found.", targetID))
		return
	}
	targetName := fmt.Sprintf("#%d (%s)", targetID, targetRoom.Name)

	oppositeDir := world.OppositeExit[dir]

	newID, err := findNextRoomID(filepath.Dir(curPath), g.World.RoomIndex())
	if err != nil {
		sess.WriteLine("Error scanning room directory.")
		return
	}

	var name string
	if len(args) > 1 {
		name = strings.Join(args[1:], " ")
	} else {
		name = fmt.Sprintf("Room #%d", newID)
	}

	conflicts := world.InsertGridConflicts(p.RoomID, dir, targetID, newID, func(id int) (*world.Room, bool) {
		r, err := g.World.LoadRoom(id)
		if err != nil {
			return nil, false
		}
		return r, true
	})
	if len(conflicts) > 0 {
		for _, c := range conflicts {
			switch c.Kind {
			case world.GridConflictTwist:
				room, _ := g.World.LoadRoom(c.Target)
				conflictName := fmt.Sprintf("#%d", c.Target)
				if room != nil {
					conflictName = fmt.Sprintf("#%d (%s)", c.Target, room.Name)
				}
				sess.WriteLine(fmt.Sprintf(
					"Cannot insert: room %s would have an ambiguous grid position after insertion (reachable via an alternate path from here).",
					conflictName))
			case world.GridConflictOverlap:
				occRoom, _ := g.World.LoadRoom(c.Occupier)
				occName := fmt.Sprintf("#%d", c.Occupier)
				if occRoom != nil {
					occName = fmt.Sprintf("#%d (%s)", c.Occupier, occRoom.Name)
				}
				sess.WriteLine(fmt.Sprintf(
					"Cannot insert: pushing %s would cause grid collision with %s.",
					targetName, occName))
			}
		}
		return
	}

	dirPath := filepath.Dir(curPath)
	newPath := filepath.Join(dirPath, strconv.Itoa(newID)+".yaml")

	newRoom := &world.Room{
		Name: name,
		Description: behavior.DescList{
			{Text: "A featureless room."},
		},
		Exits: map[world.ExitDir]world.ExitDef{
			dir:         {Room: targetID},
			oppositeDir: {Room: p.RoomID},
		},
	}

	data, err := yaml.Marshal(newRoom)
	if err != nil {
		sess.WriteLine("Error creating room YAML.")
		return
	}
	if err := os.MkdirAll(dirPath, 0755); err != nil {
		sess.WriteLine("Error creating directory.")
		return
	}

	curRoom.Exits[dir] = world.RewirePreserving(exitDef, newID)
	curData, err := yaml.Marshal(curRoom)
	if err != nil {
		sess.WriteLine("Error updating current room YAML.")
		return
	}

	// Stage all three files (the new room, the current room, and the far
	// room's reciprocal exit when it points back) into ONE journal
	// transaction. The previous sequential writes could stop after the new
	// room existed but before the current room's exit was rewritten, leaving
	// a dangling exit with no recovery record; the transaction rolls the
	// whole insert back on any failure or crash.
	txn := g.newTxn()
	if err := txn.Replace(newPath, data, 0644); err != nil {
		sess.WriteLine(fmt.Sprintf("Error writing room file: %v", err))
		return
	}
	if err := txn.Replace(curPath, curData, 0644); err != nil {
		sess.WriteLine(fmt.Sprintf("Error writing current room file: %v", err))
		return
	}
	if targetExit, tok := targetRoom.Exits[oppositeDir]; tok && targetExit.Room == p.RoomID {
		if targetPath, tok2 := g.World.GetRoomPath(targetID); tok2 {
			targetRoom.Exits[oppositeDir] = world.RewirePreserving(targetExit, newID)
			targetData, terr := yaml.Marshal(targetRoom)
			if terr != nil {
				sess.WriteLine(fmt.Sprintf("Error updating room %d YAML: %v", targetID, terr))
				return
			}
			if err := txn.Replace(targetPath, targetData, 0644); err != nil {
				sess.WriteLine(fmt.Sprintf("Error linking the opposite exit in room %d: %v", targetID, err))
				return
			}
		}
	}
	if err := txn.Commit(); err != nil {
		sess.WriteLine(fmt.Sprintf("Error committing room insert: %v", err))
		return
	}

	g.World.AddRoomPath(newID, newPath)

	oldRoom := p.RoomID
	g.relocatePlayer(sess, p, newID)
	g.saveCharacter(p)

	g.World.SeedGroundItems(newID)
	g.seedRoomMobs(newID)
	g.seedRoomObjects(newID)

	if g.Hub != nil {
		for _, other := range g.Hub.PlayersInRoom(oldRoom) {
			if other != sess {
				other.WriteLine(fmt.Sprintf("%s vanishes into the tunnel.", p.Name))
			}
		}
		g.Hub.EnterRoom(sess, newID)
		for _, other := range g.Hub.PlayersInRoom(newID) {
			if other != sess {
				other.WriteLine(fmt.Sprintf("%s appears.", p.Name))
			}
		}
	}

	g.World.RebuildRoomIndex(g.DataDir)

	sess.WriteLine(fmt.Sprintf("You insert a room to the %s and create Room #%d (%s).", dir, newID, name))
	g.doLook(sess)
	g.runEnterSteps(sess, newID)
	g.checkAggro(sess)
}