LCOV - code coverage report
Current view: top level - states - debug_menu.go Coverage Total Hit
Test: coverage.lcov Lines: 17.3 % 202 35
Test Date: 2026-11-19 00:25:22 Functions: - 0 0

            Line data    Source code
       1              : package states
       2              : 
       3              : import (
       4              :         "fmt"
       5              : 
       6              :         gc "github.com/kijimaD/ruins/internal/components"
       7              :         "github.com/kijimaD/ruins/internal/consts"
       8              :         "github.com/kijimaD/ruins/internal/dungeon"
       9              :         es "github.com/kijimaD/ruins/internal/engine/states"
      10              :         "github.com/kijimaD/ruins/internal/geometry"
      11              :         mapplanner "github.com/kijimaD/ruins/internal/mapplanner"
      12              :         "github.com/kijimaD/ruins/internal/messagedata"
      13              :         "github.com/kijimaD/ruins/internal/raw"
      14              :         "github.com/kijimaD/ruins/internal/rawschema"
      15              :         w "github.com/kijimaD/ruins/internal/world"
      16              :         "github.com/kijimaD/ruins/internal/world/gameaction"
      17              :         "github.com/kijimaD/ruins/internal/world/lifecycle"
      18              :         "github.com/kijimaD/ruins/internal/world/query"
      19              :         "github.com/mlange-42/ark/ecs"
      20              : )
      21              : 
      22              : // debugTownLayout はデバッグの町の間取りの行の id。入るたびに作り直すため間取りを指して入る
      23              : const debugTownLayout = "debug_town"
      24              : 
      25              : // NewDebugMenuState はデバッグメニューを選択メニューとして作る
      26              : func NewDebugMenuState() (es.State[w.World], error) {
      27            1 :         return NewChoiceMenu(debugMenuChoices), nil
      28            1 : }
      29              : 
      30              : // debugMenuChoices はデバッグメニューの選択肢を返す。開発用のスポーンやメッセージ確認をまとめる
      31              : func debugMenuChoices(world w.World) (string, []Choice) {
      32            1 :         choices := []Choice{
      33            1 :                 {Label: "Spawn healing potion (inventory)", Run: popAfter(func(world w.World) error {
      34            0 :                         _, err := lifecycle.SpawnBackpackItem(world, "healing_potion", 1)
      35            0 :                         return err
      36            0 :                 })},
      37              :                 {Label: "Spawn ray gun (inventory)", Run: popAfter(func(world w.World) error {
      38            0 :                         _, err := lifecycle.SpawnBackpackItem(world, "ray_gun", 1)
      39            0 :                         return err
      40            0 :                 })},
      41              :                 {Label: "Spawn escape device parts (inventory)", Run: popAfter(func(world w.World) error {
      42              :                         // 合成して使うクリアの経路を試せるよう、修理のレシピの材料をそろえる
      43            0 :                         for id, count := range map[string]int{"broken_escape_core": 1, "signal_amplifier": 1, "power_cell": 2, "electric_wire": 4} {
      44            0 :                                 if _, err := lifecycle.SpawnBackpackItem(world, id, count); err != nil {
      45            0 :                                         return err
      46            0 :                                 }
      47              :                         }
      48            0 :                         return nil
      49              :                 })},
      50              :                 {Label: "Inflict conditions", Run: popAfter(debugInflictConditions)},
      51              :                 {Label: "Treat all conditions", Run: popAfter(debugTreatAllConditions)},
      52              :                 {Label: "Exhaust fatigue", Run: popAfter(debugExhaustFatigue)},
      53              :                 {Label: "Starve hunger", Run: popAfter(debugStarveHunger)},
      54              :                 {Label: "Damage self (-10 HP)", Run: popAfter(debugDamageSelf(10))},
      55              :                 {Label: "Game over", Run: pushChoice(NewGameOverMessageState)},
      56              :                 {Label: "Run result (death screen)", Run: func(world w.World) (es.Transition[w.World], error) {
      57              :                         // 死因に目印の debug を入れて結果画面を確認する
      58            0 :                         if s := query.GetRunStats(world); s != nil {
      59            0 :                                 s.Cause = gc.CauseDebug
      60            0 :                         }
      61            0 :                         return es.Transition[w.World]{Type: es.TransPush, NewStateFuncs: []es.StateFactory[w.World]{NewRunResultState}}, nil
      62              :                 }},
      63              :                 {Label: "Run result (clear screen)", Run: func(_ w.World) (es.Transition[w.World], error) {
      64            0 :                         return es.Transition[w.World]{Type: es.TransPush, NewStateFuncs: []es.StateFactory[w.World]{NewRunClearState}}, nil
      65            0 :                 }},
      66              :                 {Label: "Start overworld", Run: func(world w.World) (es.Transition[w.World], error) {
      67            0 :                         return es.Transition[w.World]{Type: es.TransReplace, NewStateFuncs: []es.StateFactory[w.World]{newGameOverworldState(world)}}, nil
      68            0 :                 }},
      69              :         }
      70              : 
      71              :         // 絵を使わない間取りごとにデバッグ遺跡へ入る選択肢を平坦に追加する。マップ生成の見た目を試す用途。
      72              :         // TransReplace ではなく TransPop でゲームへ戻し、DungeonState.Update が enterDungeonWith を指定プランナーで通す
      73            1 :         for _, pt := range mapplanner.ProceduralPlannerTypes(world.Resources.RawMaster) {
      74            1 :                 choices = append(choices, Choice{Label: "Generate debug dungeon " + pt.Name, Run: popAfter(func(world w.World) error {
      75            0 :                         return lifecycle.RequestStateChange(world, gc.WarpDungeonEnterWithPlannerEvent(dungeon.DebugID, pt.Name))
      76            0 :                 })})
      77              :         }
      78              : 
      79              :         // 区域の種類ごとに、北で一番近い区域の手前まで帯を進める。帯は地上にしか無い
      80            1 :         districts := raw.PtrSlice(world.Resources.RawMaster.Districts)
      81            1 :         if !query.IsOnOverworld(world) {
      82            1 :                 districts = nil
      83            1 :         }
      84            1 :         for i := range districts {
      85            0 :                 id := districts[i].Id
      86            0 :                 choices = append(choices, Choice{Label: "Jump to next district " + id, Run: popAfter(func(world w.World) error {
      87            0 :                         return lifecycle.RequestStateChange(world, gc.DebugJumpToDistrictEvent(id))
      88            0 :                 })})
      89              :         }
      90              : 
      91              :         // 街用NPC・収納箱をスポーン地点の隣に固定配置したデバッグステージへ入る。
      92              :         // 街の会話・売買・収納を入ってすぐテストできる
      93            1 :         choices = append(choices, Choice{Label: "Generate debug stage", Run: popAfter(func(world w.World) error {
      94            0 :                 return lifecycle.RequestStateChange(world, gc.WarpDungeonEnterWithPlannerEvent(dungeon.DebugTownID, debugTownLayout))
      95            0 :         })})
      96              : 
      97            1 :         choices = append(choices,
      98            1 :                 Choice{Label: "Message display test", Run: pushMessage(messagedata.NewSystemMessage("The game was saved automatically.\n\nYour progress has been recorded safely."))},
      99            1 :                 Choice{Label: "Item acquisition event", Run: func(world w.World) (es.Transition[w.World], error) {
     100            0 :                         for id, count := range map[string]int{"iron": 1, "wooden_stick": 1, "ferrite_core": 2} {
     101            0 :                                 if err := lifecycle.ChangeStackCount(world, id, count); err != nil {
     102            0 :                                         return es.Transition[w.World]{}, fmt.Errorf("failed to add item: %w", err)
     103            0 :                                 }
     104              :                         }
     105            0 :                         md := &messagedata.MessageData{Speaker: ""}
     106            0 :                         md.AddText("Found a treasure chest.\n\nObtained iron.\nObtained a wooden stick.\nObtained 2 ferrite cores.\n")
     107            0 :                         return es.Transition[w.World]{Type: es.TransPush, NewStateFuncs: []es.StateFactory[w.World]{func() (es.State[w.World], error) { return NewMessageState(md) }}}, nil
     108              :                 }},
     109              :                 Choice{Label: "Chained message test", Run: pushMessage(messagedata.NewSystemMessage("Battle begins.").SystemMessage("Sword clashes against sword.").SystemMessage("Victory."))},
     110              :                 Choice{Label: "Long message test", Run: pushMessage(messagedata.NewSystemMessage("This is a test of a very long message.\n\nThe message window resizes automatically, and we confirm that even long text is displayed properly.\n\nThis test verifies that multi-line text and line breaks are handled correctly, and that the window background and border are drawn properly.\n\nMixed content should also display without any problems.\nLet us check punctuation, symbols, and numbers like 123 as well."))},
     111              :                 Choice{Label: "Choice branch message test", Run: pushMessage(messagedata.NewDialogMessage("Encountered an enemy.", "").
     112              :                         WithChoiceMessage("Fight", messagedata.NewSystemMessage("Fought.")).
     113              :                         WithChoiceMessage("Negotiate", messagedata.NewSystemMessage("Negotiated.")).
     114              :                         WithChoiceMessage("Flee", messagedata.NewSystemMessage("Fled.")))},
     115              :                 Choice{Label: "Message with background test", Run: func(_ w.World) (es.Transition[w.World], error) {
     116            0 :                         md := messagedata.NewDialogMessage("This is a test of a message with a background.", "System")
     117            0 :                         md.BackgroundKey = "hospital1"
     118            0 :                         return es.Transition[w.World]{Type: es.TransPush, NewStateFuncs: []es.StateFactory[w.World]{func() (es.State[w.World], error) { return NewMessageState(md) }}}, nil
     119              :                 }},
     120              :                 Choice{Label: "Toggle invincible", Run: popAfter(debugToggleInvincible)},
     121              :                 Choice{Label: "Kill nearby enemies", Run: popAfter(debugKillNearbyEnemies)},
     122              :                 Choice{Label: "Toggle debug display", Run: popAfter(func(world w.World) error {
     123            0 :                         world.Resources.Config.ShowMapDebug = !world.Resources.Config.ShowMapDebug
     124            0 :                         world.Resources.Config.ShowAIDebug = !world.Resources.Config.ShowAIDebug
     125            0 :                         world.Resources.Config.NoEncounter = !world.Resources.Config.NoEncounter
     126            0 :                         return nil
     127            0 :                 })},
     128              :                 Choice{Label: "Advance time of day", Run: popAfter(func(world w.World) error {
     129              :                         // 次の時間帯へ進める。色フィルタは Draw で毎回 GameTime から計算するので即反映されるが、
     130              :                         // 環境光は vision が移動時しか再計算しないので、明るさを更新するため視界を要求する
     131            0 :                         query.GetGameTime(world).AdvanceToNextTimeOfDay()
     132            0 :                         query.GetVisionState(world).RequestUpdate()
     133            0 :                         return nil
     134            0 :                 })},
     135              :                 Choice{Label: "Advance season", Run: popAfter(func(world w.World) error {
     136            0 :                         query.GetGameTime(world).AdvanceToNextSeason()
     137            0 :                         return nil
     138            0 :                 })},
     139              :                 Choice{Label: "Opening", Run: pushChoice(NewOpeningState)},
     140              :                 Choice{Label: "Name input", Run: pushChoice(NewCharacterNamingState)},
     141              :                 Choice{Label: "Job selection", Run: pushChoice(NewCharacterJobState("Ash"))},
     142            0 :                 Choice{Label: "Spawn enemy: fireball (hostile)", Run: stayAfter(func(world w.World) error { return spawnEnemyNearPlayer(world, "fireball") })},
     143            0 :                 Choice{Label: "Spawn enemy: moss turtle (neutral)", Run: stayAfter(func(world w.World) error { return spawnEnemyNearPlayer(world, "moss_turtle") })},
     144            0 :                 Choice{Label: "Spawn enemy: rat (cowardly)", Run: stayAfter(func(world w.World) error { return spawnEnemyNearPlayer(world, "rat") })},
     145            0 :                 Choice{Label: "Spawn enemy: iron sentinel (stationary)", Run: stayAfter(func(world w.World) error { return spawnEnemyNearPlayer(world, "iron_sentinel") })},
     146            0 :                 Choice{Label: "Spawn enemy: poison spider (wallHug)", Run: stayAfter(func(world w.World) error { return spawnEnemyNearPlayer(world, "poison_spider") })},
     147            0 :                 Choice{Label: "Spawn enemy: slime (swarm)", Run: stayAfter(func(world w.World) error { return spawnEnemyNearPlayer(world, "slime") })},
     148            0 :                 Choice{Label: "Spawn enemy: skeleton soldier (patrol)", Run: stayAfter(func(world w.World) error { return spawnEnemyNearPlayer(world, "skeleton_soldier") })},
     149            0 :                 Choice{Label: "Spawn enemy: stray dog (territorial)", Run: stayAfter(func(world w.World) error { return spawnEnemyNearPlayer(world, "stray_dog") })},
     150            0 :                 Choice{Label: "Spawn prop: moving_stone (PassCost)", Run: stayAfter(func(world w.World) error { return spawnPropNearPlayer(world, "moving_stone") })},
     151            0 :                 Choice{Label: "Spawn prop: hearth", Run: stayAfter(func(world w.World) error { return spawnPropNearPlayer(world, "hearth") })},
     152            0 :                 Choice{Label: "Spawn prop: barrel (destructible)", Run: stayAfter(func(world w.World) error { return spawnPropNearPlayer(world, "barrel") })},
     153            0 :                 Choice{Label: "Spawn prop: construction_sign (impassable)", Run: stayAfter(func(world w.World) error { return spawnPropNearPlayer(world, "construction_sign") })},
     154              :                 Choice{Label: "Spawn prop: wooden crate (storage, with items)", Run: stayAfter(spawnStorageWithItems)},
     155              :                 Choice{Label: "Component list", Run: pushChoice(NewComponentDebugState)},
     156              :                 Choice{Label: "Close", Run: func(_ w.World) (es.Transition[w.World], error) {
     157            0 :                         return es.Transition[w.World]{Type: es.TransPop}, nil
     158            0 :                 }},
     159              :         )
     160            1 :         return "", choices
     161              : }
     162              : 
     163              : // debugInflictConditions はデバッグでプレイヤーへ raw の不調をまとめて付ける。量から導出する不調は付けられない
     164              : func debugInflictConditions(world w.World) error {
     165            0 :         player, err := query.GetPlayerEntity(world)
     166            0 :         if err != nil {
     167            0 :                 return err
     168            0 :         }
     169            0 :         if !world.Components.HealthStatus.Has(player) {
     170            0 :                 return nil
     171            0 :         }
     172            0 :         hs := world.Components.HealthStatus.Get(player)
     173            0 :         defs := world.Resources.ConditionDefs
     174            0 :         cold := defs.ByOnset(rawschema.Cold)
     175            0 :         for _, ct := range defs.Types() {
     176            0 :                 if defs.IsDerived(ct) {
     177            0 :                         continue
     178              :                 }
     179            0 :                 part, timer := gc.BodyPartTorso, 60.0
     180            0 :                 if def, _ := defs.Def(ct); len(def.Parts) > 0 {
     181            0 :                         part = def.Parts[0]
     182            0 :                 }
     183            0 :                 if ct == cold {
     184            0 :                         part, timer = gc.BodyPartWholeBody, 90
     185            0 :                 }
     186            0 :                 hs.Parts[part].SetCondition(gc.HealthCondition{Type: ct, Timer: timer, Severity: gc.TimerToSeverity(timer)})
     187              :         }
     188            0 :         return nil
     189              : }
     190              : 
     191              : // debugExhaustFatigue はデバッグでプレイヤーの疲労を過労まで上げる。入眠をすぐ試すため
     192              : func debugExhaustFatigue(world w.World) error {
     193            0 :         player, err := query.GetPlayerEntity(world)
     194            0 :         if err != nil {
     195            0 :                 return err
     196            0 :         }
     197            0 :         if !world.Components.Fatigue.Has(player) {
     198            0 :                 return nil
     199            0 :         }
     200            0 :         fatigue := world.Components.Fatigue.Get(player)
     201            0 :         fatigue.Current = fatigue.Max
     202            0 :         return nil
     203              : }
     204              : 
     205              : // debugStarveHunger はデバッグでプレイヤーの空腹を飢餓まで下げる。栄養失調の効果をすぐ試すため
     206              : func debugStarveHunger(world w.World) error {
     207            0 :         player, err := query.GetPlayerEntity(world)
     208            0 :         if err != nil {
     209            0 :                 return err
     210            0 :         }
     211            0 :         if !world.Components.Hunger.Has(player) {
     212            0 :                 return nil
     213            0 :         }
     214            0 :         hunger := world.Components.Hunger.Get(player)
     215            0 :         hunger.Current = 0
     216            0 :         return nil
     217              : }
     218              : 
     219              : // debugTreatAllConditions はデバッグでプレイヤーの全不調を治療済みにする。回復軌道の確認用。
     220              : // 低体温は TemperatureSystem が体温から進めるので TendQuality では治らない
     221              : func debugTreatAllConditions(world w.World) error {
     222            0 :         player, err := query.GetPlayerEntity(world)
     223            0 :         if err != nil {
     224            0 :                 return err
     225            0 :         }
     226            0 :         if !world.Components.HealthStatus.Has(player) {
     227            0 :                 return nil
     228            0 :         }
     229            0 :         hs := world.Components.HealthStatus.Get(player)
     230            0 :         for p := range hs.Parts {
     231            0 :                 for i := range hs.Parts[p].Conditions {
     232              :                         // 150% は回復1.5倍の良質な治療。回復軌道に乗る様子を確認する
     233            0 :                         hs.Parts[p].Conditions[i].TendQuality = 150
     234            0 :                 }
     235              :         }
     236            0 :         return nil
     237              : }
     238              : 
     239              : // debugDamageSelf はデバッグでプレイヤーの HP を削る。HP の自然回復を観察する用
     240              : func debugDamageSelf(amount int) func(w.World) error {
     241            1 :         return func(world w.World) error {
     242            0 :                 player, err := query.GetPlayerEntity(world)
     243            0 :                 if err != nil {
     244            0 :                         return err
     245            0 :                 }
     246            0 :                 gameaction.ApplyDamage(world, player, amount, player)
     247            0 :                 return nil
     248              :         }
     249              : }
     250              : 
     251              : // playerGridElement はプレイヤーの GridElement を返す。位置を持たない文脈ではエラーにする。
     252              : // GridElement 不在の Get は Ark で panic するため、デバッグスポーンの前に弾く
     253              : func playerGridElement(world w.World) (*gc.GridElement, error) {
     254            0 :         player, err := query.GetPlayerEntity(world)
     255            0 :         if err != nil {
     256            0 :                 return nil, err
     257            0 :         }
     258            0 :         if !world.Components.GridElement.Has(player) {
     259            0 :                 return nil, fmt.Errorf("cannot spawn because the player has no position")
     260            0 :         }
     261            0 :         return world.Components.GridElement.Get(player), nil
     262              : }
     263              : 
     264              : func spawnPropNearPlayer(world w.World, name string) error {
     265            0 :         playerGrid, err := playerGridElement(world)
     266            0 :         if err != nil {
     267            0 :                 return err
     268            0 :         }
     269            0 :         _, err = lifecycle.SpawnProp(world, name, playerGrid.X+2, playerGrid.Y)
     270            0 :         return err
     271              : }
     272              : 
     273              : // spawnStorageWithItems はプレイヤーの隣にアイテム入り木箱をスポーンする
     274              : func spawnStorageWithItems(world w.World) error {
     275            0 :         playerGrid, err := playerGridElement(world)
     276            0 :         if err != nil {
     277            0 :                 return err
     278            0 :         }
     279            0 :         storageEntity, err := lifecycle.SpawnProp(world, "wooden_crate", playerGrid.X+2, playerGrid.Y)
     280            0 :         if err != nil {
     281            0 :                 return err
     282            0 :         }
     283              : 
     284            0 :         items := []struct {
     285            0 :                 name  string
     286            0 :                 count int
     287            0 :         }{
     288            0 :                 {"healing_potion", 3},
     289            0 :                 {"grenade", 1},
     290            0 :                 {"torch", 1},
     291            0 :         }
     292            0 :         for _, item := range items {
     293            0 :                 if _, err := lifecycle.SpawnStorageItem(world, item.name, item.count, storageEntity); err != nil {
     294            0 :                         return fmt.Errorf("failed to spawn storage item: %w", err)
     295            0 :                 }
     296              :         }
     297            0 :         return nil
     298              : }
     299              : 
     300              : // spawnEnemyNearPlayer はプレイヤーから少し離れた位置に敵をスポーンする
     301              : func spawnEnemyNearPlayer(world w.World, name string) error {
     302            0 :         playerGrid, err := playerGridElement(world)
     303            0 :         if err != nil {
     304            0 :                 return err
     305            0 :         }
     306            0 :         _, err = lifecycle.SpawnEnemy(world, consts.Coord[consts.Tile]{X: playerGrid.X + 8, Y: playerGrid.Y}, name)
     307            0 :         return err
     308              : }
     309              : 
     310              : // debugKillNearbyEnemiesRange はデバッグで倒す敵の、プレイヤーからのチェビシェフ距離の上限
     311              : const debugKillNearbyEnemiesRange consts.Tile = 30
     312              : 
     313              : // debugKillNearbyEnemies はデバッグでプレイヤーの近くの敵を倒す。囲まれずに周りを見て回るため
     314              : func debugKillNearbyEnemies(world w.World) error {
     315            1 :         player, err := query.GetPlayerEntity(world)
     316            1 :         if err != nil {
     317            0 :                 return err
     318            0 :         }
     319            1 :         center := world.Components.GridElement.Get(player).Coord
     320            1 :         var targets []ecs.Entity
     321            1 :         q := query.ActiveFilter3[gc.FactionEnemy, gc.GridElement, gc.HP](world).Query()
     322            1 :         for q.Next() {
     323            1 :                 p := world.Components.GridElement.Get(q.Entity()).Coord
     324            1 :                 if max(geometry.Abs(p.X-center.X), geometry.Abs(p.Y-center.Y)) <= debugKillNearbyEnemiesRange {
     325            1 :                         targets = append(targets, q.Entity())
     326            1 :                 }
     327              :         }
     328            1 :         for _, e := range targets {
     329            1 :                 gameaction.ApplyDamage(world, e, world.Components.HP.Get(e).Current, player)
     330            1 :         }
     331            1 :         return nil
     332              : }
     333              : 
     334              : // debugToggleInvincible はデバッグでプレイヤーの無敵を切り替える。無敵の間は DebugInvincibleSystem がプレイヤーを満たす
     335              : func debugToggleInvincible(world w.World) error {
     336            1 :         cfg := world.Resources.Config
     337            1 :         cfg.DebugInvincible = !cfg.DebugInvincible
     338            1 :         return nil
     339            1 : }
        

Generated by: LCOV version 2.0-1