Line data Source code
1 : package states
2 :
3 : import (
4 : "errors"
5 : "fmt"
6 : "time"
7 :
8 : "github.com/kijimaD/ruins/internal/activity"
9 : "github.com/kijimaD/ruins/internal/dungeon"
10 : es "github.com/kijimaD/ruins/internal/engine/states"
11 : "github.com/kijimaD/ruins/internal/logger"
12 : mapplanner "github.com/kijimaD/ruins/internal/mapplanner"
13 : "github.com/kijimaD/ruins/internal/messagedata"
14 : "github.com/kijimaD/ruins/internal/overworld"
15 : "github.com/kijimaD/ruins/internal/save"
16 : w "github.com/kijimaD/ruins/internal/world"
17 :
18 : "github.com/kijimaD/ruins/internal/world/query"
19 : "github.com/mlange-42/ark/ecs"
20 : )
21 :
22 : // 各ステートのファクトリー関数を集約したファイル
23 :
24 : // NewDungeonMenuState はダンジョンメニューを選択メニューとして作る
25 : func NewDungeonMenuState() (es.State[w.World], error) {
26 1 : return NewChoiceMenu(dungeonMenuChoices), nil
27 1 : }
28 :
29 : func dungeonMenuChoices(world w.World) (string, []Choice) {
30 1 : choices := []Choice{
31 1 : {Label: query.T(world, "Inventory"), Run: pushChoice(NewItemActionState(verbExamine))},
32 1 : {Label: query.T(world, "Character"), Run: pushChoice(NewCharacterState)},
33 1 : {Label: query.T(world, "Crafting"), Run: pushChoice(NewCraftMenuState)},
34 1 : {Label: query.T(world, "Statistics"), Run: pushChoice(NewRunStatsState)},
35 1 : }
36 1 : if world.Resources.Config.SaveLoadEnabled {
37 1 : choices = append(choices, Choice{Label: query.T(world, "Save game"), Run: pushChoice(NewSaveMenuState)})
38 1 : }
39 1 : choices = append(choices,
40 1 : Choice{Label: query.T(world, "Quit"), Run: func(_ w.World) (es.Transition[w.World], error) {
41 0 : return es.Transition[w.World]{Type: es.TransReplace, NewStateFuncs: []es.StateFactory[w.World]{NewMainMenuState}}, nil
42 0 : }},
43 : Choice{Label: query.T(world, "Close"), Run: func(_ w.World) (es.Transition[w.World], error) {
44 0 : return es.Transition[w.World]{Type: es.TransPop}, nil
45 0 : }},
46 : )
47 1 : return "", choices
48 : }
49 :
50 : // NewCraftMenuState は新しいCraftMenuStateインスタンスを作成するファクトリー関数
51 : func NewCraftMenuState() (es.State[w.World], error) {
52 1 : return &CraftMenuState{}, nil
53 1 : }
54 :
55 : // NewCharacterState は画面タブメニューのStateを作成するファクトリー関数。主人公を表示する
56 : func NewCharacterState() (es.State[w.World], error) {
57 0 : return &CharacterState{}, nil
58 0 : }
59 :
60 : // DungeonStateOption はDungeonStateのオプション設定関数
61 : type DungeonStateOption func(*DungeonState)
62 :
63 : // WithDefinitionName はダンジョン定義名を設定するオプション
64 : func WithDefinitionName(name string) DungeonStateOption {
65 1 : return func(ds *DungeonState) {
66 1 : ds.DefinitionName = name
67 1 : }
68 : }
69 :
70 : // WithResume はセーブから復帰するモードにするオプション。
71 : // マップの再生成・プレイヤー再配置を行わず、復元済みのワールドをそのまま使う
72 : func WithResume() DungeonStateOption {
73 1 : return func(ds *DungeonState) {
74 1 : ds.Resume = true
75 1 : }
76 : }
77 :
78 : // NewDungeonState はDungeonStateインスタンスを作成するファクトリー関数
79 : // デフォルトではBuilderTypeはPlannerTypeRandomになる
80 : func NewDungeonState(depth int, opts ...DungeonStateOption) es.StateFactory[w.World] {
81 1 : return func() (es.State[w.World], error) {
82 1 : ds := &DungeonState{
83 1 : Depth: depth,
84 1 : BuilderType: mapplanner.PlannerTypeRandom,
85 1 : }
86 1 : for _, opt := range opts {
87 1 : opt(ds)
88 1 : }
89 1 : return ds, nil
90 : }
91 : }
92 :
93 : // newGameOverworldState は新規ゲーム開始用のオーバーワールド探索ステートを返す。
94 : // 街を含むオーバーワールドを RunSeed から決定的生成し、プレイヤーは街から始まる。
95 : // キャラ作成・デモ・デバッグ開始で共通に使い、開始点を1箇所に集約する。RunSeed は都度引く。
96 : // 帯形状はマスタ DungeonOverworld が持つので、プレイ固有の RunSeed だけを渡す。
97 : func newGameOverworldState(world w.World) es.StateFactory[w.World] {
98 0 : base := NewOverworldState(mapplanner.PlannerTypeOverworldField, dungeon.DungeonOverworld, &overworld.NewGameParams{
99 0 : RunSeed: world.Resources.Config.RNG.Uint64(),
100 0 : })
101 0 : return func() (es.State[w.World], error) {
102 0 : state, err := base()
103 0 : if err != nil {
104 0 : return nil, err
105 0 : }
106 0 : if ds, ok := state.(*DungeonState); ok {
107 0 : ds.showOpening = !world.Resources.Config.SkipOpening
108 0 : }
109 0 : return state, nil
110 : }
111 : }
112 :
113 : // NewMainMenuState は新しいMainMenuStateインスタンスを作成するファクトリー関数
114 : func NewMainMenuState() (es.State[w.World], error) {
115 1 : return &MainMenuState{}, nil
116 1 : }
117 :
118 : // NewSettingsMenuState は新しいSettingsMenuStateインスタンスを作成するファクトリー関数
119 : func NewSettingsMenuState() (es.State[w.World], error) {
120 1 : return &SettingsMenuState{}, nil
121 1 : }
122 :
123 : // NewGameOverMessageState はゲームオーバー用のMessageStateを作成するファクトリー関数
124 : func NewGameOverMessageState() (es.State[w.World], error) {
125 1 : messageState := &MessageState{}
126 1 :
127 : // ゲームオーバーメッセージを作成する。翻訳は world を要するので OnStart で構築する
128 1 : messageState.build = func(world w.World) *messagedata.MessageData {
129 1 : return messagedata.NewSystemMessage(query.T(world, "You died.")).
130 1 : WithChoice(query.T(world, "Return to main menu"), func(_ w.World) error {
131 0 : messageState.SetTransition(es.Transition[w.World]{
132 0 : Type: es.TransReplace,
133 0 : NewStateFuncs: []es.StateFactory[w.World]{NewMainMenuState}})
134 0 : return nil
135 0 : })
136 : }
137 :
138 1 : return messageState, nil
139 : }
140 :
141 : // NewSaveMenuState は手動セーブ画面を作成するファクトリー関数。
142 : // 固定4スロットで、主人公名とタイムスタンプを表示する。
143 : func NewSaveMenuState() (es.State[w.World], error) {
144 1 : saveManager, err := save.NewSerializationManager()
145 1 : if err != nil {
146 0 : return nil, fmt.Errorf("failed to create save manager: %w", err)
147 0 : }
148 : // スロットラベルはファイル IO を伴うので初回 Fetch で一度だけ組んでキャッシュする。
149 : // world は Fetch から渡る。保存後は TransSwitch でステートを開き直して再構築する
150 1 : var choices []Choice
151 1 : return NewChoiceMenu(func(world w.World) (string, []Choice) {
152 1 : if choices == nil {
153 1 : for i := 1; i <= 4; i++ {
154 1 : slotName := fmt.Sprintf("slot%d", i)
155 1 : label, value := formatSaveSlotLabel(world, saveManager, slotName)
156 1 : choices = append(choices, Choice{Label: label, Value: value, Indent: 1, Run: func(world w.World) (es.Transition[w.World], error) {
157 0 : if err := saveManager.SaveWorld(world, slotName); err != nil {
158 0 : return es.Transition[w.World]{}, fmt.Errorf("save failed: %w", err)
159 0 : }
160 0 : return es.Transition[w.World]{Type: es.TransSwitch, NewStateFuncs: []es.StateFactory[w.World]{NewSaveMenuState}}, nil
161 : }})
162 : }
163 1 : choices = append(choices, backChoice(world))
164 : }
165 1 : return query.T(world, "Save"), choices
166 : }), nil
167 : }
168 :
169 : // NewLoadMenuState はロード画面を作成するファクトリー関数。
170 : // 手動4スロットとオートセーブ4スロットをセクション分けで表示する。
171 : func NewLoadMenuState() (es.State[w.World], error) {
172 1 : saveManager, err := save.NewSerializationManager()
173 1 : if err != nil {
174 0 : return nil, fmt.Errorf("failed to create save manager: %w", err)
175 0 : }
176 : // ラベルはファイル IO を伴うので初回 Fetch で一度だけ組んでキャッシュする
177 1 : var choices []Choice
178 1 : return NewChoiceMenu(func(world w.World) (string, []Choice) {
179 1 : if choices == nil {
180 1 : choices = append(choices, Choice{Label: query.T(world, "Manual save"), Header: true})
181 1 : for i := 1; i <= 4; i++ {
182 1 : choices = append(choices, loadSlotChoice(world, saveManager, fmt.Sprintf("slot%d", i)))
183 1 : }
184 1 : choices = append(choices, Choice{Label: query.T(world, "Auto save"), Header: true})
185 1 : autoSaves, err := saveManager.ListAutoSaves()
186 1 : if err != nil {
187 0 : logger.New(logger.CategorySave).Error("failed to list auto saves", "error", err.Error())
188 0 : autoSaves = nil
189 0 : }
190 1 : if len(autoSaves) > 4 {
191 0 : autoSaves = autoSaves[:4]
192 0 : }
193 1 : for i := range 4 {
194 1 : if i < len(autoSaves) {
195 0 : choices = append(choices, loadSlotChoice(world, saveManager, autoSaves[i]))
196 0 : } else {
197 1 : choices = append(choices, emptySlotChoice())
198 1 : }
199 : }
200 1 : choices = append(choices, backChoice(world))
201 : }
202 1 : return query.T(world, "Load game"), choices
203 : }), nil
204 : }
205 :
206 : // backChoice は戻る選択肢を返す。選択メニューで共通に使う
207 : func backChoice(world w.World) Choice {
208 1 : return Choice{Label: query.T(world, "Back"), Run: func(_ w.World) (es.Transition[w.World], error) {
209 0 : return es.Transition[w.World]{Type: es.TransPop}, nil
210 0 : }}
211 : }
212 :
213 : // emptySlotChoice は空きスロットの行を返す。選べない見出し行にしつつ、埋まったスロットと
214 : // 同じ段へ字下げして縦に揃える
215 : func emptySlotChoice() Choice {
216 1 : return Choice{Label: "---", Header: true, Indent: 1}
217 1 : }
218 :
219 : // loadSlotChoice はロードスロット1つ分の選択肢を返す
220 : func loadSlotChoice(world w.World, saveManager *save.SerializationManager, slotName string) Choice {
221 1 : if !saveManager.SaveFileExists(slotName) {
222 1 : return emptySlotChoice()
223 1 : }
224 1 : label, value := formatSaveSlotLabel(world, saveManager, slotName)
225 1 : return Choice{Label: label, Value: value, Indent: 1, Run: func(world w.World) (es.Transition[w.World], error) {
226 1 : if err := saveManager.LoadWorld(world, slotName); err != nil {
227 : // ロード失敗はアプリ全体を落とさない。RestoreWorldFromJSON の probe 検証で本番ワールドは
228 : // 無傷なので、エラーはログに残し、ロードのメニューの上に知らせを重ねる。ゲームループへ返すと
229 : // main の log.Fatal まで波及してプロセスごと落ちてしまう
230 1 : logger.New(logger.CategorySave).Error("failed to load save", "slot", slotName, "error", err.Error())
231 1 : return es.Transition[w.World]{Type: es.TransPush, NewStateFuncs: []es.StateFactory[w.World]{newLoadFailedMessageState}}, nil
232 1 : }
233 : // 復元済みの現在地から再生成せずに復帰する
234 0 : return es.Transition[w.World]{Type: es.TransReplace, NewStateFuncs: []es.StateFactory[w.World]{newResumeStateFactory(world)}}, nil
235 : }}
236 : }
237 :
238 : // newResumeStateFactory はロード復元時の復帰先ステートを保存内容から選ぶ。
239 : // 現ステージが帯データを持つ、すなわちオーバーワールドなら OverworldState で復帰して帯を
240 : // 再構築し、通常ダンジョンなら DungeonState で復帰する。定義名・深度から再生成はしない。
241 : func newResumeStateFactory(world w.World) es.StateFactory[w.World] {
242 1 : if query.IsOnOverworld(world) {
243 : // ロード復元。帯形状は SeamlessBand から復元するので params は nil。種別はマスタを渡す
244 1 : return NewOverworldState(mapplanner.PlannerTypeOverworldField, dungeon.DungeonOverworld, nil)
245 1 : }
246 1 : d := query.GetDungeon(world)
247 1 : return NewDungeonState(d.CurrentStage.Depth, WithDefinitionName(d.CurrentStage.Name), WithResume())
248 : }
249 :
250 : // ErrNoContinuePoint は継続できるセーブが無いことを表す。エラーではなく、呼び出し側はこれを見て
251 : // メニューへ退避する。復元の失敗と区別するためのセンチネル。
252 : var ErrNoContinuePoint = errors.New("no save to continue")
253 :
254 : // ResumeFromLatestSave は最新のセーブを saveManager から world へ読み込み、その地点の復帰ステートを返す。
255 : // 一覧に出るセーブが無いときは ErrNoContinuePoint を、最新のセーブを読めないときは読み込みのエラーを返す。
256 : func ResumeFromLatestSave(world w.World, saveManager *save.SerializationManager) (es.State[w.World], error) {
257 : // 手動と自動を混ぜた全スロットから最新を読む。ListSaves はタイムスタンプ降順で返す
258 1 : saves, err := saveManager.ListSaves()
259 1 : if err != nil {
260 0 : return nil, fmt.Errorf("continue: list saves: %w", err)
261 0 : }
262 1 : if len(saves) == 0 {
263 1 : return nil, ErrNoContinuePoint
264 1 : }
265 1 : latest := saves[0]
266 1 : if err := saveManager.LoadWorld(world, latest); err != nil {
267 1 : return nil, fmt.Errorf("continue: load save %q: %w", latest, err)
268 1 : }
269 1 : state, err := newResumeStateFactory(world)()
270 1 : if err != nil {
271 0 : return nil, fmt.Errorf("continue: build resume state: %w", err)
272 0 : }
273 1 : return state, nil
274 : }
275 :
276 : // ContinueOrMainMenu は最新のセーブから続きを始めるステートを返す。セーブが無いときはメインメニューを、
277 : // 読めないときは読めなかったことを知らせるメインメニューを返す
278 : func ContinueOrMainMenu(world w.World, saveManager *save.SerializationManager) es.State[w.World] {
279 1 : state, err := ResumeFromLatestSave(world, saveManager)
280 1 : if err != nil {
281 1 : if errors.Is(err, ErrNoContinuePoint) {
282 1 : return &MainMenuState{}
283 1 : }
284 1 : logger.New(logger.CategorySave).Error("failed to continue from the latest save", "error", err.Error())
285 1 : return &MainMenuState{loadFailed: true}
286 : }
287 1 : return state
288 : }
289 :
290 : // formatSaveSlotLabel はスロット行の左ラベルと、値のプレイ時間を返す。時間が無ければ value は空。値は右寄せ列で描く。
291 : func formatSaveSlotLabel(world w.World, saveManager *save.SerializationManager, slotName string) (label, value string) {
292 1 : if !saveManager.SaveFileExists(slotName) {
293 1 : return "---", ""
294 1 : }
295 :
296 1 : playerName, nameErr := saveManager.GetSavePlayerName(slotName)
297 1 : playTime, ptErr := saveManager.GetSavePlayTime(slotName)
298 1 :
299 1 : if nameErr == nil && ptErr == nil {
300 0 : return playerName, formatPlayTime(playTime)
301 0 : }
302 1 : return query.T(world, "Has data"), ""
303 : }
304 :
305 : // formatPlayTime は累積プレイ実時間を時:分:秒で表す。時は無制限、分と秒は0埋め。例 101:34:07
306 : func formatPlayTime(d time.Duration) string {
307 1 : h := int(d / time.Hour)
308 1 : m := int(d % time.Hour / time.Minute)
309 1 : s := int(d % time.Minute / time.Second)
310 1 : return fmt.Sprintf("%d:%02d:%02d", h, m, s)
311 1 : }
312 :
313 : // NewMessageState は組み立て済みメッセージから MessageState を作成する。
314 : // 構築を build へ一本化するため、受け取った messageData を返すだけの build で包む
315 : func NewMessageState(messageData *messagedata.MessageData) (es.State[w.World], error) {
316 1 : return &MessageState{
317 2 : build: func(_ w.World) *messagedata.MessageData { return messageData },
318 : }, nil
319 : }
320 :
321 : // NewShopMenuState は新しいShopMenuStateインスタンスを作成するファクトリー関数。
322 : // merchant はこの店の在庫を持つ商人。売買はこの商人の収納を出し入れする
323 : func NewShopMenuState(merchant ecs.Entity) (es.State[w.World], error) {
324 1 : return &ShopMenuState{merchant: merchant}, nil
325 1 : }
326 :
327 : // NewStorageMenuState は収納メニューStateを作成する
328 : func NewStorageMenuState(storageEntity ecs.Entity) (es.State[w.World], error) {
329 1 : return &StorageMenuState{storageEntity: storageEntity}, nil
330 1 : }
331 :
332 : // NewInteractionMenuState はインタラクションメニューStateを作成する
333 : func NewInteractionMenuState(world w.World) (es.State[w.World], error) {
334 0 : if len(GetInteractionActions(world)) == 0 {
335 0 : messageState := &MessageState{}
336 0 : messageState.build = func(world w.World) *messagedata.MessageData {
337 0 : return messagedata.NewSystemMessage(query.T(world, "No actions available."))
338 0 : }
339 0 : return messageState, nil
340 : }
341 0 : return NewChoiceMenu(interactionChoices), nil
342 : }
343 :
344 : // interactionActionChoices は交流アクション列を選択肢へ変換する。選ぶと実行してダンジョンへ戻る。
345 : // キャンセルは選択肢でなく Esc で閉じる。他メニューと操作を揃える
346 : func interactionActionChoices(actions []InteractionAction) []Choice {
347 0 : choices := make([]Choice, 0, len(actions))
348 0 : for _, action := range actions {
349 0 : choices = append(choices, Choice{Label: action.Label, Run: func(world w.World) (es.Transition[w.World], error) {
350 0 : playerEntity, err := query.GetPlayerEntity(world)
351 0 : if err != nil {
352 0 : return es.Transition[w.World]{}, fmt.Errorf("failed to get player: %w", err)
353 0 : }
354 0 : if _, err := activity.ExecuteInteraction(playerEntity, action.Target, action.Interaction, world); err != nil {
355 0 : return es.Transition[w.World]{}, fmt.Errorf("failed to execute action: %w", err)
356 0 : }
357 0 : return es.Transition[w.World]{Type: es.TransPop}, nil
358 : }})
359 : }
360 0 : return choices
361 : }
362 :
363 : // interactionChoices は範囲内の交流アクションを選択肢にする。交流メニューで使う
364 : func interactionChoices(world w.World) (string, []Choice) {
365 0 : return "", interactionActionChoices(GetInteractionActions(world))
366 0 : }
367 :
368 : // sameTileActionChoices は足元タイルの手動アクションを選択肢にする。ダンジョンの相互作用キーで使う
369 : func sameTileActionChoices(world w.World) (string, []Choice) {
370 0 : return "", interactionActionChoices(GetSameTileManualActions(world))
371 0 : }
372 :
373 : // NewFeedFuelMenuState は給油メニューを作る。くべ先は呼ぶ側が FireFuelSink・CubeFuelSink で決める。
374 : func NewFeedFuelMenuState(sink FuelSink) (es.State[w.World], error) {
375 1 : return &FeedFuelMenuState{sink: sink}, nil
376 1 : }
377 :
378 : // NewMerchantDialogState は商人との会話ステートを作成。merchant はこの商人の実体で、店を開くとき在庫の持ち主として渡す。
379 : // messageKey は商人の会話の行で、その最初のページに店を開く選択肢を付ける
380 : func NewMerchantDialogState(speakerName string, merchant ecs.Entity, messageKey string) (es.State[w.World], error) {
381 1 : persistentState := &PersistentMessageState{}
382 1 :
383 1 : persistentState.build = func(world w.World) *messagedata.MessageData {
384 1 : return messagedata.GetDialogue(world, messageKey, speakerName).
385 1 : WithChoice(query.T(world, "Look"), func(_ w.World) error {
386 0 : persistentState.SetTransition(es.Transition[w.World]{
387 0 : Type: es.TransPush,
388 0 : NewStateFuncs: []es.StateFactory[w.World]{
389 0 : func() (es.State[w.World], error) { return NewShopMenuState(merchant) },
390 : },
391 : })
392 0 : return nil
393 : }).
394 : WithChoice(query.T(world, "No business"), func(_ w.World) error {
395 0 : persistentState.SetTransition(es.Transition[w.World]{Type: es.TransPop})
396 0 : return nil
397 0 : })
398 : }
399 :
400 1 : return persistentState, nil
401 : }
402 :
403 : // NewOpeningState はオープニングを表示するStateを作成するファクトリー関数
404 : // 完了後はポップする。後続ステートが必要な場合は呼び出し側でスタックに積む
405 : func NewOpeningState() (es.State[w.World], error) {
406 1 : messageState := &MessageState{}
407 1 : // 翻訳は world を要するので OnStart でページを組む
408 1 : messageState.build = func(world w.World) *messagedata.MessageData {
409 : // 背景キーを持たせず、土台のゲーム画面へモーダルとして重ねる
410 1 : page := &messagedata.MessageData{Speaker: ""}
411 1 : page.AddMarkup(query.T(world, "You are a space traveler. Your ship crashed\non a frozen planet. Only your cargo cube survived.\nHead <keyword>north</keyword>. A relay station may still remain.\n<keyword>Repair</keyword> the escape core and <keyword>escape</keyword> this planet."))
412 1 : return page
413 1 : }
414 1 : return messageState, nil
415 : }
|