LCOV - code coverage report
Current view: top level - states - shop_menu.go Coverage Total Hit
Test: coverage.lcov Lines: 68.5 % 124 85
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/inputmapper"
      10              :         "github.com/kijimaD/ruins/internal/keybind"
      11              :         "github.com/kijimaD/ruins/internal/menuloop"
      12              :         "github.com/kijimaD/ruins/internal/resources"
      13              :         gs "github.com/kijimaD/ruins/internal/systems"
      14              :         "github.com/kijimaD/ruins/internal/widgets/menuframe"
      15              :         "github.com/kijimaD/ruins/internal/widgets/overlay"
      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              : 
      20              :         "github.com/kijimaD/ruins/internal/world/gameaction"
      21              :         "github.com/kijimaD/ruins/internal/world/query"
      22              :         "github.com/mlange-42/ark/ecs"
      23              : )
      24              : 
      25              : // ShopMenuState はショップメニューのゲームステート。
      26              : // 商人の在庫を売買する。買うと在庫が減り、売ると売った品が在庫に並ぶ
      27              : type ShopMenuState struct {
      28              :         es.BaseState[w.World]
      29              :         merchant ecs.Entity     // 品揃えを LocationInStorage で持つ商人。売買の相手
      30              :         detail   overlay.Detail // 詳細モーダル。overlay として Screen に登録する
      31              :         screen   *menuloop.Screen[ShopProps]
      32              : }
      33              : 
      34              : // State interface ================
      35              : 
      36              : var _ es.State[w.World] = &ShopMenuState{}
      37              : 
      38              : // shopSellTabID は売却タブの識別子。空表示の文言分岐に使う。
      39              : const shopSellTabID = "sell"
      40              : 
      41              : var _ menuloop.KeyBindings = &ShopMenuState{}
      42              : 
      43              : // OnStart はステートが開始される際に呼ばれる
      44              : func (st *ShopMenuState) OnStart(_ w.World) error {
      45            1 :         st.detail = overlay.NewEntityDetail(func() (ecs.Entity, bool) {
      46            1 :                 it, ok := st.selectedShopItem()
      47            1 :                 return it.Entity, ok
      48            1 :         })
      49            1 :         st.screen = menuloop.NewScreen[ShopProps](st, &st.detail)
      50            1 :         return nil
      51              : }
      52              : 
      53              : // Update はゲームステートの更新処理を行う
      54              : func (st *ShopMenuState) Update(world w.World) (es.Transition[w.World], error) {
      55              :         // 売買で所持品が変わると WeightDirty が立つ。この画面でも再計算を回し、総重量の表示を売買のたびに更新する
      56            1 :         if err := runUpdaters(world, &gs.WeightDirtySystem{}); err != nil {
      57            0 :                 return es.Transition[w.World]{}, err
      58            0 :         }
      59            1 :         return st.screen.Update(world)
      60              : }
      61              : 
      62              : // Draw はゲームステートの描画処理を行う
      63              : func (st *ShopMenuState) Draw(_ w.World, screen *ebiten.Image) error {
      64            1 :         st.screen.Draw(screen)
      65            1 :         return nil
      66            1 : }
      67              : 
      68              : // KeyBindings は x の詳細表示を共通入力に足す
      69              : func (st *ShopMenuState) KeyBindings() []keybind.Binding {
      70            1 :         return detailOpenBindings
      71            1 : }
      72              : 
      73              : // DoAction はActionを実行する
      74              : func (st *ShopMenuState) DoAction(world w.World, action inputmapper.ActionID) (es.Transition[w.World], error) {
      75            1 :         switch action {
      76              :         case inputmapper.ActionMenuCancel, inputmapper.ActionCloseMenu:
      77            1 :                 return es.Transition[w.World]{Type: es.TransPop}, nil
      78              :         case inputmapper.ActionOpenItemDetail:
      79            0 :                 st.detail.Open(world)
      80              :         case inputmapper.ActionMenuSelect:
      81            1 :                 if err := st.buySellSelected(world); err != nil {
      82            0 :                         return es.Transition[w.World]{}, err
      83            0 :                 }
      84              :         default:
      85            0 :                 return es.Transition[w.World]{}, fmt.Errorf("shopMenu: unsupported action: %s", action)
      86              :         }
      87            1 :         return es.Transition[w.World]{Type: es.TransNone}, nil
      88              : }
      89              : 
      90              : // ================
      91              : // Props
      92              : // ================
      93              : 
      94              : // ShopProps は画面の表示 props。menuloop.Screen の型引数として渡す
      95              : type ShopProps struct {
      96              :         Tabs []shopTabData
      97              : }
      98              : 
      99              : type shopTabData struct {
     100              :         ID    string
     101              :         Label string
     102              :         Items []shopItemData
     103              : }
     104              : 
     105              : // shopItemData は一覧1行分。1行は1スタックで、売買はスタック丸ごと行う。
     106              : // 名前・重量・個数は実体から都度出せるので持たず、プレイヤーの所持金や倍率が要る値だけを持つ
     107              : type shopItemData struct {
     108              :         Entity   ecs.Entity      // スタック代表の実体。表示も操作もこれから解決する
     109              :         Count    int             // スタックの個数。束ねた結果を持ち回り、行ごとに数え直さない
     110              :         Price    consts.Currency // 行の合計額。単価は価値と交渉スキルの倍率から出し、スタック個数を掛ける
     111              :         IsBuy    bool            // 買いタブの行なら真
     112              :         Disabled bool            // 所持金が足りず選べない
     113              : }
     114              : 
     115              : // Fetch は世界から表示 props を構築する。menuloop.Model の Model 部にあたる。
     116              : // ショップはプレイヤーの操作でしか開かないので、プレイヤー不在は不変条件違反として返す。
     117              : // 価格は query.BuyPrice/SellPrice が取引と揃えて出す
     118              : func (st *ShopMenuState) Fetch(world w.World) (ShopProps, error) {
     119            1 :         player, err := query.GetPlayerEntity(world)
     120            1 :         if err != nil {
     121            0 :                 return ShopProps{}, err
     122            0 :         }
     123            1 :         currency := query.GetCurrency(world, player)
     124            1 : 
     125            1 :         return ShopProps{
     126            1 :                 Tabs: []shopTabData{
     127            1 :                         {ID: "buy", Label: query.T(world, "Buy"), Items: st.createBuyItems(world, player, currency)},
     128            1 :                         {ID: shopSellTabID, Label: query.T(world, "Sell"), Items: st.createSellItems(world, player)},
     129            1 :                 },
     130            1 :         }, nil
     131              : }
     132              : 
     133              : // Menu は一覧の構成を返す。menuloop.Model の Menu 部にあたる
     134              : func (st *ShopMenuState) Menu(props ShopProps) menuloop.MenuConfig {
     135            1 :         itemCounts := make([]int, len(props.Tabs))
     136            1 :         for i, tab := range props.Tabs {
     137            1 :                 itemCounts[i] = len(tab.Items)
     138            1 :         }
     139            1 :         return menuloop.MenuConfig{Key: "shop", TabCount: len(props.Tabs), ItemCounts: itemCounts, ItemsPerPage: menuloop.ItemsPerPageAuto}
     140              : }
     141              : 
     142              : // createBuyItems は商人の在庫アイテムを買いタブへ並べる。同一スタックは1行に束ね、
     143              : // 額はスタック個数分の合計にする。購入はスタック丸ごとなので、表示額と支払額が一致する
     144              : func (st *ShopMenuState) createBuyItems(world w.World, player ecs.Entity, currency consts.Currency) []shopItemData {
     145            1 :         stacks := query.StorageStacks(world, st.merchant)
     146            1 :         items := make([]shopItemData, 0, len(stacks))
     147            1 : 
     148            1 :         for _, stack := range stacks {
     149              :                 // BuyPrice は価値×スタック個数で既に全量の額を返す
     150            1 :                 total := query.BuyPrice(world, player, stack.Rep)
     151            1 :                 items = append(items, shopItemData{
     152            1 :                         Entity:   stack.Rep,
     153            1 :                         Count:    stack.Count,
     154            1 :                         Price:    total,
     155            1 :                         IsBuy:    true,
     156            1 :                         Disabled: currency < total,
     157            1 :                 })
     158            1 :         }
     159              : 
     160            1 :         return items
     161              : }
     162              : 
     163              : // createSellItems はプレイヤーの持ち物を売りタブへ並べる。売ると実体が商人の在庫へ移る。
     164              : // 同一スタックは1行に束ね、額はスタック個数分の合計にする
     165              : func (st *ShopMenuState) createSellItems(world w.World, player ecs.Entity) []shopItemData {
     166            1 :         stacks := query.BackpackStacks(world, player)
     167            1 :         items := make([]shopItemData, 0, len(stacks))
     168            1 :         for _, stack := range stacks {
     169              :                 // SellPrice は価値×スタック個数で既に全量の額を返す
     170            1 :                 items = append(items, shopItemData{
     171            1 :                         Entity: stack.Rep,
     172            1 :                         Count:  stack.Count,
     173            1 :                         Price:  query.SellPrice(world, player, stack.Rep),
     174            1 :                         IsBuy:  false,
     175            1 :                 })
     176            1 :         }
     177              : 
     178            1 :         return items
     179              : }
     180              : 
     181              : // ================
     182              : // Window
     183              : // ================
     184              : 
     185              : // buySellSelected は現在カーソルが当たっている行を、買いタブなら購入・雇用、売りタブなら売却する。
     186              : // 決定で即実行し、途中のアクション選択は挟まない。購入・雇用は所持金が足りなければ何もしない
     187              : func (st *ShopMenuState) buySellSelected(world w.World) error {
     188            1 :         item, ok := st.selectedShopItem()
     189            1 :         if !ok {
     190            1 :                 return nil
     191            1 :         }
     192            0 :         if item.IsBuy {
     193            0 :                 canAfford := false
     194            0 :                 query.Player(world, func(p ecs.Entity) { canAfford = query.GetCurrency(world, p) >= item.Price })
     195            0 :                 if !canAfford {
     196            0 :                         return nil
     197            0 :                 }
     198              :                 // 選択が古く実体が消えていれば何もしない。dead entity への Has/移動は panic するため先に守る
     199            0 :                 if !world.ECS.Alive(item.Entity) {
     200            0 :                         return nil
     201            0 :                 }
     202            0 :                 var err error
     203            0 :                 query.Player(world, func(p ecs.Entity) { err = gameaction.BuyStock(world, p, item.Entity) })
     204            0 :                 if err != nil {
     205            0 :                         return fmt.Errorf("failed to buy: %w", err)
     206            0 :                 }
     207            0 :                 return nil
     208              :         }
     209              :         // 選択が古く実体が消えていれば何もしない。dead entity への移動は panic するため先に守る
     210            0 :         if !world.ECS.Alive(item.Entity) {
     211            0 :                 return nil
     212            0 :         }
     213            0 :         var err error
     214            0 :         query.Player(world, func(p ecs.Entity) { err = gameaction.SellStock(world, p, st.merchant, item.Entity) })
     215            0 :         if err != nil {
     216            0 :                 return fmt.Errorf("failed to sell: %w", err)
     217            0 :         }
     218            0 :         return nil
     219              : }
     220              : 
     221              : // selectedShopItem は現在カーソルが当たっている行を返す
     222              : func (st *ShopMenuState) selectedShopItem() (shopItemData, bool) {
     223            1 :         props := st.screen.Props()
     224            1 :         cursor := st.screen.Selection()
     225            1 :         if cursor.TabIndex >= len(props.Tabs) {
     226            1 :                 return shopItemData{}, false
     227            1 :         }
     228            0 :         items := props.Tabs[cursor.TabIndex].Items
     229            0 :         if cursor.ItemIndex >= len(items) {
     230            0 :                 return shopItemData{}, false
     231            0 :         }
     232            0 :         return items[cursor.ItemIndex], true
     233              : }
     234              : 
     235              : // ================
     236              : // View
     237              : // ================
     238              : 
     239              : // ViewUI は購入・売却タブとアイコン付き商品一覧を組む。
     240              : func (st *ShopMenuState) ViewUI(world w.World, props ShopProps, cursor menuloop.Selection, res resources.UIResources) uicore.Drawable {
     241            1 :         labels := make([]string, len(props.Tabs))
     242            1 :         for i, tab := range props.Tabs {
     243            1 :                 labels[i] = tab.Label
     244            1 :         }
     245            1 :         content, pager := st.buildItemListUI(world, props.Tabs, cursor.TabIndex, cursor.ItemIndex, cursor.PageSize, res)
     246            1 :         return menuframe.TabScreen(world, res, "", labels, cursor.TabIndex, content, keybind.HelpHint(world), pager)
     247              : }
     248              : 
     249              : // buildItemListUI は行列とフッタ右端のページ表示を返す。
     250              : func (st *ShopMenuState) buildItemListUI(world w.World, tabs []shopTabData, tabIndex, itemIndex, perPage int, res resources.UIResources) ([]uicore.Drawable, string) {
     251            1 :         if tabIndex >= len(tabs) {
     252            0 :                 return nil, ""
     253            0 :         }
     254            1 :         currentTab := tabs[tabIndex]
     255            1 :         cols := itemMenuColumns(styled.Num(), styled.Num())
     256            1 :         rows := make([]menuframe.Row, len(currentTab.Items))
     257            1 :         for i, it := range currentTab.Items {
     258            1 :                 total := query.GetEntityWeight(world, it.Entity) * consts.Milligram(it.Count)
     259            1 :                 rows[i] = itemMenuRow(world, it.Entity, it.Count, it.Price.String(), total.KgString())
     260            1 :         }
     261            1 :         emptyText := query.T(world, "No goods")
     262            1 :         if currentTab.ID == shopSellTabID {
     263            1 :                 emptyText = query.T(world, "No items to sell")
     264            1 :         }
     265            1 :         return menuframe.RenderList(itemIndex, rows, cols, menuframe.ListOpts{EmptyText: emptyText, ItemsPerPage: perPage}, res)
     266              : }
        

Generated by: LCOV version 2.0-1