LCOV - code coverage report
Current view: top level - states - character_state.go Coverage Total Hit
Test: coverage.lcov Lines: 70.8 % 216 153
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/kijimaD/ruins/internal/i18n"
       7              : 
       8              :         "github.com/hajimehoshi/ebiten/v2"
       9              :         gc "github.com/kijimaD/ruins/internal/components"
      10              :         es "github.com/kijimaD/ruins/internal/engine/states"
      11              :         "github.com/kijimaD/ruins/internal/gamelog"
      12              :         "github.com/kijimaD/ruins/internal/inputmapper"
      13              :         "github.com/kijimaD/ruins/internal/keybind"
      14              :         "github.com/kijimaD/ruins/internal/menuloop"
      15              :         "github.com/kijimaD/ruins/internal/raw"
      16              :         "github.com/kijimaD/ruins/internal/rawschema"
      17              :         gs "github.com/kijimaD/ruins/internal/systems"
      18              :         "github.com/kijimaD/ruins/internal/widgets/entityspec"
      19              :         "github.com/kijimaD/ruins/internal/widgets/overlay"
      20              :         w "github.com/kijimaD/ruins/internal/world"
      21              : 
      22              :         "github.com/kijimaD/ruins/internal/world/query"
      23              :         "github.com/mlange-42/ark/ecs"
      24              : )
      25              : 
      26              : // 画面タブメニュー。キャラクター情報の閲覧・操作を装備・スキルのタブでまとめる。
      27              : // 所持アイテムへの動詞でなくキャラクター情報が対象なので、動詞タブ画面とは別 state にする。
      28              : // ダンジョンからの直達ショートカットは持たず、ダンジョンメニューから開く。
      29              : 
      30              : const characterMenuKey = "character"
      31              : 
      32              : // charTab は画面タブの種別。装備は編集可能、以降は読み取り専用の情報タブ
      33              : type charTab string
      34              : 
      35              : const (
      36              :         charTabEquip   charTab = "equip"   // 装備。編集可能
      37              :         charTabAbility charTab = "ability" // 能力
      38              :         charTabSkill   charTab = "skill"   // スキル
      39              :         charTabEffect  charTab = "effect"  // 効果
      40              :         charTabHealth  charTab = "health"  // 健康
      41              :         charTabBasic   charTab = "basic"   // 基本
      42              : )
      43              : 
      44              : // characterTabs はタブの種別と見出しを表示順に対応づける。タブ番号はこの並び順で決まる。
      45              : // 編集可能な装備の後ろに読み取り専用の情報タブが並ぶ
      46              : var characterTabs = []struct {
      47              :         Kind  charTab
      48              :         Label i18n.Msgid
      49              : }{
      50              :         {charTabEquip, "Equipment"},
      51              :         {charTabAbility, "Abilities"},
      52              :         {charTabSkill, "Skills"},
      53              :         {charTabEffect, "Effects"},
      54              :         {charTabHealth, "Health"},
      55              :         {charTabBasic, "Basic"},
      56              : }
      57              : 
      58              : // charFirstInfoTab は情報タブが始まるタブ番号。編集タブの装備の後に情報タブが並ぶ。
      59              : // 先頭の情報タブ ability の位置から導き、編集タブを増減しても追従させる。マジックナンバーを避ける
      60              : var charFirstInfoTab = indexOfCharTab(charTabAbility)
      61              : 
      62              : // indexOfCharTab はタブ種別の表示順での位置を返す。見つからなければ 0
      63              : func indexOfCharTab(kind charTab) int {
      64            1 :         for i, t := range characterTabs {
      65            1 :                 if t.Kind == kind {
      66            1 :                         return i
      67            1 :                 }
      68              :         }
      69            0 :         return 0
      70              : }
      71              : 
      72              : // charTabAt はタブ番号に対応するタブ種別を返す。範囲外は空文字を返す
      73              : func charTabAt(index int) charTab {
      74            1 :         if index < 0 || index >= len(characterTabs) {
      75            0 :                 return ""
      76            0 :         }
      77            1 :         return characterTabs[index].Kind
      78              : }
      79              : 
      80              : // characterTabLabels はタブの見出し一覧を現在言語で表示順に返す
      81              : func characterTabLabels(world w.World) []string {
      82            1 :         labels := make([]string, len(characterTabs))
      83            1 :         for i, t := range characterTabs {
      84            1 :                 labels[i] = query.T(world, t.Label)
      85            1 :         }
      86            1 :         return labels
      87              : }
      88              : 
      89              : // CharacterState は画面タブメニューのステート。主人公の装備と情報を閲覧・編集する
      90              : type CharacterState struct {
      91              :         es.BaseState[w.World]
      92              :         detail overlay.Detail // 詳細モーダル。overlay として Screen に登録する
      93              :         screen *menuloop.Screen[CharacterProps]
      94              : }
      95              : 
      96              : var _ es.State[w.World] = &CharacterState{}
      97              : var _ menuloop.KeyBindings = &CharacterState{}
      98              : 
      99              : // OnStart はステートが開始される際に呼ばれる
     100              : func (st *CharacterState) OnStart(_ w.World) error {
     101            1 :         st.detail = overlay.NewDetail(st.detailContent)
     102            1 :         st.screen = menuloop.NewScreen[CharacterProps](st, &st.detail)
     103            1 :         return nil
     104            1 : }
     105              : 
     106              : // Update はステートの更新処理を Screen へ委譲する
     107              : func (st *CharacterState) Update(world w.World) (es.Transition[w.World], error) {
     108              :         // 装備の着脱でステータスと重量が変わる。再計算を回して表示を更新する
     109            1 :         if err := runUpdaters(world, &gs.StatsChangedSystem{}, &gs.WeightDirtySystem{}); err != nil {
     110            0 :                 return es.Transition[w.World]{}, err
     111            0 :         }
     112            1 :         return st.screen.Update(world)
     113              : }
     114              : 
     115              : // Draw はステートの描画を Screen へ委譲する
     116              : func (st *CharacterState) Draw(_ w.World, screen *ebiten.Image) error {
     117            1 :         st.screen.Draw(screen)
     118            1 :         return nil
     119            1 : }
     120              : 
     121              : // KeyBindings は共通入力に加える独自キーの束縛表。x で選択中の詳細モーダルを開く
     122              : func (st *CharacterState) KeyBindings() []keybind.Binding {
     123            1 :         return detailOpenBindings
     124            1 : }
     125              : 
     126              : // DoAction は閲覧中の Action を実行する
     127              : func (st *CharacterState) DoAction(world w.World, action inputmapper.ActionID) (es.Transition[w.World], error) {
     128            1 :         switch action {
     129              :         case inputmapper.ActionMenuCancel, inputmapper.ActionCloseMenu:
     130            0 :                 return es.Transition[w.World]{Type: es.TransPop}, nil
     131              :         case inputmapper.ActionOpenItemDetail:
     132            0 :                 st.detail.Open(world)
     133            0 :                 return es.Transition[w.World]{Type: es.TransNone}, nil
     134              :         case inputmapper.ActionMenuSelect:
     135            1 :                 return st.onBrowseSelect(world), nil
     136              :         default:
     137            0 :                 return es.Transition[w.World]{}, fmt.Errorf("unknown action: %s", action)
     138              :         }
     139              : }
     140              : 
     141              : // onBrowseSelect は閲覧中の Enter を処理する。装備タブは装備選択を別 state として push し、
     142              : // 情報タブは詳細を開く
     143              : func (st *CharacterState) onBrowseSelect(world w.World) es.Transition[w.World] {
     144            1 :         cursor := st.screen.Selection()
     145            1 :         props := st.screen.Props()
     146            1 :         switch charTabAt(cursor.TabIndex) {
     147              :         case charTabEquip:
     148            1 :                 if cursor.ItemIndex >= len(props.EquipSlots) {
     149            0 :                         return es.Transition[w.World]{Type: es.TransNone}
     150            0 :                 }
     151            1 :                 return es.Transition[w.World]{
     152            1 :                         Type:          es.TransPush,
     153            1 :                         NewStateFuncs: []es.StateFactory[w.World]{newEquipSelectState(props.EquipSlots[cursor.ItemIndex])},
     154            1 :                 }
     155              :         default:
     156            0 :                 st.detail.Open(world)
     157            0 :                 return es.Transition[w.World]{Type: es.TransNone}
     158              :         }
     159              : }
     160              : 
     161              : // logEquipChange は装備の着脱をゲームログに出す。format は対象キャラ名とアイテム名を差し込む
     162              : // "%s ... %s" 形式の翻訳済み書式。アイテム名はシアンを保つ
     163              : func logEquipChange(world w.World, character ecs.Entity, itemName, format string) {
     164            1 :         characterName := ""
     165            1 :         if world.ECS.Alive(character) && world.Components.Name.Has(character) {
     166            1 :                 characterName = query.GetEntityName(character, world)
     167            1 :         }
     168            1 :         gamelog.New(query.GetGameLog(world)).
     169            1 :                 Markup(fmt.Sprintf(format, characterName, gamelog.Tag("item", itemName))).
     170            1 :                 Log()
     171              : }
     172              : 
     173              : // Fetch は主人公のスナップショットを組む
     174              : func (st *CharacterState) Fetch(world w.World) (CharacterProps, error) {
     175            1 :         player, err := query.GetPlayerEntity(world)
     176            1 :         if err != nil {
     177            0 :                 return CharacterProps{}, err
     178            0 :         }
     179              :         // 死亡直後のフレームは実体が消えている。遷移までの過渡状態なので空表示にする
     180            1 :         if !world.ECS.Alive(player) {
     181            0 :                 return CharacterProps{}, nil
     182            0 :         }
     183            1 :         name := ""
     184            1 :         if world.Components.Name.Has(player) {
     185            1 :                 name = query.GetEntityName(player, world)
     186            1 :         }
     187            1 :         return CharacterProps{
     188            1 :                 TargetName: name,
     189            1 :                 EquipSlots: characterEquipSlots(world, player),
     190            1 :                 InfoTabs:   st.fetchInfoTabs(world, player),
     191            1 :         }, nil
     192              : }
     193              : 
     194              : // Menu は装備・情報タブのカーソル構成を返す。情報タブの見出し行はカーソルを飛ばす
     195              : func (st *CharacterState) Menu(props CharacterProps) menuloop.MenuConfig {
     196            1 :         itemCounts := make([]int, 0, 1+len(props.InfoTabs))
     197            1 :         skips := make([][]bool, 0, 1+len(props.InfoTabs))
     198            1 :         itemCounts = append(itemCounts, len(props.EquipSlots))
     199            1 :         skips = append(skips, make([]bool, len(props.EquipSlots)))
     200            1 :         for _, tab := range props.InfoTabs {
     201            1 :                 itemCounts = append(itemCounts, len(tab.Items))
     202            1 :                 s := make([]bool, len(tab.Items))
     203            1 :                 for i, item := range tab.Items {
     204            1 :                         s[i] = item.IsHeader
     205            1 :                 }
     206            1 :                 skips = append(skips, s)
     207              :         }
     208            1 :         return menuloop.MenuConfig{Key: characterMenuKey, TabCount: len(itemCounts), ItemCounts: itemCounts, Skips: skips}
     209              : }
     210              : 
     211              : // detailContent は現在の対象に応じた詳細内容を返す。詳細モーダルの唯一の定義点。
     212              : // 閲覧中は装備中アイテム・空スロット・情報行を出し分ける
     213              : func (st *CharacterState) detailContent(world w.World) (overlay.DetailContent, bool) {
     214            0 :         cursor := st.screen.Selection()
     215            0 :         props := st.screen.Props()
     216            0 :         switch charTabAt(cursor.TabIndex) {
     217              :         case charTabEquip:
     218            0 :                 if cursor.ItemIndex >= len(props.EquipSlots) {
     219            0 :                         return overlay.DetailContent{}, false
     220            0 :                 }
     221            0 :                 slot := props.EquipSlots[cursor.ItemIndex]
     222            0 :                 if slot.Entity != nil {
     223            0 :                         return overlay.EntityDetailContent(world, *slot.Entity), true
     224            0 :                 }
     225              :                 // 空スロットは性能行を持たず案内だけ出す
     226            0 :                 return overlay.DetailContent{Name: slot.SlotLabel, Desc: query.T(world, "Nothing equipped")}, true
     227              :         default:
     228            0 :                 infoIdx := cursor.TabIndex - charFirstInfoTab
     229            0 :                 if infoIdx < 0 || infoIdx >= len(props.InfoTabs) {
     230            0 :                         return overlay.DetailContent{}, false
     231            0 :                 }
     232            0 :                 tab := props.InfoTabs[infoIdx]
     233            0 :                 if cursor.ItemIndex >= len(tab.Items) {
     234            0 :                         return overlay.DetailContent{}, false
     235            0 :                 }
     236            0 :                 item := tab.Items[cursor.ItemIndex]
     237            0 :                 if tab.ID == tabHealth {
     238            0 :                         return healthDetailContent(world, item), true
     239            0 :                 }
     240            0 :                 return infoDetailContent(item), true
     241              :         }
     242              : }
     243              : 
     244              : // ================
     245              : // Props
     246              : // ================
     247              : 
     248              : // CharacterProps は画面の表示 props。menuloop.Screen の型引数として渡す
     249              : type CharacterProps struct {
     250              :         TargetName string          // 表示対象のキャラクター名
     251              :         EquipSlots []equipItemData //
     252              :         InfoTabs   []statusTabData // 能力・スキル・効果・健康・基本の読み取り専用タブ
     253              : }
     254              : 
     255              : // equipItemData は装備スロット1つ分の表示データ
     256              : type equipItemData struct {
     257              :         SlotLabel  string
     258              :         ItemName   string
     259              :         SlotNumber gc.EquipmentSlotNumber
     260              :         Entity     *ecs.Entity // 装備中エンティティ。空きなら nil
     261              :         Character  ecs.Entity  // 装備スロットを持つキャラ本体
     262              : }
     263              : 
     264              : // characterEquipSlots は指定したキャラクターの全装備スロットを列挙する
     265              : func characterEquipSlots(world w.World, character ecs.Entity) []equipItemData {
     266            1 :         items := make([]equipItemData, 0, 12)
     267            1 : 
     268            1 :         weapons := query.GetWeapons(world, character)
     269            1 :         weaponSlots := []gc.EquipmentSlotNumber{gc.SlotWeapon1, gc.SlotWeapon2, gc.SlotWeapon3, gc.SlotWeapon4, gc.SlotWeapon5}
     270            1 :         for i, weapon := range weapons {
     271            1 :                 name := ""
     272            1 :                 if weapon != nil {
     273            1 :                         name = query.GetEntityName(*weapon, world)
     274            1 :                 }
     275            1 :                 items = append(items, equipItemData{SlotLabel: query.T(world, "Weapon %d", i+1), ItemName: name, SlotNumber: weaponSlots[i], Entity: weapon, Character: character})
     276              :         }
     277              : 
     278              :         // armor・armorLabels・armorSlots は防具7スロットに対応する並行配列。
     279              :         // GetArmorEquipments はスロット数ぶんの固定長スライスを返し、3者の長さは常に一致する
     280            1 :         armor := query.GetArmorEquipments(world, character)
     281            1 :         armorLabels := []string{query.T(world, "Armor (head)"), query.T(world, "Armor (torso)"), query.T(world, "Armor (arms)"), query.T(world, "Armor (hands)"), query.T(world, "Armor (legs)"), query.T(world, "Armor (feet)"), query.T(world, "Armor (jewelry)")}
     282            1 :         armorSlots := []gc.EquipmentSlotNumber{gc.SlotHead, gc.SlotTorso, gc.SlotArms, gc.SlotHands, gc.SlotLegs, gc.SlotFeet, gc.SlotJewelry}
     283            1 :         for i, slot := range armor {
     284            1 :                 name := ""
     285            1 :                 if slot != nil {
     286            1 :                         name = query.GetEntityName(*slot, world)
     287            1 :                 }
     288            1 :                 items = append(items, equipItemData{SlotLabel: armorLabels[i], ItemName: name, SlotNumber: armorSlots[i], Entity: slot, Character: character})
     289              :         }
     290              : 
     291            1 :         return items
     292              : }
     293              : 
     294              : // equipableForSlot は指定スロットに装備できるバックパック内アイテムを返す
     295              : func equipableForSlot(world w.World, slotNumber gc.EquipmentSlotNumber) []ecs.Entity {
     296            1 :         items := []ecs.Entity{}
     297            1 :         if gc.SlotWeapon1 <= slotNumber && slotNumber <= gc.SlotWeapon5 {
     298            1 :                 q := ecs.NewFilter1[gc.LocationInBackpack](world.ECS).Query()
     299            1 :                 for q.Next() {
     300            1 :                         entity := q.Entity()
     301            1 :                         if !query.IsWeapon(world, entity) {
     302            1 :                                 continue
     303              :                         }
     304            1 :                         items = append(items, entity)
     305              :                 }
     306            1 :                 return query.SortEntities(world, items)
     307              :         }
     308              : 
     309            1 :         var target rawschema.EquipmentCategory
     310            1 :         switch slotNumber {
     311              :         case gc.SlotHead:
     312            1 :                 target = rawschema.EquipmentCategoryHEAD
     313              :         case gc.SlotTorso:
     314            0 :                 target = rawschema.EquipmentCategoryTORSO
     315              :         case gc.SlotArms:
     316            0 :                 target = rawschema.EquipmentCategoryARMS
     317              :         case gc.SlotHands:
     318            0 :                 target = rawschema.EquipmentCategoryHANDS
     319              :         case gc.SlotLegs:
     320            0 :                 target = rawschema.EquipmentCategoryLEGS
     321              :         case gc.SlotFeet:
     322            0 :                 target = rawschema.EquipmentCategoryFEET
     323              :         case gc.SlotJewelry:
     324            0 :                 target = rawschema.EquipmentCategoryJEWELRY
     325              :         default:
     326            0 :                 return query.SortEntities(world, items)
     327              :         }
     328              : 
     329            1 :         q := ecs.NewFilter2[gc.LocationInBackpack, gc.Wearable](world.ECS).Query()
     330            1 :         for q.Next() {
     331            1 :                 entity := q.Entity()
     332            1 :                 wearable := world.Components.Wearable.Get(entity)
     333            1 :                 if wearable != nil && wearable.EquipmentCategory == target {
     334            1 :                         items = append(items, entity)
     335            1 :                 }
     336              :         }
     337            1 :         return query.SortEntities(world, items)
     338              : }
     339              : 
     340              : // infoDetailContent は情報タブの1行を詳細内容にする。見出しと説明、内訳の行を出す
     341              : func infoDetailContent(item statusItemData) overlay.DetailContent {
     342            0 :         heading := item.Label
     343            0 :         if item.Value != "" {
     344            0 :                 heading = fmt.Sprintf("%s  %s", item.Label, item.Value)
     345            0 :         }
     346            0 :         rows := []entityspec.SpecRow{}
     347            0 :         for _, d := range item.Details {
     348            0 :                 if d.Value == "" {
     349            0 :                         continue
     350              :                 }
     351            0 :                 rows = append(rows, entityspec.SpecRow{Label: d.Label, Value: d.Value})
     352              :         }
     353            0 :         return overlay.DetailContent{Name: heading, Desc: item.Description, Rows: rows}
     354              : }
     355              : 
     356              : // healthDetailContent は健康タブで選んだ1症状の詳細を組む。名前と概要、進行度・治療・
     357              : // 能力デバフの性能行を返す。症状の無い部位のエントリは概要だけを出す
     358              : func healthDetailContent(world w.World, item statusItemData) overlay.DetailContent {
     359              :         // 症状の無い部位は概要だけ出す
     360            1 :         if item.Condition == nil {
     361            0 :                 return overlay.DetailContent{Name: query.BodyPartName(world, item.BodyPart), Desc: query.T(world, "No injury or illness")}
     362            0 :         }
     363            1 :         cond := item.Condition
     364            1 :         // 導出不調は Timer も治療状態も持たない。進行度でなく重症度と、下げる身体機能だけを出す
     365            1 :         if world.Resources.ConditionDefs.IsDerived(cond.Type) {
     366            1 :                 return derivedConditionDetail(world, cond)
     367            1 :         }
     368              : 
     369            1 :         pain, bodyFunc, drop := world.Resources.ConditionDefs.BodyFuncImpact(cond, item.BodyPart)
     370            1 :         rows := make([]entityspec.SpecRow, 0, 4)
     371            1 :         rows = append(rows,
     372            1 :                 entityspec.SpecRow{Label: query.T(world, "Progress"), Value: fmt.Sprintf("%d%%", int(cond.Timer))},
     373            1 :                 entityspec.SpecRow{Label: query.T(world, "Treatment"), Value: treatmentStatus(world, *cond)},
     374            1 :         )
     375            1 :         if pain > 0 {
     376            1 :                 rows = append(rows, entityspec.SpecRow{Label: query.T(world, "Pain"), Value: fmt.Sprintf("+%d", pain)})
     377            1 :         }
     378            1 :         if drop > 0 {
     379            1 :                 rows = append(rows, entityspec.SpecRow{Label: query.T(world, bodyFunc.Name()), Value: fmt.Sprintf("-%d", drop)})
     380            1 :         }
     381              :         // 血液量を下げる不調はその量を示す。失血で体力が減ることを読み取れるようにする
     382            1 :         if bd := world.Resources.ConditionDefs.BloodDrop(cond); bd > 0 {
     383            0 :                 rows = append(rows, entityspec.SpecRow{Label: query.T(world, "Blood loss"), Value: fmt.Sprintf("-%d", bd)})
     384            0 :         }
     385              :         // 治し方を示す。当てずっぽうにせず、どのアイテムで治せるか分かるようにする
     386            1 :         if name, ok := remedyItemNameFor(world, cond.Type); ok {
     387            1 :                 rows = append(rows, entityspec.SpecRow{Label: query.T(world, "Treated by"), Value: query.T(world, name)})
     388            1 :         }
     389            1 :         return overlay.DetailContent{
     390            1 :                 Name: translatedConditionName(world, cond.Type),
     391            1 :                 Desc: query.ConditionDescription(world, cond.Type),
     392            1 :                 Rows: rows,
     393            1 :         }
     394              : }
     395              : 
     396              : // derivedConditionDetail は過労・栄養失調の詳細を組む。量から導出され Timer も治療状態も持たないので、
     397              : // 進行度・治療でなく重症度を出す。この不調は意識と代謝を同じ量だけ下げるので両方の低下を並べる
     398              : func derivedConditionDetail(world w.World, cond *gc.HealthCondition) overlay.DetailContent {
     399            1 :         rows := []entityspec.SpecRow{
     400            1 :                 {Label: query.T(world, "Severity"), Value: query.T(world, cond.Severity.Name())},
     401            1 :         }
     402              :         // 全身性なので意識と代謝を drop ぶん下げる
     403            1 :         if _, _, drop := world.Resources.ConditionDefs.BodyFuncImpact(cond, gc.BodyPartWholeBody); drop > 0 {
     404            1 :                 rows = append(rows,
     405            1 :                         entityspec.SpecRow{Label: query.T(world, gc.BodyFuncConsciousness.Name()), Value: fmt.Sprintf("-%d", drop)},
     406            1 :                         entityspec.SpecRow{Label: query.T(world, gc.BodyFuncMetabolism.Name()), Value: fmt.Sprintf("-%d", drop)},
     407            1 :                 )
     408            1 :         }
     409            1 :         return overlay.DetailContent{
     410            1 :                 Name: translatedConditionName(world, cond.Type),
     411            1 :                 Desc: query.ConditionDescription(world, cond.Type),
     412            1 :                 Rows: rows,
     413            1 :         }
     414              : }
     415              : 
     416              : // remedyItemNameFor は指定した不調を治療できるアイテムの英語名を raw の Remedy から逆引きする。
     417              : // 健康タブに治し方を示すのに使う。見つからなければ ok=false。
     418              : // 複数のアイテムが同じ不調を治せる場合は先頭の1件だけ返す。1症状に1種の治療アイテムを保つ前提
     419              : func remedyItemNameFor(world w.World, ct gc.ConditionType) (i18n.Msgid, bool) {
     420            1 :         items := raw.PtrSlice(world.Resources.RawMaster.Items)
     421            1 :         for i := range items {
     422            1 :                 it := &items[i]
     423            1 :                 if it.Remedy == nil {
     424            1 :                         continue
     425              :                 }
     426            1 :                 for _, t := range it.Remedy.Treats {
     427            1 :                         if gc.ConditionType(t) == ct {
     428            1 :                                 return i18n.Msgid(it.Name), true
     429            1 :                         }
     430              :                 }
     431              :         }
     432            0 :         return "", false
     433              : }
        

Generated by: LCOV version 2.0-1