LCOV - code coverage report
Current view: top level - states - character_naming.go Coverage Total Hit
Test: coverage.lcov Lines: 69.2 % 120 83
Test Date: 2026-11-19 00:25:22 Functions: - 0 0

            Line data    Source code
       1              : package states
       2              : 
       3              : import (
       4              :         "fmt"
       5              :         "time"
       6              :         "unicode/utf8"
       7              : 
       8              :         "github.com/hajimehoshi/ebiten/v2"
       9              :         "github.com/kijimaD/ruins/internal/config"
      10              :         "github.com/kijimaD/ruins/internal/consts"
      11              :         es "github.com/kijimaD/ruins/internal/engine/states"
      12              :         "github.com/kijimaD/ruins/internal/hooks"
      13              :         "github.com/kijimaD/ruins/internal/input"
      14              :         "github.com/kijimaD/ruins/internal/inputmapper"
      15              :         "github.com/kijimaD/ruins/internal/widgets/menuframe"
      16              :         "github.com/kijimaD/ruins/internal/widgets/theme"
      17              :         "github.com/kijimaD/ruins/internal/widgets/uicore"
      18              :         w "github.com/kijimaD/ruins/internal/world"
      19              : 
      20              :         "github.com/kijimaD/ruins/internal/world/query"
      21              : )
      22              : 
      23              : const (
      24              :         nameMinLength    = 1
      25              :         nameMaxLength    = 10
      26              :         errorDisplayTime = 2 * time.Second
      27              : )
      28              : 
      29              : // CharacterNamingState はキャラクター名前入力画面のステート。
      30              : //
      31              : // 入力はテキストチャンネルの例外で、束縛表と keybind.ReadInput を通さずキーを直読みする。
      32              : // 文字入力は ebiten.AppendInputChars と Backspace を直読みして props の名前へ反映する。
      33              : // IME の変換途中状態やカーソル編集は離散的な Action の語彙に還元できないため、
      34              : // Action チャンネルへは統一しない。再生が必要になれば文字列を別口で注入する
      35              : type CharacterNamingState struct {
      36              :         es.BaseState[w.World]
      37              :         mount *hooks.Mount[namingProps]
      38              :         body  uicore.Drawable
      39              : }
      40              : 
      41              : // NewCharacterNamingState は名付けステートのファクトリを返す
      42              : func NewCharacterNamingState() (es.State[w.World], error) {
      43            1 :         return &CharacterNamingState{}, nil
      44            1 : }
      45              : 
      46              : // State interface ================
      47              : 
      48              : var _ es.State[w.World] = &CharacterNamingState{}
      49              : var _ es.ActionHandler[w.World] = &CharacterNamingState{}
      50              : 
      51              : // OnPause はステートが一時停止される際に呼ばれる
      52            0 : func (st *CharacterNamingState) OnPause(_ w.World) error { return nil }
      53              : 
      54              : // OnResume はステートが再開される際に呼ばれる
      55            0 : func (st *CharacterNamingState) OnResume(_ w.World) error { return nil }
      56              : 
      57              : // OnStart はステート開始時の処理を行う
      58              : func (st *CharacterNamingState) OnStart(world w.World) error {
      59            1 :         st.mount = hooks.NewMount[namingProps]()
      60            1 : 
      61              :         // 既存プレイヤーの名前を初期値として設定
      62            1 :         initialName := ""
      63            1 :         playerEntity, err := query.GetPlayerEntity(world)
      64            1 :         if err == nil {
      65            1 :                 if world.Components.Name.Has(playerEntity) {
      66            1 :                         initialName = query.GetEntityName(playerEntity, world)
      67            1 :                 }
      68              :         }
      69              : 
      70            1 :         st.mount.SetProps(namingProps{
      71            1 :                 CurrentName:  initialName,
      72            1 :                 ErrorMessage: "",
      73            1 :         })
      74            1 :         return nil
      75              : }
      76              : 
      77              : // OnStop はステートが停止される際に呼ばれる
      78            0 : func (st *CharacterNamingState) OnStop(_ w.World) error { return nil }
      79              : 
      80              : // Update はゲームステートの更新処理を行う
      81              : func (st *CharacterNamingState) Update(world w.World) (es.Transition[w.World], error) {
      82            1 :         props := st.mount.GetProps()
      83            1 : 
      84              :         // エラーメッセージの自動クリア
      85            1 :         expired, _, resetTimer := hooks.UseTimer(st.mount.Store(), "errorTimer", errorDisplayTime)
      86            1 :         if expired && props.ErrorMessage != "" {
      87            0 :                 st.mount.SetProps(namingProps{
      88            0 :                         CurrentName:  props.CurrentName,
      89            0 :                         ErrorMessage: "",
      90            0 :                 })
      91            0 :                 resetTimer()
      92            0 :         }
      93              : 
      94              :         // 文字入力を名前へ取り込む
      95            1 :         if newName, changed := readTextInput(props.CurrentName); changed {
      96            0 :                 st.mount.SetProps(namingProps{
      97            0 :                         CurrentName:  newName,
      98            0 :                         ErrorMessage: props.ErrorMessage,
      99            0 :                 })
     100            0 :         }
     101              : 
     102              :         // 入力処理
     103            1 :         if action, ok := st.HandleInput(world.Resources.Config); ok {
     104            0 :                 if transition, err := st.DoAction(world, action); err != nil {
     105            0 :                         return es.Transition[w.World]{}, err
     106            0 :                 } else if transition.Type != es.TransNone {
     107            0 :                         return transition, nil
     108            0 :                 }
     109              :         }
     110              : 
     111              :         // dirty判定とUI再構築
     112            1 :         if st.mount.Update() || st.body == nil {
     113            1 :                 st.body = st.buildUI(world)
     114            1 :         }
     115            1 :         return st.ConsumeTransition(), nil
     116              : }
     117              : 
     118              : // readTextInput は今フレームの文字入力と Backspace を名前へ反映する。
     119              : // 印字文字は AppendInputChars で受け取り、最大長までを追記する。Backspace は末尾1文字を消す
     120              : func readTextInput(current string) (string, bool) {
     121            1 :         name := current
     122            1 :         changed := false
     123            1 :         for _, r := range ebiten.AppendInputChars(nil) {
     124            0 :                 if r == '\n' || r == '\r' || r == '\t' {
     125            0 :                         continue
     126              :                 }
     127            0 :                 if utf8.RuneCountInString(name) >= nameMaxLength {
     128            0 :                         break
     129              :                 }
     130            0 :                 name += string(r)
     131            0 :                 changed = true
     132              :         }
     133            1 :         if input.GetSharedKeyboardInput().IsKeyPressedWithRepeat(ebiten.KeyBackspace) && name != "" {
     134            0 :                 runes := []rune(name)
     135            0 :                 name = string(runes[:len(runes)-1])
     136            0 :                 changed = true
     137            0 :         }
     138            1 :         return name, changed
     139              : }
     140              : 
     141              : // Draw はスクリーンに描画する
     142              : func (st *CharacterNamingState) Draw(_ w.World, screen *ebiten.Image) error {
     143            1 :         screen.Fill(theme.ScreenBackground)
     144            1 :         if st.body != nil {
     145            1 :                 st.body.Draw(uicore.NewEbitenCanvas(screen))
     146            1 :         }
     147            1 :         return nil
     148              : }
     149              : 
     150              : // HandleInput はキー入力をActionに変換する
     151              : func (st *CharacterNamingState) HandleInput(_ *config.Config) (inputmapper.ActionID, bool) {
     152            1 :         keyboardInput := input.GetSharedKeyboardInput()
     153            1 :         if keyboardInput.IsEnterJustPressedOnce() {
     154            0 :                 return inputmapper.ActionMenuSelect, true
     155            0 :         }
     156            1 :         if keyboardInput.IsKeyJustPressed(ebiten.KeyEscape) {
     157            0 :                 return inputmapper.ActionMenuCancel, true
     158            0 :         }
     159            1 :         return "", false
     160              : }
     161              : 
     162              : // DoAction はActionを実行する
     163              : func (st *CharacterNamingState) DoAction(world w.World, action inputmapper.ActionID) (es.Transition[w.World], error) {
     164            1 :         switch action {
     165              :         case inputmapper.ActionMenuCancel, inputmapper.ActionCloseMenu:
     166            1 :                 return st.cancel(world), nil
     167              :         case inputmapper.ActionMenuSelect:
     168            0 :                 return st.confirmName(world), nil
     169              :         default:
     170            0 :                 return es.Transition[w.World]{}, fmt.Errorf("characterNaming: unsupported action: %s", action)
     171              :         }
     172              : }
     173              : 
     174              : // ================
     175              : // Props
     176              : // ================
     177              : 
     178              : // namingProps は名前入力画面のProps
     179              : type namingProps struct {
     180              :         CurrentName  string
     181              :         ErrorMessage string
     182              : }
     183              : 
     184              : // confirmName は名前を確定する
     185              : func (st *CharacterNamingState) confirmName(world w.World) es.Transition[w.World] {
     186            1 :         props := st.mount.GetProps()
     187            1 :         name := props.CurrentName
     188            1 :         nameLen := utf8.RuneCountInString(name)
     189            1 : 
     190            1 :         if nameLen < nameMinLength || nameLen > nameMaxLength {
     191            1 :                 st.mount.SetProps(namingProps{
     192            1 :                         CurrentName:  props.CurrentName,
     193            1 :                         ErrorMessage: query.T(world, "Enter a name of 1 to 10 characters"),
     194            1 :                 })
     195            1 :                 _, startTimer, _ := hooks.UseTimer(st.mount.Store(), "errorTimer", errorDisplayTime)
     196            1 :                 startTimer()
     197            1 :                 return es.Transition[w.World]{Type: es.TransNone}
     198            1 :         }
     199              : 
     200            1 :         playerEntity, err := query.GetPlayerEntity(world)
     201            1 :         if err == nil {
     202              :                 // 既存プレイヤーの名前を変更した
     203            1 :                 if nameComp := world.Components.Name.Get(playerEntity); nameComp != nil {
     204            1 :                         nameComp.Custom = name
     205            1 :                 }
     206            1 :                 return es.Transition[w.World]{Type: es.TransPop}
     207              :         }
     208              : 
     209              :         // 職業選択画面へ遷移
     210            1 :         return es.Transition[w.World]{
     211            1 :                 Type:          es.TransPush,
     212            1 :                 NewStateFuncs: []es.StateFactory[w.World]{NewCharacterJobState(name)},
     213            1 :         }
     214              : }
     215              : 
     216              : // cancel はキャンセルする
     217              : func (st *CharacterNamingState) cancel(world w.World) es.Transition[w.World] {
     218            1 :         _, err := query.GetPlayerEntity(world)
     219            1 :         if err == nil {
     220            1 :                 return es.Transition[w.World]{Type: es.TransPop}
     221            1 :         }
     222            1 :         return es.Transition[w.World]{
     223            1 :                 Type:          es.TransReplace,
     224            1 :                 NewStateFuncs: []es.StateFactory[w.World]{NewMainMenuState},
     225            1 :         }
     226              : }
     227              : 
     228              : // ================
     229              : // buildUI
     230              : // ================
     231              : 
     232              : // buildUI は名前入力画面を uicore のツリーとして組む。
     233              : // タイトル・入力枠・エラー・ヒントを画面中央へ縦に並べる。入力枠には現在名とキャレットを描く
     234              : func (st *CharacterNamingState) buildUI(world w.World) uicore.Drawable {
     235            1 :         res := world.Resources.UIResources
     236            1 :         props := st.mount.GetProps()
     237            1 : 
     238              :         // 入力枠の中身。空なら placeholder を薄色で、入力中は名前にキャレットを添える。
     239              :         // 縦位置は VCenter で入力枠の中央へ合わせる
     240            1 :         var content *uicore.Text
     241            1 :         if props.CurrentName == "" {
     242            0 :                 content = uicore.NewText(query.T(world, "Name"), res.Text.BodyFace, theme.TextSecondary)
     243            0 :         } else {
     244            1 :                 content = uicore.NewText(props.CurrentName+"|", res.Text.BodyFace, theme.TextPrimary)
     245            1 :         }
     246            1 :         content.VCenter = true
     247            1 : 
     248            1 :         hint := consts.IconKeyEnter + " " + query.T(world, "Confirm") + " / " + consts.IconKeyEsc + " " + query.T(world, "Back")
     249            1 :         return menuframe.FormScreen(world, res, query.T(world, "Name"), content, props.ErrorMessage, hint)
     250              : }
        

Generated by: LCOV version 2.0-1