LCOV - code coverage report
Current view: top level - activity - attack.go Coverage Total Hit
Test: coverage.lcov Lines: 87.1 % 294 256
Test Date: 2026-11-19 00:25:22 Functions: - 0 0

            Line data    Source code
       1              : package activity
       2              : 
       3              : import (
       4              :         "fmt"
       5              :         "strconv"
       6              : 
       7              :         gc "github.com/kijimaD/ruins/internal/components"
       8              :         "github.com/kijimaD/ruins/internal/consts"
       9              :         "github.com/kijimaD/ruins/internal/formula"
      10              :         "github.com/kijimaD/ruins/internal/gamelog"
      11              :         "github.com/kijimaD/ruins/internal/geometry"
      12              :         "github.com/kijimaD/ruins/internal/i18n"
      13              :         "github.com/kijimaD/ruins/internal/raw"
      14              :         "github.com/kijimaD/ruins/internal/rawschema"
      15              :         "github.com/kijimaD/ruins/internal/skill"
      16              :         w "github.com/kijimaD/ruins/internal/world"
      17              : 
      18              :         "github.com/kijimaD/ruins/internal/world/gameaction"
      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              : // 攻撃システムの定数
      25              : const (
      26              :         MeleeAttackRange = 1.5 // 近接攻撃の最大射程(斜めも考慮)
      27              : )
      28              : 
      29              : // MeleeBehavior はBehaviorの実装
      30              : type MeleeBehavior struct{}
      31              : 
      32              : // Info はBehaviorの実装
      33              : func (ab *MeleeBehavior) Info() Info {
      34            1 :         return Info{
      35            1 :                 Name:            "Attack",
      36            1 :                 Description:     "Attack an enemy",
      37            1 :                 Interruptible:   false,
      38            1 :                 Resumable:       false,
      39            1 :                 ActionPointCost: consts.StandardActionCost,
      40            1 :                 TotalRequiredAP: 0,
      41            1 :         }
      42              : }
      43              : 
      44              : // Name はBehaviorの実装
      45              : func (ab *MeleeBehavior) Name() gc.BehaviorName {
      46            1 :         return gc.BehaviorMelee
      47            1 : }
      48              : 
      49              : // NewMeleeActivity は攻撃対象を指定して攻撃アクティビティを組む。
      50              : func NewMeleeActivity(target ecs.Entity) *gc.Activity {
      51            1 :         comp := NewActivity(gc.BehaviorMelee, 0)
      52            1 :         comp.Params = &gc.MeleeParams{Target: target}
      53            1 :         return comp
      54            1 : }
      55              : 
      56              : // Validate はBehaviorの実装
      57              : func (ab *MeleeBehavior) Validate(comp *gc.Activity, actor ecs.Entity, world w.World) error {
      58            1 :         p, ok := comp.Params.(*gc.MeleeParams)
      59            1 :         if !ok {
      60            0 :                 return ErrParamsTypeMismatch
      61            0 :         }
      62              : 
      63            1 :         if world.Components.Dead.Has(actor) {
      64            0 :                 return ErrAttackerDead
      65            0 :         }
      66              : 
      67              :         // 近接は隣接歩き込み専用で、対象選択が生存・隣接・攻撃能力を保証する。以降で弾かれるのは
      68              :         // 選択後の消失など通常プレイで起きない不変条件違反なのでシステムエラーとする。
      69              :         // ゼロ値・死亡エンティティは Ark の Has でパニックするため先に弾く
      70            1 :         if !world.ECS.Alive(p.Target) {
      71            1 :                 return fmt.Errorf("target does not exist")
      72            1 :         }
      73              : 
      74            1 :         if !world.Components.GridElement.Has(p.Target) {
      75            0 :                 return fmt.Errorf("target has no position")
      76            0 :         }
      77              : 
      78            1 :         if world.Components.Dead.Has(p.Target) {
      79            1 :                 return fmt.Errorf("target is already dead")
      80            1 :         }
      81              : 
      82            1 :         if !ab.isInRange(actor, p.Target, world) {
      83            1 :                 return fmt.Errorf("target is out of melee range")
      84            1 :         }
      85              : 
      86            1 :         if !ab.canPerformAttack(actor, world) {
      87            1 :                 return fmt.Errorf("attacker has no attack means")
      88            1 :         }
      89              : 
      90            1 :         return nil
      91              : }
      92              : 
      93              : // selectedWeapon はプレイヤーが選択中の武器スロットの武器を返す。空きスロットなら ok は偽
      94              : func selectedWeapon(world w.World, actor ecs.Entity) (ecs.Entity, bool, error) {
      95            1 :         selectedSlot := query.GetWeaponSelection(world).Slot
      96            1 :         weaponIndex := selectedSlot - 1
      97            1 :         if weaponIndex < 0 || weaponIndex >= 5 {
      98            1 :                 return ecs.Entity{}, false, fmt.Errorf("%w: %d", ErrInvalidWeaponSlot, selectedSlot)
      99            1 :         }
     100            1 :         weapon := query.GetWeapons(world, actor)[weaponIndex]
     101            1 :         if weapon == nil {
     102            1 :                 return ecs.Entity{}, false, nil
     103            1 :         }
     104            1 :         return *weapon, true, nil
     105              : }
     106              : 
     107              : // Start はBehaviorの実装
     108              : func (ab *MeleeBehavior) Start(comp *gc.Activity, actor ecs.Entity, _ w.World) error {
     109            1 :         if p, ok := comp.Params.(*gc.MeleeParams); ok {
     110            1 :                 log.Debug("attack started", "actor", actor, "target", p.Target)
     111            1 :         }
     112            1 :         return nil
     113              : }
     114              : 
     115              : // DoTurn はBehaviorの実装
     116              : func (ab *MeleeBehavior) DoTurn(comp *gc.Activity, actor ecs.Entity, world w.World) error {
     117            1 :         if _, ok := comp.Params.(*gc.MeleeParams); !ok {
     118            1 :                 return ErrParamsTypeMismatch
     119            1 :         }
     120              : 
     121            1 :         if !ab.canAttack(comp, actor, world) {
     122            1 :                 return ErrAttackTargetInvalid
     123            1 :         }
     124              : 
     125            1 :         if err := ab.performAttack(comp, actor, world); err != nil {
     126            0 :                 return err
     127            0 :         }
     128              : 
     129            1 :         Complete(comp)
     130            1 :         return nil
     131              : }
     132              : 
     133              : // Finish はBehaviorの実装
     134              : func (ab *MeleeBehavior) Finish(comp *gc.Activity, actor ecs.Entity, _ w.World) error {
     135            1 :         p, ok := comp.Params.(*gc.MeleeParams)
     136            1 :         if !ok {
     137            0 :                 return ErrParamsTypeMismatch
     138            0 :         }
     139            1 :         log.Debug("attack activity finished",
     140            1 :                 "actor", actor,
     141            1 :                 "target", p.Target)
     142            1 : 
     143            1 :         return nil
     144              : }
     145              : 
     146              : // Canceled はBehaviorの実装
     147              : func (ab *MeleeBehavior) Canceled(comp *gc.Activity, actor ecs.Entity, _ w.World) error {
     148            1 :         log.Debug("attack canceled", "actor", actor, "reason", comp.CancelReason)
     149            1 :         return nil
     150            1 : }
     151              : 
     152              : func (ab *MeleeBehavior) performAttack(comp *gc.Activity, actor ecs.Entity, world w.World) error {
     153            1 :         p, ok := comp.Params.(*gc.MeleeParams)
     154            1 :         if !ok {
     155            0 :                 return ErrParamsTypeMismatch
     156            0 :         }
     157            1 :         target := p.Target
     158            1 : 
     159            1 :         log.Debug("performing attack", "attacker", actor, "target", target)
     160            1 : 
     161            1 :         attack, attackMethodName, err := getAttackParams(actor, world)
     162            1 :         if err != nil {
     163            0 :                 return fmt.Errorf("failed to get attack parameters: %w", err)
     164            0 :         }
     165              : 
     166            1 :         return applyAttackDamage(actor, target, world, attack, attackMethodName, 0, 0)
     167              : }
     168              : 
     169              : func (ab *MeleeBehavior) canAttack(comp *gc.Activity, actor ecs.Entity, world w.World) bool {
     170            1 :         if _, ok := comp.Params.(*gc.MeleeParams); !ok {
     171            1 :                 return false
     172            1 :         }
     173              : 
     174            1 :         if err := ab.Validate(comp, actor, world); err != nil {
     175            1 :                 return false
     176            1 :         }
     177              : 
     178            1 :         return true
     179              : }
     180              : 
     181              : func (ab *MeleeBehavior) isInRange(attacker, target ecs.Entity, world w.World) bool {
     182            1 :         if !world.Components.GridElement.Has(attacker) {
     183            0 :                 return false
     184            0 :         }
     185            1 :         attackerGrid := world.Components.GridElement.Get(attacker)
     186            1 : 
     187            1 :         if !world.Components.GridElement.Has(target) {
     188            0 :                 return false
     189            0 :         }
     190            1 :         targetGrid := world.Components.GridElement.Get(target)
     191            1 : 
     192            1 :         distance := geometry.Distance(float64(attackerGrid.X), float64(attackerGrid.Y), float64(targetGrid.X), float64(targetGrid.Y))
     193            1 : 
     194              :         // TODO: 遠距離武器の場合は射程を武器から取得
     195            1 :         return distance <= MeleeAttackRange
     196              : }
     197              : 
     198              : func (ab *MeleeBehavior) canPerformAttack(attacker ecs.Entity, world w.World) bool {
     199              :         // TODO: 装備武器のチェック
     200            1 :         abils := world.Components.Abilities.Get(attacker)
     201            1 :         return abils != nil
     202            1 : }
     203              : 
     204              : // getBareHandsAttack は素手武器の攻撃パラメータを取得する
     205              : func getBareHandsAttack(world w.World) (gc.Attacker, i18n.Msgid, error) {
     206            1 :         bareHandsSpec, err := raw.NewWeaponSpec(world.Resources.RawMaster, "bare_hands")
     207            1 :         if err != nil {
     208            0 :                 return nil, "", fmt.Errorf("bare hands weapon not found: %w", err)
     209            0 :         }
     210            1 :         if bareHandsSpec.Melee == nil {
     211            0 :                 return nil, "", fmt.Errorf("bare hands weapon has no Melee component")
     212            0 :         }
     213            1 :         if bareHandsSpec.Name == nil {
     214            0 :                 return nil, "", fmt.Errorf("bare hands weapon has no Name component")
     215            0 :         }
     216            1 :         return bareHandsSpec.Melee, bareHandsSpec.Name.Name, nil
     217              : }
     218              : 
     219              : // getAttackParams は攻撃者の武器から攻撃パラメータと攻撃方法名を取得する
     220              : // 戻り値: (攻撃パラメータ, 攻撃方法名, エラー)
     221              : func getAttackParams(attacker ecs.Entity, world w.World) (gc.Attacker, i18n.Msgid, error) {
     222              :         // プレイヤーの場合: 装備武器から攻撃パラメータを取得
     223            1 :         if world.Components.Player.Has(attacker) {
     224            1 :                 weapon, ok, err := selectedWeapon(world, attacker)
     225            1 :                 if err != nil {
     226            1 :                         return nil, "", err
     227            1 :                 }
     228            1 :                 if ok {
     229            1 :                         attack, weaponName, err := query.GetMeleeFromWeapon(world, weapon)
     230            1 :                         if err == nil && attack != nil {
     231            1 :                                 return attack, weaponName, nil
     232            1 :                         }
     233              :                 }
     234              : 
     235              :                 // 武器が装備されていない場合は素手武器を使用
     236            1 :                 return getBareHandsAttack(world)
     237              :         }
     238              : 
     239              :         // 敵の場合: CommandTableから攻撃パラメータを取得
     240            1 :         if world.Components.CommandTable.Has(attacker) {
     241            1 :                 attack, weaponName, err := query.GetAttackFromCommandTable(world, attacker)
     242            1 :                 if err == nil && attack != nil {
     243            1 :                         return attack, weaponName, nil
     244            1 :                 }
     245              : 
     246              :                 // CommandTableから取得できない場合は素手武器を使用
     247            1 :                 return getBareHandsAttack(world)
     248              :         }
     249              : 
     250            1 :         return nil, "", ErrNoAttackSource
     251              : }
     252              : 
     253              : // getSkillMult はスキル倍率(%)を返す。
     254              : // isDamageがtrueならダメージ倍率、falseなら命中倍率を参照する
     255              : func getSkillMult(entity ecs.Entity, attack gc.Attacker, world w.World, isDamage bool) consts.Percent {
     256            1 :         if attack == nil {
     257            1 :                 return consts.PercentBase
     258            1 :         }
     259            1 :         weapon, ok := world.Resources.SkillDefs.Weapon(attack.GetAttackCategory())
     260            1 :         if !ok {
     261            1 :                 return consts.PercentBase
     262            1 :         }
     263            1 :         key := weapon.Damage
     264            1 :         if !isDamage {
     265            1 :                 key = weapon.Accuracy
     266            1 :         }
     267            1 :         return query.ProficiencyValue(world, entity, key)
     268              : }
     269              : 
     270              : // elementMult は対象の属性 element への耐性の倍率を返す。耐性を持たない属性なら等倍
     271              : func elementMult(target ecs.Entity, element rawschema.Element, world w.World) consts.Percent {
     272            1 :         key, ok := world.Resources.SkillDefs.Resist(element)
     273            1 :         if !ok {
     274            1 :                 return consts.PercentBase
     275            1 :         }
     276            1 :         return query.ProficiencyValue(world, target, key)
     277              : }
     278              : 
     279              : // applyAttackDamage はダメージ適用・ログ出力・スキル成長・死亡処理を一括で行う共通関数。
     280              : // ShootBehaviorからも使用される
     281              : func applyAttackDamage(actor, target ecs.Entity, world w.World, attack gc.Attacker, attackMethodName i18n.Msgid, hitRateModifier int, damageModifier int) error {
     282            1 :         if attack == nil {
     283            0 :                 return fmt.Errorf("attack must not be nil")
     284            0 :         }
     285              : 
     286            1 :         hit, criticalHit := rollHitCheckWithModifier(actor, target, world, attack, hitRateModifier)
     287            1 :         if !hit {
     288            1 :                 logAttackResult(actor, target, world, false, false, 0, attackMethodName)
     289            1 :                 lifecycle.SpawnVisualEffect(target, gc.NewMissEffect(), world)
     290            1 :                 return nil
     291            1 :         }
     292              : 
     293            1 :         damage := max(calculateDamage(actor, target, world, attack, criticalHit, damageModifier), 0)
     294            1 : 
     295            1 :         logAttackResult(actor, target, world, true, criticalHit, damage, attackMethodName)
     296            1 :         // 削れない相手を殴り続けて安全に稼げないよう、ダメージ0では武器スキルを伸ばさない
     297            1 :         if damage > 0 {
     298            1 :                 growWeaponSkill(actor, world, attack)
     299            1 :         }
     300            1 :         lifecycle.SpawnVisualEffect(target, gc.NewDamageEffect(damage), world)
     301            1 :         gameaction.ApplyDamage(world, target, damage, actor)
     302            1 :         if world.Components.Prop.Has(target) && world.Components.Dead.Has(target) {
     303            1 :                 if err := dropSalvage(world, actor, target); err != nil {
     304            0 :                         return err
     305            0 :                 }
     306              :         }
     307              :         // HP を削った後、HealthStatus を持つ対象へ確率で怪我を付ける
     308            1 :         applyInjury(actor, target, world, attack)
     309            1 : 
     310              :         // 被ダメージで中断可能なアクティビティをキャンセルする
     311            1 :         if comp := query.GetActivity(world, target); comp != nil && CanInterrupt(comp) {
     312            1 :                 CancelActivity(target, "took an attack", world)
     313            1 :         }
     314              : 
     315            1 :         return nil
     316              : }
     317              : 
     318              : // calculateHitRate は命中率を算出する。ダイスロールなしの純粋な計算で、UI表示と命中判定の両方で使用する
     319              : func calculateHitRate(attacker, target ecs.Entity, world w.World, attack gc.Attacker, modifier int) int {
     320            1 :         if !world.Components.Abilities.Has(attacker) {
     321            0 :                 return formula.BaseHitRate
     322            0 :         }
     323            1 :         attackerAbils := world.Components.Abilities.Get(attacker)
     324            1 : 
     325              :         // Abilitiesを持たないターゲットには自動命中する
     326            1 :         targetAgility := 0
     327            1 :         if world.Components.Abilities.Has(target) {
     328            1 :                 targetAbilsComp := world.Components.Abilities.Get(target)
     329            1 :                 targetAgility = targetAbilsComp.Agility.Total
     330            1 :         }
     331              : 
     332              :         // 基礎命中は反射神経 DEX と対象の回避の対抗。武器習熟の能力値と体調由来の
     333              :         // 命中低下は WeaponAccuracy 側が畳むのでここには足さない
     334            1 :         hitRate := formula.BaseHitRate + (attackerAbils.Dexterity.Total-targetAgility)*formula.HitRatePerStatPoint
     335            1 :         hitRate += getWeaponAccuracyFromAttack(attack)
     336            1 :         hitRate = getSkillMult(attacker, attack, world, false).ApplyInt(hitRate)
     337            1 :         hitRate += modifier
     338            1 : 
     339            1 :         return formula.ClampHitRate(hitRate)
     340              : }
     341              : 
     342              : // rollHitCheckWithModifier は命中判定を行う。modifierは追加の命中率補正(負値でペナルティ)
     343              : func rollHitCheckWithModifier(attacker, target ecs.Entity, world w.World, attack gc.Attacker, modifier int) (hit bool, critical bool) {
     344            1 :         hitRate := calculateHitRate(attacker, target, world, attack, modifier)
     345            1 : 
     346            1 :         roll := world.Resources.Config.RNG.IntN(formula.DiceMax) + 1
     347            1 :         hit = roll <= hitRate
     348            1 :         critical = roll <= formula.CriticalHitThreshold
     349            1 : 
     350            1 :         return hit, critical
     351            1 : }
     352              : 
     353              : // getWeaponAccuracyFromAttack はAttackerから命中率補正を取得する
     354              : func getWeaponAccuracyFromAttack(attack gc.Attacker) int {
     355            1 :         return attack.GetAccuracy() - formula.BaseHitRate
     356            1 : }
     357              : 
     358              : // calculateDamage は ECS から攻撃側と対象の値を集め、formula.Damage で1回の命中のダメージを求める
     359              : func calculateDamage(attacker, target ecs.Entity, world w.World, attack gc.Attacker, critical bool, damageModifier int) int {
     360            1 :         if !world.Components.Abilities.Has(attacker) {
     361            0 :                 return 0
     362            0 :         }
     363            1 :         attackerAbils := world.Components.Abilities.Get(attacker)
     364            1 : 
     365            1 :         ability := attackerAbils.Strength.Total
     366            1 :         if _, ranged := world.Resources.SkillDefs.RangeParams(attack.GetAttackCategory()); ranged {
     367            1 :                 ability = attackerAbils.Sensation.Total
     368            1 :         }
     369              : 
     370            1 :         defense := 0
     371            1 :         if world.Components.Abilities.Has(target) {
     372            1 :                 defense = world.Components.Abilities.Get(target).Defense.Total
     373            1 :         }
     374              : 
     375              :         // 道具の倍率は最低保証の後に掛け、道具が必須なのに無いときは確実に0にする
     376            1 :         return formula.Damage(formula.DamageInput{
     377            1 :                 Ability:      ability,
     378            1 :                 Die:          world.Resources.Config.RNG.IntN(formula.DamageRandomRange) + 1,
     379            1 :                 WeaponDamage: attack.GetDamage(),
     380            1 :                 Modifier:     damageModifier,
     381            1 :                 SkillMult:    int(getSkillMult(attacker, attack, world, true)),
     382            1 :                 Critical:     critical,
     383            1 :                 ElementMult:  int(elementMult(target, attack.GetElement(), world)),
     384            1 :                 Defense:      defense,
     385            1 :         }) * toolDamageMultiplier(world, attacker, target)
     386              : }
     387              : 
     388              : // growWeaponSkill は攻撃成功時に武器スキルの経験値を加算する
     389              : func growWeaponSkill(actor ecs.Entity, world w.World, attack gc.Attacker) {
     390              :         // スキル成長は味方側の進行要素。敵も Skills を持つが戦闘中に強くならないよう除外する
     391            1 :         if query.IsEnemy(world, actor) {
     392            1 :                 return
     393            1 :         }
     394            1 :         if !world.Components.Skills.Has(actor) {
     395            1 :                 return
     396            1 :         }
     397            1 :         skills := world.Components.Skills.Get(actor)
     398            1 : 
     399            1 :         weapon, ok := world.Resources.SkillDefs.Weapon(attack.GetAttackCategory())
     400            1 :         if !ok {
     401            1 :                 return
     402            1 :         }
     403            1 :         skillID := weapon.Skill
     404            1 :         s := skills.Get(skillID)
     405            1 : 
     406            1 :         if !world.Components.Abilities.Has(actor) {
     407            1 :                 return
     408            1 :         }
     409            1 :         abils := world.Components.Abilities.Get(actor)
     410            1 :         ablID := world.Resources.SkillDefs.Ability(skillID)
     411            1 : 
     412            1 :         if skill.GainExp(s, abils.ValueOf(ablID)) {
     413            1 :                 actorName := query.GetEntityName(actor, world)
     414            1 :                 gamelog.New(query.GetGameLog(world)).
     415            1 :                         Markup(query.T(world, "%s's skill rose! (%s Lv%d)", actorName, string(skillID), s.Value)).
     416            1 :                         Log()
     417            1 :         }
     418              : }
     419              : 
     420              : // logAttackResult は攻撃結果をログに出力する
     421              : func logAttackResult(attacker, target ecs.Entity, world w.World, hit bool, critical bool, damage int, attackMethodName i18n.Msgid) {
     422            1 :         attackerRelevant := query.IsAlly(world, attacker)
     423            1 :         targetRelevant := query.IsAlly(world, target)
     424            1 :         if !attackerRelevant && !targetRelevant {
     425            1 :                 return
     426            1 :         }
     427              : 
     428            1 :         attackerName := query.GetEntityName(attacker, world)
     429            1 :         targetName := query.GetEntityName(target, world)
     430            1 :         attackerMarkup := query.NameMarkup(attacker, attackerName, world)
     431            1 :         targetMarkup := query.NameMarkup(target, targetName, world)
     432            1 :         damageStr := strconv.Itoa(damage)
     433            1 : 
     434            1 :         logger := gamelog.New(query.GetGameLog(world))
     435            1 :         withMethod := attackMethodName != ""
     436            1 :         var methodName string
     437            1 :         if withMethod {
     438            1 :                 methodName = query.T(world, attackMethodName)
     439            1 :         }
     440            1 :         switch {
     441              :         case !hit:
     442            1 :                 if withMethod {
     443            1 :                         logger.Markup(query.T(world, "%s used %s to attack %s but missed.", attackerMarkup, methodName, targetMarkup))
     444            1 :                 } else {
     445            0 :                         logger.Markup(query.T(world, "%s attacked %s but missed.", attackerMarkup, targetMarkup))
     446            0 :                 }
     447              :         case critical:
     448            1 :                 if withMethod {
     449            1 :                         logger.Markup(query.T(world, "%s used %s to score a critical hit on %s and dealt %s damage!", attackerMarkup, methodName, targetMarkup, damageStr))
     450            1 :                 } else {
     451            0 :                         logger.Markup(query.T(world, "%s scored a critical hit on %s and dealt %s damage!", attackerMarkup, targetMarkup, damageStr))
     452            0 :                 }
     453              :         default:
     454            1 :                 if withMethod {
     455            1 :                         logger.Markup(query.T(world, "%s used %s to attack %s and dealt %s damage.", attackerMarkup, methodName, targetMarkup, damageStr))
     456            1 :                 } else {
     457            0 :                         logger.Markup(query.T(world, "%s attacked %s and dealt %s damage.", attackerMarkup, targetMarkup, damageStr))
     458            0 :                 }
     459              :         }
     460            1 :         logger.Log()
     461              : }
        

Generated by: LCOV version 2.0-1