LCOV - code coverage report
Current view: top level - states - cube_facility_menu.go Coverage Total Hit
Test: coverage.lcov Lines: 41.4 % 145 60
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              :         "github.com/hajimehoshi/ebiten/v2"
       7              :         "github.com/kijimaD/ruins/internal/consts"
       8              :         es "github.com/kijimaD/ruins/internal/engine/states"
       9              :         "github.com/kijimaD/ruins/internal/gamelog"
      10              :         "github.com/kijimaD/ruins/internal/inputmapper"
      11              :         "github.com/kijimaD/ruins/internal/keybind"
      12              :         "github.com/kijimaD/ruins/internal/menuloop"
      13              :         "github.com/kijimaD/ruins/internal/resources"
      14              :         "github.com/kijimaD/ruins/internal/widgets/hud"
      15              :         "github.com/kijimaD/ruins/internal/widgets/menuframe"
      16              :         "github.com/kijimaD/ruins/internal/widgets/styled"
      17              :         "github.com/kijimaD/ruins/internal/widgets/uicore"
      18              :         w "github.com/kijimaD/ruins/internal/world"
      19              :         "github.com/kijimaD/ruins/internal/world/lifecycle"
      20              :         "github.com/kijimaD/ruins/internal/world/query"
      21              :         "github.com/mlange-42/ark/ecs"
      22              : )
      23              : 
      24              : // CubeFacilityMenuState はキューブの展開空間へ設備を装着する画面。展開空間を表す UI 内グリッドを描き、
      25              : // カーソルでマスを選ぶ。空きマスで決定すると装着アイテムの選択へ進み、設備マスで決定すると撤去する。
      26              : // フィールドを歩いて装着/撤去する経路は持たず、装着と撤去をこの画面へ集約する。展開中のみ開く。
      27              : type CubeFacilityMenuState struct {
      28              :         es.BaseState[w.World]
      29              :         cube   ecs.Entity
      30              :         cursor consts.Coord[consts.Tile] // キューブ中心からの相対オフセット
      31              : }
      32              : 
      33              : var _ es.State[w.World] = &CubeFacilityMenuState{}
      34              : 
      35              : // NewCubeFacilityMenuState はキューブの設備画面を開くファクトリを返す。カーソルはキューブ本体でなく
      36              : // 隣のマスから始める。本体マスは装着先にならず、そこから始めると初手の決定が空振りして戸惑うため。
      37              : func NewCubeFacilityMenuState(cube ecs.Entity) (es.State[w.World], error) {
      38            0 :         return &CubeFacilityMenuState{cube: cube, cursor: consts.Coord[consts.Tile]{X: 1}}, nil
      39            0 : }
      40              : 
      41              : // OnStart はステートが開始される際に呼ばれる。OnPause/OnResume/OnStop は BaseState の既定に委ねる
      42            0 : func (st *CubeFacilityMenuState) OnStart(_ w.World) error { return nil }
      43              : 
      44              : // cubeFacilityBindings は設備画面の束縛表。矢印でカーソルを動かし、Enter で決定、Esc で閉じる
      45              : var cubeFacilityBindings = []keybind.Binding{
      46              :         {Key: ebiten.KeyEscape, Press: keybind.PressJust, Action: inputmapper.ActionMenuCancel},
      47              :         {Key: ebiten.KeyArrowUp, Press: keybind.PressRepeat, Action: inputmapper.ActionMenuUp},
      48              :         {Key: ebiten.KeyArrowDown, Press: keybind.PressRepeat, Action: inputmapper.ActionMenuDown},
      49              :         {Key: ebiten.KeyArrowLeft, Press: keybind.PressRepeat, Action: inputmapper.ActionMenuLeft},
      50              :         {Key: ebiten.KeyArrowRight, Press: keybind.PressRepeat, Action: inputmapper.ActionMenuRight},
      51              :         {Key: ebiten.KeyEnter, Press: keybind.PressJust, Action: inputmapper.ActionMenuSelect},
      52              : }
      53              : 
      54              : // Update はゲームステートの更新処理を行う
      55              : func (st *CubeFacilityMenuState) Update(world w.World) (es.Transition[w.World], error) {
      56              :         // 展開中でなければ空間が無いので閉じる。呼び出し側が展開中のみ開くので通常は起きない
      57            1 :         if !world.Components.Deployed.Has(st.cube) {
      58            1 :                 return es.Transition[w.World]{Type: es.TransPop}, nil
      59            1 :         }
      60            0 :         if action, ok := keybind.ReadInput(world, cubeFacilityBindings); ok {
      61            0 :                 return st.doAction(world, action)
      62            0 :         }
      63            0 :         return st.ConsumeTransition(), nil
      64              : }
      65              : 
      66              : // doAction は Action を実行する
      67              : func (st *CubeFacilityMenuState) doAction(world w.World, action inputmapper.ActionID) (es.Transition[w.World], error) {
      68            1 :         switch action {
      69              :         case inputmapper.ActionMenuCancel, inputmapper.ActionCloseMenu:
      70            1 :                 return es.Transition[w.World]{Type: es.TransPop}, nil
      71              :         case inputmapper.ActionMenuUp:
      72            0 :                 st.moveCursor(world, 0, -1)
      73              :         case inputmapper.ActionMenuDown:
      74            0 :                 st.moveCursor(world, 0, 1)
      75              :         case inputmapper.ActionMenuLeft:
      76            0 :                 st.moveCursor(world, -1, 0)
      77              :         case inputmapper.ActionMenuRight:
      78            1 :                 st.moveCursor(world, 1, 0)
      79              :         case inputmapper.ActionMenuSelect:
      80            0 :                 return st.selectCell(world)
      81              :         default:
      82            0 :                 return es.Transition[w.World]{}, fmt.Errorf("cubeFacility: unsupported action: %s", action)
      83              :         }
      84            1 :         return st.ConsumeTransition(), nil
      85              : }
      86              : 
      87              : // moveCursor はカーソルを凍結した展開範囲の中でクランプして動かす
      88              : func (st *CubeFacilityMenuState) moveCursor(world w.World, dx consts.Tile, dy consts.Tile) {
      89            1 :         r := world.Components.Deployed.Get(st.cube).Range
      90            1 :         next := st.cursor.Add(consts.Coord[consts.Tile]{X: dx, Y: dy})
      91            1 :         if next.X < -r.X || next.X > r.X || next.Y < -r.Y || next.Y > r.Y {
      92            1 :                 return
      93            1 :         }
      94            1 :         st.cursor = next
      95              : }
      96              : 
      97              : // selectCell はカーソルのマスを決定する。空きなら装着アイテム選択へ、設備なら撤去する
      98              : func (st *CubeFacilityMenuState) selectCell(world w.World) (es.Transition[w.World], error) {
      99            1 :         base := world.Components.GridElement.Get(st.cube).Coord
     100            1 :         coord := base.Add(st.cursor)
     101            1 :         kind, _ := st.cellKindAt(world, coord)
     102            1 :         switch kind {
     103              :         case hud.FacilityCellEmpty:
     104            1 :                 player, err := query.GetPlayerEntity(world)
     105            1 :                 if err != nil {
     106            0 :                         return es.Transition[w.World]{}, err
     107            0 :                 }
     108            1 :                 if len(query.BackpackDeployables(world, player)) == 0 {
     109            0 :                         gamelog.New(query.GetGameLog(world)).
     110            0 :                                 Markup(query.T(world, "You have nothing to deploy.")).
     111            0 :                                 Log()
     112            0 :                         return st.ConsumeTransition(), nil
     113            0 :                 }
     114            1 :                 return es.Transition[w.World]{
     115            1 :                         Type:          es.TransPush,
     116            1 :                         NewStateFuncs: []es.StateFactory[w.World]{newCubeFacilitySelectState(st.cube, coord)},
     117            1 :                 }, nil
     118              :         case hud.FacilityCellUsed:
     119            1 :                 return st.removeAt(world, coord)
     120              :         default:
     121              :                 // キューブ本体・障害物のマスは決定しても何もしない
     122            0 :                 return st.ConsumeTransition(), nil
     123              :         }
     124              : }
     125              : 
     126              : // removeAt は coord の設備を撤去してアイテムへ戻す。中身が残る収納など撤去できない場合はログを出す
     127              : func (st *CubeFacilityMenuState) removeAt(world w.World, coord consts.Coord[consts.Tile]) (es.Transition[w.World], error) {
     128            1 :         prop, ok := query.FacilityAt(world, coord)
     129            1 :         if !ok {
     130            0 :                 return st.ConsumeTransition(), nil
     131            0 :         }
     132            1 :         player, err := query.GetPlayerEntity(world)
     133            1 :         if err != nil {
     134            0 :                 return es.Transition[w.World]{}, err
     135            0 :         }
     136              :         // FacilityAt が Deployable を保証するので、ここへ来る err は収納非空のみ。他種別が増えたら文言を分ける
     137            1 :         if err := lifecycle.RemoveFacility(world, prop, player); err != nil {
     138            0 :                 gamelog.New(query.GetGameLog(world)).
     139            0 :                         Markup(query.T(world, "Cannot remove: empty its contents first.")).
     140            0 :                         Log()
     141            0 :         }
     142            1 :         return st.ConsumeTransition(), nil
     143              : }
     144              : 
     145              : // cellKindAt は coord のマスの見た目種別と、Used のとき装着されている設備を返す。装着でない prop や壁は障害物。
     146              : func (st *CubeFacilityMenuState) cellKindAt(world w.World, coord consts.Coord[consts.Tile]) (hud.FacilityCellKind, ecs.Entity) {
     147            1 :         if world.Components.GridElement.Get(st.cube).Coord == coord {
     148            1 :                 return hud.FacilityCellCube, ecs.Entity{}
     149            1 :         }
     150            1 :         if e, ok := query.FacilityAt(world, coord); ok {
     151            1 :                 return hud.FacilityCellUsed, e
     152            1 :         }
     153            1 :         if lifecycle.FacilityCellFree(world, st.cube, coord) {
     154            1 :                 return hud.FacilityCellEmpty, ecs.Entity{}
     155            1 :         }
     156            1 :         return hud.FacilityCellBlocked, ecs.Entity{}
     157              : }
     158              : 
     159              : // Draw は展開空間のグリッドを組んで hud へ渡す。uicore の組み立ては hud に閉じ、画面はデータを渡すだけにする
     160              : func (st *CubeFacilityMenuState) Draw(world w.World, screen *ebiten.Image) error {
     161              :         // Update は展開中でなければ Pop するが、遷移フレームで Draw が先に来ても Deployed.Get で
     162              :         // panic しないよう守る。展開空間が無ければ描くものが無い
     163            1 :         if !world.Components.Deployed.Has(st.cube) {
     164            1 :                 return nil
     165            1 :         }
     166            0 :         r := world.Components.Deployed.Get(st.cube).Range
     167            0 :         base := world.Components.GridElement.Get(st.cube).Coord
     168            0 :         cols := 2*int(r.X) + 1
     169            0 :         rows := 2*int(r.Y) + 1
     170            0 : 
     171              :         // マスごとに cellKindAt が LocationOnField を走査するが、展開空間は小さくメニュー1画面の描画なので
     172              :         // 事前のセット化はせず許容する。範囲が大きくなり負荷が問題化したら1度の走査でマップを組む
     173            0 :         cells := make([]hud.FacilityCell, 0, cols*rows)
     174            0 :         for row := range rows {
     175            0 :                 for col := range cols {
     176            0 :                         coord := base.Add(consts.Coord[consts.Tile]{X: consts.Tile(col) - r.X, Y: consts.Tile(row) - r.Y})
     177            0 :                         kind, facility := st.cellKindAt(world, coord)
     178            0 :                         cells = append(cells, hud.FacilityCell{Kind: kind, Icon: st.iconFor(world, kind, facility)})
     179            0 :                 }
     180              :         }
     181              : 
     182            0 :         view := hud.FacilityGridView{
     183            0 :                 Cols:      cols,
     184            0 :                 Rows:      rows,
     185            0 :                 Cells:     cells,
     186            0 :                 CursorCol: int(st.cursor.X + r.X),
     187            0 :                 CursorRow: int(st.cursor.Y + r.Y),
     188            0 :                 Title:     query.T(world, "Facility"),
     189            0 :                 Footer:    query.T(world, "Arrows: Move  Esc: Close"),
     190            0 :         }
     191            0 :         view.Content, view.Hint = st.cursorInfo(world, base.Add(st.cursor))
     192            0 : 
     193            0 :         hud.DrawFacilityGrid(uicore.NewEbitenCanvas(screen), menuframe.WindowRect(world), world.Resources.UIResources.Text.BodyFace, view)
     194            0 :         return nil
     195              : }
     196              : 
     197              : // iconFor はマスに重ねるスプライトを返す。キューブ本体と装着された設備だけ絵を持つ。
     198              : func (st *CubeFacilityMenuState) iconFor(world w.World, kind hud.FacilityCellKind, facility ecs.Entity) *ebiten.Image {
     199            0 :         switch kind {
     200              :         case hud.FacilityCellCube:
     201            0 :                 return menuIcon(world, st.cube)
     202              :         case hud.FacilityCellUsed:
     203            0 :                 return menuIcon(world, facility)
     204            0 :         case hud.FacilityCellEmpty, hud.FacilityCellBlocked:
     205              :         }
     206            0 :         return nil
     207              : }
     208              : 
     209              : // cursorInfo はカーソルのマスの内容名と押せる操作を返す
     210              : func (st *CubeFacilityMenuState) cursorInfo(world w.World, coord consts.Coord[consts.Tile]) (content string, hint string) {
     211            1 :         kind, facility := st.cellKindAt(world, coord)
     212            1 :         switch kind {
     213              :         case hud.FacilityCellCube:
     214            1 :                 return query.T(world, "Cube"), ""
     215              :         case hud.FacilityCellUsed:
     216            1 :                 return query.GetEntityName(facility, world), query.T(world, "Enter: remove")
     217              :         case hud.FacilityCellEmpty:
     218            1 :                 return query.T(world, "Empty"), query.T(world, "Enter: place")
     219              :         default:
     220            0 :                 return query.T(world, "Occupied"), ""
     221              :         }
     222              : }
     223              : 
     224              : // CubeFacilitySelectState は空きマスへ装着する装着アイテムを選ぶメニュー。モジュール選択と同型で、
     225              : // バックパックの装着アイテムを並べ、選ぶと coord へ装着して閉じる。
     226              : type CubeFacilitySelectState struct {
     227              :         es.BaseState[w.World]
     228              :         cube   ecs.Entity
     229              :         coord  consts.Coord[consts.Tile]
     230              :         screen *menuloop.Screen[CubeFacilitySelectProps]
     231              : }
     232              : 
     233              : var _ es.State[w.World] = &CubeFacilitySelectState{}
     234              : 
     235              : // CubeFacilitySelectProps は装着アイテム選択の表示 props
     236              : type CubeFacilitySelectProps struct {
     237              :         Candidates []ecs.Entity // 装着できる装着アイテム。プレイヤーのバックパックから集める
     238              : }
     239              : 
     240              : // newCubeFacilitySelectState は coord への装着アイテム選択を開くファクトリを返す
     241              : func newCubeFacilitySelectState(cube ecs.Entity, coord consts.Coord[consts.Tile]) es.StateFactory[w.World] {
     242            1 :         return func() (es.State[w.World], error) {
     243            0 :                 return &CubeFacilitySelectState{cube: cube, coord: coord}, nil
     244            0 :         }
     245              : }
     246              : 
     247              : // OnStart はステートが開始される際に呼ばれる
     248              : func (st *CubeFacilitySelectState) OnStart(_ w.World) error {
     249            0 :         st.screen = menuloop.NewScreen[CubeFacilitySelectProps](st)
     250            0 :         return nil
     251            0 : }
     252              : 
     253              : // Update はゲームステートの更新処理を行う
     254              : func (st *CubeFacilitySelectState) Update(world w.World) (es.Transition[w.World], error) {
     255            0 :         return st.screen.Update(world)
     256            0 : }
     257              : 
     258              : // Draw はゲームステートの描画処理を行う
     259              : func (st *CubeFacilitySelectState) Draw(_ w.World, screen *ebiten.Image) error {
     260            0 :         st.screen.Draw(screen)
     261            0 :         return nil
     262            0 : }
     263              : 
     264              : // Fetch は世界から表示 props を構築する。候補はプレイヤーのバックパックから集める。
     265              : // プレイヤー不在は握りつぶさず error で返して早期に検知する。
     266              : func (st *CubeFacilitySelectState) Fetch(world w.World) (CubeFacilitySelectProps, error) {
     267            1 :         player, err := query.GetPlayerEntity(world)
     268            1 :         if err != nil {
     269            1 :                 return CubeFacilitySelectProps{}, fmt.Errorf("cube facility select: %w", err)
     270            1 :         }
     271            1 :         return CubeFacilitySelectProps{Candidates: query.BackpackDeployables(world, player)}, nil
     272              : }
     273              : 
     274              : // Menu は単一リストの構成を返す
     275              : func (st *CubeFacilitySelectState) Menu(props CubeFacilitySelectProps) menuloop.MenuConfig {
     276            0 :         return menuloop.MenuConfig{Key: "cube_facility_select", TabCount: 1, ItemCounts: []int{len(props.Candidates)}, ItemsPerPage: menuloop.ItemsPerPageAuto}
     277            0 : }
     278              : 
     279              : // ViewUI は候補一覧を中央パネルへ組む
     280              : func (st *CubeFacilitySelectState) ViewUI(world w.World, props CubeFacilitySelectProps, cursor menuloop.Selection, res resources.UIResources) uicore.Drawable {
     281            0 :         rows := make([]menuframe.Row, 0, len(props.Candidates))
     282            0 :         for _, entity := range props.Candidates {
     283            0 :                 rows = append(rows, menuframe.Row{Cells: []styled.Cell{styled.IconCell(menuIcon(world, entity)), styled.TextCell(query.GetEntityName(entity, world))}})
     284            0 :         }
     285            0 :         list, pager := menuframe.RenderList(cursor.ItemIndex, rows, styled.Cols(styled.Icon(), styled.Name()),
     286            0 :                 menuframe.ListOpts{EmptyText: query.T(world, "No items to deploy")}, res)
     287            0 :         return menuframe.PanelScreen(world, res, query.T(world, "Choose facility"), list, keybind.HelpHint(world), pager)
     288              : }
     289              : 
     290              : // DoAction はActionを実行する。選択で装着して閉じる
     291              : func (st *CubeFacilitySelectState) DoAction(world w.World, action inputmapper.ActionID) (es.Transition[w.World], error) {
     292            0 :         switch action {
     293              :         case inputmapper.ActionMenuCancel, inputmapper.ActionCloseMenu:
     294            0 :                 return es.Transition[w.World]{Type: es.TransPop}, nil
     295              :         case inputmapper.ActionMenuSelect:
     296            0 :                 if err := placeFacilityChoice(world, st.cube, st.coord, st.screen.Props().Candidates, st.screen.Selection().ItemIndex); err != nil {
     297            0 :                         return es.Transition[w.World]{}, err
     298            0 :                 }
     299            0 :                 return es.Transition[w.World]{Type: es.TransPop}, nil
     300              :         default:
     301            0 :                 return es.Transition[w.World]{}, fmt.Errorf("cubeFacilitySelect: unsupported action: %s", action)
     302              :         }
     303              : }
     304              : 
     305              : // placeFacilityChoice は候補一覧の idx を coord へ装着する。範囲外の idx は装着せず nil を返す。
     306              : // 画面の選択状態から装着を切り出し、UI ループを介さずに装着ロジックを試験できるようにする。
     307              : func placeFacilityChoice(world w.World, cube ecs.Entity, coord consts.Coord[consts.Tile], candidates []ecs.Entity, idx int) error {
     308            1 :         if idx < 0 || idx >= len(candidates) {
     309            1 :                 return nil
     310            1 :         }
     311            1 :         _, err := lifecycle.PlaceFacility(world, cube, candidates[idx], coord)
     312            1 :         return err
     313              : }
        

Generated by: LCOV version 2.0-1