LCOV - code coverage report
Current view: top level - states - item_action_state.go Coverage Total Hit
Test: coverage.lcov Lines: 65.1 % 166 108
Test Date: 2026-11-19 00:25:22 Functions: - 0 0

            Line data    Source code
       1              : package states
       2              : 
       3              : import (
       4              :         "fmt"
       5              :         "slices"
       6              : 
       7              :         "github.com/kijimaD/ruins/internal/i18n"
       8              : 
       9              :         "github.com/hajimehoshi/ebiten/v2"
      10              :         "github.com/kijimaD/ruins/internal/activity"
      11              :         gc "github.com/kijimaD/ruins/internal/components"
      12              :         "github.com/kijimaD/ruins/internal/consts"
      13              :         es "github.com/kijimaD/ruins/internal/engine/states"
      14              :         "github.com/kijimaD/ruins/internal/inputmapper"
      15              :         "github.com/kijimaD/ruins/internal/keybind"
      16              :         "github.com/kijimaD/ruins/internal/menuloop"
      17              :         "github.com/kijimaD/ruins/internal/resources"
      18              :         "github.com/kijimaD/ruins/internal/widgets/menuframe"
      19              :         "github.com/kijimaD/ruins/internal/widgets/overlay"
      20              :         "github.com/kijimaD/ruins/internal/widgets/styled"
      21              :         "github.com/kijimaD/ruins/internal/widgets/uicore"
      22              :         w "github.com/kijimaD/ruins/internal/world"
      23              : 
      24              :         "github.com/kijimaD/ruins/internal/world/query"
      25              :         "github.com/mlange-42/ark/ecs"
      26              : )
      27              : 
      28              : // verbID は動詞タブ1つを識別する
      29              : type verbID string
      30              : 
      31              : const (
      32              :         verbExamine     verbID = "examine"     // 調べる
      33              :         verbPlace       verbID = "place"       // 置く
      34              :         verbConsume     verbID = "consume"     // 食べる。飲み物も含む
      35              :         verbRead        verbID = "read"        // 読む
      36              :         verbUse         verbID = "use"         // 使う
      37              :         verbDisassemble verbID = "disassemble" // 分解する
      38              : )
      39              : 
      40              : // itemVerb は動詞タブ1つ分の定義。Accept で対象アイテムを絞り、Exec で選択アイテムへ動詞を適用する。
      41              : // Exec が nil の動詞は実行を持たず、Enter で詳細モーダルを開く。調べるがこれに当たる。
      42              : // 動詞はこの構造体を単一の真実にする。キー・アクション・表示・振る舞いを1行にまとめ、
      43              : // HandleInput のキー変換と verbByAction のアクション対応はこの一覧から導く。追加は1行で足りる。
      44              : type itemVerb struct {
      45              :         ID    verbID
      46              :         Label i18n.Msgid
      47              :         // KeyHint はタブ見出しに添える直達ショートカットの表記。大文字は Shift 併用を表す。
      48              :         // 調べる X は Shift+x、置く d は KeyD をそのまま押す
      49              :         KeyHint string
      50              :         // Key と Shift は直達ショートカットのキー。Shift は同じキーの動詞を Shift の有無で分ける。
      51              :         // Action はそのショートカットが発するアクション。ダンジョン等からの直達もこのアクションで届く
      52              :         Key    ebiten.Key
      53              :         Shift  keybind.ShiftMode
      54              :         Action inputmapper.ActionID
      55              :         Accept func(world w.World, entity ecs.Entity) bool
      56              :         Exec   func(world w.World, entity ecs.Entity) (es.Transition[w.World], error)
      57              : }
      58              : 
      59              : // verbList は表示順に並べた動詞タブの一覧。タブ順を兼ねる。内容は定数なのでパッケージ変数で1度だけ構築する。
      60              : // 投げるは Throwable と ThrowActivity の実装後に足す。
      61              : var verbList = []itemVerb{
      62              :         {
      63              :                 ID:      verbExamine,
      64              :                 Label:   "Inspect",
      65              :                 KeyHint: "X",
      66              :                 Key:     ebiten.KeyX,
      67              :                 Shift:   keybind.ShiftRequired,
      68              :                 Action:  inputmapper.ActionVerbExamine,
      69            1 :                 Accept:  func(_ w.World, _ ecs.Entity) bool { return true },
      70              :                 Exec:    nil,
      71              :         },
      72              :         {
      73              :                 ID:      verbPlace,
      74              :                 Label:   "Drop",
      75              :                 KeyHint: "d",
      76              :                 Key:     ebiten.KeyD,
      77              :                 Shift:   keybind.ShiftForbidden,
      78              :                 Action:  inputmapper.ActionVerbPlace,
      79              :                 // 装着アイテムは設備画面からのみ装着する。素で落とすと展開空間外に設備が残るので落とさせない
      80            1 :                 Accept: func(world w.World, entity ecs.Entity) bool { return !world.Components.Deployable.Has(entity) },
      81              :                 Exec:   execPlace,
      82              :         },
      83              :         {
      84              :                 ID:      verbConsume,
      85              :                 Label:   "Eat",
      86              :                 KeyHint: "e",
      87              :                 Key:     ebiten.KeyE,
      88              :                 Action:  inputmapper.ActionVerbConsume,
      89              :                 Accept:  acceptConsumeFood,
      90              :                 Exec:    execUseItem,
      91              :         },
      92              :         {
      93              :                 ID:      verbRead,
      94              :                 Label:   "Read",
      95              :                 KeyHint: "r",
      96              :                 Key:     ebiten.KeyR,
      97              :                 Action:  inputmapper.ActionVerbRead,
      98            1 :                 Accept:  func(world w.World, entity ecs.Entity) bool { return world.Components.Book.Has(entity) },
      99              :                 Exec:    execRead,
     100              :         },
     101              :         {
     102              :                 ID:      verbUse,
     103              :                 Label:   "Use",
     104              :                 KeyHint: "t",
     105              :                 Key:     ebiten.KeyT,
     106              :                 Action:  inputmapper.ActionVerbUse,
     107              :                 Accept:  acceptUseTool,
     108              :                 Exec:    execUseItem,
     109              :         },
     110              :         {
     111              :                 ID:      verbDisassemble,
     112              :                 Label:   "Disassemble",
     113              :                 KeyHint: "D",
     114              :                 Key:     ebiten.KeyD,
     115              :                 Shift:   keybind.ShiftRequired,
     116              :                 Action:  inputmapper.ActionVerbDisassemble,
     117              :                 Accept:  acceptDisassemble,
     118              :                 Exec:    execDisassemble,
     119              :         },
     120              : }
     121              : 
     122              : // acceptConsumeFood は栄養か回復を持つ消費物を食べるの対象とする。飲み物も含む
     123              : func acceptConsumeFood(world w.World, entity ecs.Entity) bool {
     124            1 :         if !world.Components.Consumable.Has(entity) {
     125            1 :                 return false
     126            1 :         }
     127            1 :         return world.Components.ProvidesNutrition.Has(entity) || world.Components.ProvidesHealing.Has(entity)
     128              : }
     129              : 
     130              : // acceptUseTool は栄養も回復も持たない消費物を使うの対象とする
     131              : func acceptUseTool(world w.World, entity ecs.Entity) bool {
     132            1 :         if !world.Components.Consumable.Has(entity) {
     133            1 :                 return false
     134            1 :         }
     135            1 :         return !world.Components.ProvidesNutrition.Has(entity) && !world.Components.ProvidesHealing.Has(entity)
     136              : }
     137              : 
     138              : // acceptDisassemble は材質の素材に戻せるアイテムを分解するの対象とする
     139              : func acceptDisassemble(world w.World, entity ecs.Entity) bool {
     140            1 :         _, _, ok := query.ItemDisassemblyYield(world, entity)
     141            1 :         return ok
     142            1 : }
     143              : 
     144              : // execDisassemble は選択アイテムの分解を開始しダンジョンへ戻る。分解は重さに応じて複数ターンかかる
     145              : func execDisassemble(world w.World, entity ecs.Entity) (es.Transition[w.World], error) {
     146            0 :         player, err := query.GetPlayerEntity(world)
     147            0 :         if err != nil {
     148            0 :                 return es.Transition[w.World]{}, err
     149            0 :         }
     150            0 :         if _, err := activity.Execute(activity.NewDisassembleActivity(entity, world), player, world); err != nil {
     151            0 :                 return es.Transition[w.World]{}, err
     152            0 :         }
     153            0 :         return es.Transition[w.World]{Type: es.TransPop}, nil
     154              : }
     155              : 
     156              : // execPlace は選択アイテムをプレイヤーの足元に置いてダンジョンへ戻る。置く位置は指定しない
     157              : func execPlace(world w.World, entity ecs.Entity) (es.Transition[w.World], error) {
     158            0 :         player, err := query.GetPlayerEntity(world)
     159            0 :         if err != nil {
     160            0 :                 return es.Transition[w.World]{}, err
     161            0 :         }
     162            0 :         dest := gc.GridElement{Coord: world.Components.GridElement.Get(player).Coord}
     163            0 :         if _, err := activity.Execute(activity.NewDropActivity(entity, dest), player, world); err != nil {
     164            0 :                 return es.Transition[w.World]{}, err
     165            0 :         }
     166            0 :         return es.Transition[w.World]{Type: es.TransPop}, nil
     167              : }
     168              : 
     169              : // execUseItem は選択アイテムへ UseItemBehavior を適用しダンジョンへ戻る。
     170              : // 効果の有無で食べた・使ったのログ文言は UseItemBehavior 側が出し分ける。
     171              : func execUseItem(world w.World, entity ecs.Entity) (es.Transition[w.World], error) {
     172            0 :         player, err := query.GetPlayerEntity(world)
     173            0 :         if err != nil {
     174            0 :                 return es.Transition[w.World]{}, err
     175            0 :         }
     176            0 :         if _, err := activity.Execute(activity.NewUseItemActivity(entity), player, world); err != nil {
     177            0 :                 return es.Transition[w.World]{}, err
     178            0 :         }
     179            0 :         return es.Transition[w.World]{Type: es.TransPop}, nil
     180              : }
     181              : 
     182              : // execRead は選択した本の読書を開始しダンジョンへ戻る。読了は複数ターンにわたりダンジョンの進行が駆動する。
     183              : func execRead(world w.World, entity ecs.Entity) (es.Transition[w.World], error) {
     184            1 :         player, err := query.GetPlayerEntity(world)
     185            1 :         if err != nil {
     186            0 :                 return es.Transition[w.World]{}, err
     187            0 :         }
     188            1 :         act := activity.NewReadActivity(entity, world)
     189            1 :         if _, err := activity.Execute(act, player, world); err != nil {
     190              :                 // Execute が返すエラーはシステムの致命エラーだけ。最上位まで伝播させる。
     191              :                 // スキル不足や周囲の敵などのユーザー起因の失敗は Execute が gamelog へ出したうえで
     192              :                 // err=nil を返すため、ここには来ず通常どおり閉じる
     193            0 :                 return es.Transition[w.World]{}, err
     194            0 :         }
     195            1 :         return es.Transition[w.World]{Type: es.TransPop}, nil
     196              : }
     197              : 
     198              : // verbByAction はダンジョン等からの直達アクションを対応する動詞へ対応づける。verbList から導く
     199              : func verbByAction(action inputmapper.ActionID) (verbID, bool) {
     200            1 :         for _, v := range verbList {
     201            1 :                 if v.Action == action {
     202            1 :                         return v.ID, true
     203            1 :                 }
     204              :         }
     205            1 :         return "", false
     206              : }
     207              : 
     208              : // verbTabIndex は動詞のタブ位置を返す
     209              : func verbTabIndex(id verbID) int {
     210            1 :         for i, v := range verbList {
     211            1 :                 if v.ID == id {
     212            1 :                         return i
     213            1 :                 }
     214              :         }
     215            1 :         return 0
     216              : }
     217              : 
     218              : const itemActionMenuKey = "item_action"
     219              : 
     220              : // ItemActionState は動詞タブ画面のステート。上部の動詞タブを切り替え、その動詞に使えるアイテムだけを
     221              : // 名前のみで一覧する。Enter で即実行しダンジョンへ戻る。x で選択中アイテムの詳細モーダルを開く。
     222              : type ItemActionState struct {
     223              :         es.BaseState[w.World]
     224              :         initialVerb verbID         // 開いた直後に表示する動詞タブ
     225              :         detail      overlay.Detail // 詳細モーダル。overlay として Screen に登録する
     226              :         screen      *menuloop.Screen[ItemActionProps]
     227              : }
     228              : 
     229              : var _ es.State[w.World] = &ItemActionState{}
     230              : var _ menuloop.KeyBindings = &ItemActionState{}
     231              : 
     232              : // NewItemActionState は動詞タブ画面を initial のタブで開くファクトリを返す
     233              : func NewItemActionState(initial verbID) es.StateFactory[w.World] {
     234            1 :         return func() (es.State[w.World], error) {
     235            1 :                 return &ItemActionState{initialVerb: initial}, nil
     236            1 :         }
     237              : }
     238              : 
     239              : // OnStart はステートが開始される際に呼ばれる
     240              : func (st *ItemActionState) OnStart(_ w.World) error {
     241            1 :         st.detail = overlay.NewEntityDetail(st.selectedEntity)
     242            1 :         st.screen = menuloop.NewScreen[ItemActionProps](st, &st.detail)
     243            1 :         return nil
     244            1 : }
     245              : 
     246              : // Update はステートの更新処理
     247              : func (st *ItemActionState) Update(world w.World) (es.Transition[w.World], error) {
     248            1 :         return st.screen.Update(world)
     249            1 : }
     250              : 
     251              : // Draw はステートの描画処理
     252              : func (st *ItemActionState) Draw(_ w.World, screen *ebiten.Image) error {
     253            1 :         st.screen.Draw(screen)
     254            1 :         return nil
     255            1 : }
     256              : 
     257              : // itemActionBindings は詳細モーダルの x と動詞ショートカットの束縛表。verbList から導くので
     258              : // 動詞の追加で列挙は要らない。Shift 無しの x は動詞でなく詳細モーダルを開く。
     259              : // Shift+x の調べるとキーを共有するので、詳細の束縛を先頭に置く。verbList は定数なので1度だけ組む
     260              : var itemActionBindings = func() []keybind.Binding {
     261            1 :         bindings := slices.Clone(detailOpenBindings)
     262            1 :         for _, v := range verbList {
     263            1 :                 bindings = append(bindings, keybind.Binding{Key: v.Key, Shift: v.Shift, Action: v.Action})
     264            1 :         }
     265            1 :         return bindings
     266              : }()
     267              : 
     268              : // KeyBindings は動詞タブへの直達キーを共通入力に足す
     269              : func (st *ItemActionState) KeyBindings() []keybind.Binding {
     270            1 :         return itemActionBindings
     271            1 : }
     272              : 
     273              : // DoAction は Action を実行する
     274              : func (st *ItemActionState) DoAction(world w.World, action inputmapper.ActionID) (es.Transition[w.World], error) {
     275            1 :         switch action {
     276              :         case inputmapper.ActionMenuCancel, inputmapper.ActionCloseMenu:
     277            0 :                 return es.Transition[w.World]{Type: es.TransPop}, nil
     278              :         case inputmapper.ActionOpenItemDetail:
     279            1 :                 st.detail.Open(world)
     280            1 :                 return es.Transition[w.World]{Type: es.TransNone}, nil
     281              :         case inputmapper.ActionMenuSelect:
     282            0 :                 return st.executeSelected(world)
     283              :         default:
     284              :                 // 動詞の直達キーは対応タブへジャンプする。verbList から導くので動詞追加で列挙は要らない
     285            1 :                 if v, ok := verbByAction(action); ok {
     286            1 :                         st.jumpToTab(v)
     287            1 :                         return es.Transition[w.World]{Type: es.TransNone}, nil
     288            1 :                 }
     289            0 :                 return es.Transition[w.World]{}, fmt.Errorf("unknown action: %s", action)
     290              :         }
     291              : }
     292              : 
     293              : func (st *ItemActionState) jumpToTab(target verbID) {
     294            1 :         st.screen.SetTab(verbTabIndex(target))
     295            1 : }
     296              : 
     297              : // executeSelected は選択中アイテムへ現在の動詞を適用する。Exec を持たない調べるは詳細モーダルを開く
     298              : func (st *ItemActionState) executeSelected(world w.World) (es.Transition[w.World], error) {
     299            0 :         cursor := st.screen.Selection()
     300            0 :         vs := verbList
     301            0 :         if cursor.TabIndex >= len(vs) {
     302            0 :                 return es.Transition[w.World]{Type: es.TransNone}, nil
     303            0 :         }
     304            0 :         verb := vs[cursor.TabIndex]
     305            0 :         if verb.Exec == nil {
     306            0 :                 st.detail.Open(world)
     307            0 :                 return es.Transition[w.World]{Type: es.TransNone}, nil
     308            0 :         }
     309              : 
     310            0 :         props := st.screen.Props()
     311            0 :         tab := props.Tabs[cursor.TabIndex]
     312            0 :         if cursor.ItemIndex >= len(tab.Items) {
     313            0 :                 return es.Transition[w.World]{Type: es.TransNone}, nil
     314            0 :         }
     315            0 :         return verb.Exec(world, tab.Items[cursor.ItemIndex].Entity)
     316              : }
     317              : 
     318              : // ================
     319              : // Props
     320              : // ================
     321              : 
     322              : // ItemActionProps は画面の表示 props。menuloop.Screen の型引数として渡す
     323              : type ItemActionProps struct {
     324              :         Tabs []verbTabData
     325              : }
     326              : 
     327              : type verbTabData struct {
     328              :         ID    verbID
     329              :         Label string
     330              :         Key   string // タブ見出しに添える直達ショートカット表記
     331              :         Items []itemRowData
     332              : }
     333              : 
     334              : // Fetch は世界から表示 props を構築する。menuloop.Model の Model 部にあたる。
     335              : // アイテムメニューはプレイヤーの操作でしか開かないので、プレイヤー不在は不変条件違反として返す
     336              : func (st *ItemActionState) Fetch(world w.World) (ItemActionProps, error) {
     337            1 :         player, err := query.GetPlayerEntity(world)
     338            1 :         if err != nil {
     339            0 :                 return ItemActionProps{}, err
     340            0 :         }
     341            1 :         backpack := query.BackpackStacks(world, player)
     342            1 : 
     343            1 :         vs := verbList
     344            1 :         tabs := make([]verbTabData, len(vs))
     345            1 :         for i, verb := range vs {
     346            1 :                 items := make([]itemRowData, 0, len(backpack))
     347            1 :                 for _, stack := range backpack {
     348            1 :                         if !verb.Accept(world, stack.Rep) {
     349            1 :                                 continue
     350              :                         }
     351            1 :                         items = append(items, newItemActionEntry(world, stack))
     352              :                 }
     353            1 :                 tabs[i] = verbTabData{ID: verb.ID, Label: query.T(world, verb.Label), Key: verb.KeyHint, Items: items}
     354              :         }
     355            1 :         return ItemActionProps{Tabs: tabs}, nil
     356              : }
     357              : 
     358              : func newItemActionEntry(world w.World, stack query.Stack) itemRowData {
     359              :         // 1行は1スタックなので、重量は個数分の合計にして行内の粒度を名前の個数と揃える。
     360              :         // 1個分の値は詳細モーダルが受け持つ
     361            1 :         total := query.GetEntityWeight(world, stack.Rep) * consts.Milligram(stack.Count)
     362            1 :         entry := itemRowData{
     363            1 :                 Entity: stack.Rep,
     364            1 :                 Name:   query.GetEntityName(stack.Rep, world),
     365            1 :                 Weight: total.KgString(),
     366            1 :                 Count:  stack.Count,
     367            1 :         }
     368            1 :         if world.Components.Description.Has(stack.Rep) {
     369            1 :                 entry.Desc = query.T(world, world.Components.Description.Get(stack.Rep).Description)
     370            1 :         }
     371            1 :         return entry
     372              : }
     373              : 
     374              : // ================
     375              : // View
     376              : // ================
     377              : 
     378              : // Menu は一覧の構成を返す。menuloop.Model の Menu 部にあたる
     379              : func (st *ItemActionState) Menu(props ItemActionProps) menuloop.MenuConfig {
     380            1 :         itemCounts := make([]int, len(props.Tabs))
     381            1 :         for i, tab := range props.Tabs {
     382            1 :                 itemCounts[i] = len(tab.Items)
     383            1 :         }
     384            1 :         return menuloop.MenuConfig{Key: itemActionMenuKey, TabCount: len(props.Tabs), ItemCounts: itemCounts, ItemsPerPage: menuloop.ItemsPerPageAuto, InitialTab: verbTabIndex(st.initialVerb)}
     385              : }
     386              : 
     387              : // ViewUI は動詞タブとアイコン付きアイテム一覧を組む。
     388              : func (st *ItemActionState) ViewUI(world w.World, props ItemActionProps, cursor menuloop.Selection, res resources.UIResources) uicore.Drawable {
     389            1 :         labels := make([]string, len(props.Tabs))
     390            1 :         for i, tab := range props.Tabs {
     391            1 :                 if tab.Key != "" {
     392            1 :                         labels[i] = fmt.Sprintf("%s(%s)", tab.Label, tab.Key)
     393            1 :                 } else {
     394            0 :                         labels[i] = tab.Label
     395            0 :                 }
     396              :         }
     397            1 :         content, pager := st.buildItemListUI(world, props, cursor.TabIndex, cursor.ItemIndex, cursor.PageSize, res)
     398            1 :         return menuframe.TabScreen(world, res, "", labels, cursor.TabIndex, content, keybind.HelpHint(world), pager)
     399              : }
     400              : 
     401              : // buildItemListUI は行列とフッタ右端のページ表示を返す。
     402              : func (st *ItemActionState) buildItemListUI(world w.World, props ItemActionProps, tabIndex, itemIndex, perPage int, res resources.UIResources) ([]uicore.Drawable, string) {
     403            1 :         if tabIndex >= len(props.Tabs) {
     404            0 :                 return nil, ""
     405            0 :         }
     406            1 :         items := props.Tabs[tabIndex].Items
     407            1 :         cols := itemMenuColumns(styled.Num())
     408            1 :         rows := make([]menuframe.Row, len(items))
     409            1 :         for i, it := range items {
     410            1 :                 rows[i] = itemMenuRow(world, it.Entity, it.Count, it.Weight)
     411            1 :         }
     412            1 :         return menuframe.RenderList(itemIndex, rows, cols, menuframe.ListOpts{EmptyText: query.T(world, "No matching items"), ItemsPerPage: perPage}, res)
     413              : }
     414              : 
     415              : // selectedEntity は現在カーソルが当たっているアイテムのエンティティを返す
     416              : func (st *ItemActionState) selectedEntity() (ecs.Entity, bool) {
     417            1 :         props := st.screen.Props()
     418            1 :         cursor := st.screen.Selection()
     419            1 :         if cursor.TabIndex >= len(props.Tabs) {
     420            0 :                 return gc.InvalidEntity, false
     421            0 :         }
     422            1 :         items := props.Tabs[cursor.TabIndex].Items
     423            1 :         if cursor.ItemIndex >= len(items) {
     424            0 :                 return gc.InvalidEntity, false
     425            0 :         }
     426            1 :         return items[cursor.ItemIndex].Entity, true
     427              : }
        

Generated by: LCOV version 2.0-1