LCOV - code coverage report
Current view: top level - activity - shoot.go Coverage Total Hit
Test: coverage.lcov Lines: 88.2 % 136 120
Test Date: 2026-11-19 00:25:22 Functions: - 0 0

            Line data    Source code
       1              : package activity
       2              : 
       3              : import (
       4              :         "fmt"
       5              :         "math"
       6              : 
       7              :         gc "github.com/kijimaD/ruins/internal/components"
       8              :         "github.com/kijimaD/ruins/internal/consts"
       9              :         "github.com/kijimaD/ruins/internal/geometry"
      10              :         "github.com/kijimaD/ruins/internal/i18n"
      11              :         w "github.com/kijimaD/ruins/internal/world"
      12              : 
      13              :         "github.com/kijimaD/ruins/internal/world/query"
      14              :         "github.com/mlange-42/ark/ecs"
      15              : )
      16              : 
      17              : // 射撃システムの定数
      18              : const (
      19              :         CoverPenaltyPerObject = 15 // 射線上の遮蔽物1つにつきの命中率ペナルティ(%)
      20              : )
      21              : 
      22              : // ShootBehavior は射撃アクティビティの実装
      23              : type ShootBehavior struct{}
      24              : 
      25              : // Info はBehaviorの実装
      26              : func (sb *ShootBehavior) Info() Info {
      27            1 :         return Info{
      28            1 :                 Name:            "Shoot",
      29            1 :                 Description:     "Attack an enemy from range",
      30            1 :                 Interruptible:   false,
      31            1 :                 Resumable:       false,
      32            1 :                 ActionPointCost: consts.StandardActionCost,
      33            1 :         }
      34              : }
      35              : 
      36              : // Name はBehaviorの実装
      37              : func (sb *ShootBehavior) Name() gc.BehaviorName {
      38            1 :         return gc.BehaviorShoot
      39            1 : }
      40              : 
      41              : // NewShootActivity は射撃対象を指定して射撃アクティビティを組む。
      42              : func NewShootActivity(target ecs.Entity) *gc.Activity {
      43            1 :         comp := NewActivity(gc.BehaviorShoot, 0)
      44            1 :         comp.Params = &gc.ShootParams{Target: target}
      45            1 :         return comp
      46            1 : }
      47              : 
      48              : // Validate は射撃の検証を行う
      49              : func (sb *ShootBehavior) Validate(comp *gc.Activity, actor ecs.Entity, world w.World) error {
      50            1 :         p, ok := comp.Params.(*gc.ShootParams)
      51            1 :         if !ok {
      52            1 :                 return ErrParamsTypeMismatch
      53            1 :         }
      54            1 :         if world.Components.Dead.Has(actor) {
      55            1 :                 return ErrAttackerDead
      56            1 :         }
      57              :         // 対象は CanShootTarget が事前に絞る。存在しない・死亡はここでは選べないので、
      58              :         // 発火するのは選択後の消失など不変条件違反。システムエラーとして伝播させる
      59            1 :         if !world.Components.GridElement.Has(p.Target) {
      60            0 :                 return fmt.Errorf("target has no position")
      61            0 :         }
      62            1 :         if world.Components.Dead.Has(p.Target) {
      63            1 :                 return fmt.Errorf("target is already dead")
      64            1 :         }
      65              : 
      66              :         // 遠距離武器が装備されているか。CanShootTarget が事前に絞るので、武器スロット不正も
      67              :         // 遠距離武器なしもここでは起こらない。発火したら不変条件違反なのでそのまま伝播させる
      68            1 :         fire, _, err := getEquippedFire(actor, world)
      69            1 :         if err != nil {
      70            1 :                 return err
      71            1 :         }
      72              : 
      73              :         // 残弾チェック
      74            1 :         if fire.Magazine <= 0 {
      75            1 :                 return fmt.Errorf("out of ammo")
      76            1 :         }
      77              : 
      78              :         // 射程・射線チェック
      79            1 :         distance := EntityDistance(actor, p.Target, world)
      80            1 :         rangeParams, rangeOK := world.Resources.SkillDefs.RangeParams(fire.AttackCategory)
      81            1 :         if !rangeOK {
      82            0 :                 return fmt.Errorf("no ranged weapon equipped")
      83            0 :         }
      84            1 :         if distance > float64(rangeParams.MaxRange) {
      85            1 :                 return fmt.Errorf("target is out of range")
      86            1 :         }
      87              : 
      88              :         // 射線上に壁がないか
      89            1 :         if blocked, _ := checkLineOfSight(actor, p.Target, world); blocked {
      90            1 :                 return fmt.Errorf("line of sight is blocked")
      91            1 :         }
      92              : 
      93            1 :         return nil
      94              : }
      95              : 
      96              : // Start はBehaviorの実装
      97              : func (sb *ShootBehavior) Start(comp *gc.Activity, actor ecs.Entity, _ w.World) error {
      98            1 :         if p, ok := comp.Params.(*gc.ShootParams); ok {
      99            1 :                 log.Debug("shoot started", "actor", actor, "target", p.Target)
     100            1 :         }
     101            1 :         return nil
     102              : }
     103              : 
     104              : // DoTurn は射撃の実行処理
     105              : func (sb *ShootBehavior) DoTurn(comp *gc.Activity, actor ecs.Entity, world w.World) error {
     106            1 :         p, ok := comp.Params.(*gc.ShootParams)
     107            1 :         if !ok {
     108            1 :                 return ErrParamsTypeMismatch
     109            1 :         }
     110              : 
     111            1 :         target := p.Target
     112            1 : 
     113              :         // 装備武器を取得
     114            1 :         fire, weaponName, err := getEquippedFire(actor, world)
     115            1 :         if err != nil {
     116            0 :                 return err
     117            0 :         }
     118              : 
     119              :         // 弾薬消費
     120            1 :         fire.Magazine--
     121            1 : 
     122              :         // 命中率修正を計算(距離ペナルティ + 遮蔽ペナルティ + 弾薬修正)
     123            1 :         hitModifier := calculateRangedHitModifier(actor, target, fire, world)
     124            1 :         hitModifier += fire.LoadedAccuracyBonus
     125            1 : 
     126              :         // ダメージ適用(共通関数を使用)
     127            1 :         if err := applyAttackDamage(actor, target, world, fire, weaponName, hitModifier, fire.LoadedDamageBonus); err != nil {
     128            0 :                 return err
     129            0 :         }
     130              : 
     131            1 :         Complete(comp)
     132            1 :         return nil
     133              : }
     134              : 
     135              : // Finish はBehaviorの実装
     136              : func (sb *ShootBehavior) Finish(_ *gc.Activity, actor ecs.Entity, _ w.World) error {
     137            1 :         log.Debug("shoot finished", "actor", actor)
     138            1 :         return nil
     139            1 : }
     140              : 
     141              : // Canceled はBehaviorの実装
     142              : func (sb *ShootBehavior) Canceled(comp *gc.Activity, actor ecs.Entity, _ w.World) error {
     143            1 :         log.Debug("shoot canceled", "actor", actor, "reason", comp.CancelReason)
     144            1 :         return nil
     145            1 : }
     146              : 
     147              : // getEquippedFire はプレイヤーの装備中の遠距離武器のFireと武器名を取得する
     148              : func getEquippedFire(actor ecs.Entity, world w.World) (*gc.Fire, i18n.Msgid, error) {
     149            1 :         selectedSlot := query.GetWeaponSelection(world).Slot
     150            1 :         weaponIndex := selectedSlot - 1
     151            1 :         if weaponIndex < 0 || weaponIndex >= 5 {
     152            0 :                 return nil, "", fmt.Errorf("%w: %d", ErrInvalidWeaponSlot, selectedSlot)
     153            0 :         }
     154              : 
     155            1 :         weapons := query.GetWeapons(world, actor)
     156            1 :         weaponEntity := weapons[weaponIndex]
     157            1 :         if weaponEntity == nil {
     158            0 :                 return nil, "", ErrShootNoFireWeapon
     159            0 :         }
     160              : 
     161            1 :         fire, name, err := query.GetFireFromWeapon(world, *weaponEntity)
     162            1 :         if err != nil {
     163            1 :                 return nil, "", ErrShootNoFireWeapon
     164            1 :         }
     165            1 :         return fire, name, nil
     166              : }
     167              : 
     168              : // calculateRangedHitModifier は距離と遮蔽による命中率修正を計算する
     169              : func calculateRangedHitModifier(actor, target ecs.Entity, attack gc.Attacker, world w.World) int {
     170            1 :         modifier := 0
     171            1 : 
     172              :         // 距離ペナルティ
     173            1 :         distance := EntityDistance(actor, target, world)
     174            1 :         rangeParams, ok := world.Resources.SkillDefs.RangeParams(attack.GetAttackCategory())
     175            1 :         if ok && distance > float64(rangeParams.OptimalRange) {
     176            1 :                 excess := int(distance) - rangeParams.OptimalRange
     177            1 :                 modifier -= excess * rangeParams.PenaltyPerTile
     178            1 :         }
     179              : 
     180              :         // 遮蔽ペナルティ
     181            1 :         _, coverCount := checkLineOfSight(actor, target, world)
     182            1 :         modifier -= coverCount * CoverPenaltyPerObject
     183            1 : 
     184            1 :         return modifier
     185              : }
     186              : 
     187              : // EntityDistance は2エンティティ間の距離を返す
     188              : func EntityDistance(a, b ecs.Entity, world w.World) float64 {
     189            1 :         if !world.Components.GridElement.Has(a) || !world.Components.GridElement.Has(b) {
     190            1 :                 return math.MaxFloat64
     191            1 :         }
     192            1 :         aPos := world.Components.GridElement.Get(a)
     193            1 :         bPos := world.Components.GridElement.Get(b)
     194            1 :         return geometry.Distance(float64(aPos.X), float64(aPos.Y), float64(bPos.X), float64(bPos.Y))
     195              : }
     196              : 
     197              : // checkLineOfSight は射線上の壁と遮蔽物を1パスでチェックする。
     198              : // 壁(BlockView=true)があればblocked=true、遮蔽物(BlockPass=true, BlockView=false)の数をcoverCountで返す
     199              : func checkLineOfSight(actor, target ecs.Entity, world w.World) (blocked bool, coverCount int) {
     200            1 :         if !world.Components.GridElement.Has(actor) || !world.Components.GridElement.Has(target) {
     201            0 :                 return true, 0
     202            0 :         }
     203            1 :         aPos := world.Components.GridElement.Get(actor)
     204            1 :         tPos := world.Components.GridElement.Get(target)
     205            1 : 
     206            1 :         points := geometry.BresenhamLine(consts.Coord[int]{X: int(aPos.X), Y: int(aPos.Y)}, consts.Coord[int]{X: int(tPos.X), Y: int(tPos.Y)})
     207            1 :         for _, p := range points {
     208            1 :                 entities := query.GetEntitiesAt(world, consts.Tile(p.X), consts.Tile(p.Y))
     209            1 :                 for _, e := range entities {
     210            1 :                         if world.Components.BlockView.Has(e) {
     211            1 :                                 return true, coverCount
     212            1 :                         }
     213            1 :                         if world.Components.BlockPass.Has(e) {
     214            1 :                                 coverCount++
     215            1 :                         }
     216              :                 }
     217              :         }
     218            1 :         return false, coverCount
     219              : }
     220              : 
     221              : // CanShootTarget はactorからtargetに射撃可能かを判定する。
     222              : // 射撃対象選択UIでのフィルタリング用
     223              : func CanShootTarget(actor, target ecs.Entity, world w.World) bool {
     224            1 :         comp := NewShootActivity(target)
     225            1 :         return (&ShootBehavior{}).Validate(comp, actor, world) == nil
     226            1 : }
     227              : 
     228              : // CalculateShootHitRate は射撃の命中率を計算して返す。情報パネル表示用
     229              : func CalculateShootHitRate(actor, target ecs.Entity, world w.World) int {
     230            1 :         fire, _, err := getEquippedFire(actor, world)
     231            1 :         if err != nil {
     232            0 :                 return 0
     233            0 :         }
     234              : 
     235            1 :         modifier := calculateRangedHitModifier(actor, target, fire, world)
     236            1 :         modifier += fire.LoadedAccuracyBonus
     237            1 : 
     238            1 :         return calculateHitRate(actor, target, world, fire, modifier)
     239              : }
        

Generated by: LCOV version 2.0-1