Line data Source code
1 : package aiinput
2 :
3 : import (
4 : "math/rand/v2"
5 :
6 : "github.com/kijimaD/ruins/internal/activity"
7 : gc "github.com/kijimaD/ruins/internal/components"
8 : "github.com/kijimaD/ruins/internal/consts"
9 : "github.com/kijimaD/ruins/internal/gamelog"
10 : "github.com/kijimaD/ruins/internal/geometry"
11 : "github.com/kijimaD/ruins/internal/logger"
12 : "github.com/kijimaD/ruins/internal/rawschema"
13 : w "github.com/kijimaD/ruins/internal/world"
14 :
15 : "github.com/kijimaD/ruins/internal/world/lifecycle"
16 : "github.com/kijimaD/ruins/internal/world/query"
17 : "github.com/mlange-42/ark/ecs"
18 : )
19 :
20 : // territorialRadius はTerritorial移動パターンでスポーン地点から離れられる最大距離を定義する
21 : const territorialRadius consts.Tile = 5
22 :
23 : // followStartDistance は休んでいる随伴者が追いかけ始めるプレイヤーとのチェビシェフ距離
24 : const followStartDistance = 4
25 :
26 : // soloPlanner は敵・中立NPC用の行動計画を実装する。
27 : // AIStateの状態遷移とSoloMovementによる移動を統合して行動を決定する
28 : type soloPlanner struct {
29 : visionSystem VisionSystem
30 : logger *logger.Logger
31 : rng *rand.Rand
32 : }
33 :
34 : func newSoloPlanner(rng *rand.Rand) *soloPlanner {
35 1 : return &soloPlanner{
36 1 : visionSystem: NewVisionSystem(),
37 1 : logger: logger.New(logger.CategoryTurn),
38 1 : rng: rng,
39 1 : }
40 : }
41 :
42 : // Plan は状態遷移の評価とアクション決定を一体的に行う。
43 : // APループ内で繰り返し呼ばれ、状態遷移は同一ターン内でべき等
44 : func (rp *soloPlanner) Plan(world w.World, entity ecs.Entity) *gc.Activity {
45 1 : solo := world.Components.SoloAI.Get(entity)
46 1 : if solo == nil {
47 0 : rp.logger.Warn("no SoloAI component", "entity", entity)
48 0 : return nil
49 0 : }
50 1 : grid := world.Components.GridElement.Get(entity)
51 1 :
52 1 : target := rp.findNearestHostile(world, entity)
53 1 : if target == nil {
54 1 : return rp.planDrivingAction(world, entity, solo, grid)
55 1 : }
56 :
57 1 : turnNumber := query.GetTurnState(world).TurnNumber
58 1 : canSee := rp.visionSystem.CanSeeTarget(world, entity, *target, solo.ViewDistance)
59 1 : rp.updateState(solo, canSee, turnNumber)
60 1 :
61 1 : switch solo.SubState {
62 : case gc.AIStateChasing:
63 1 : return rp.planChaseAction(world, entity, *target, grid)
64 : case gc.AIStateFleeing:
65 1 : return rp.planFleeAction(world, entity, *target, grid)
66 : case gc.AIStateDriving:
67 1 : return rp.planDrivingAction(world, entity, solo, grid)
68 : case gc.AIStateWaiting:
69 1 : return waitAction()
70 : default:
71 0 : return waitAction()
72 : }
73 : }
74 :
75 : // findNearestHostile は最寄りの敵対エンティティを探す。
76 : // 視界判定は含まない。Chasing状態で視界外の対象を追い続けるため
77 : func (rp *soloPlanner) findNearestHostile(world w.World, entity ecs.Entity) *ecs.Entity {
78 1 : grid := world.Components.GridElement.Get(entity)
79 1 : nearest, _, _ := query.FindNearestCharacter(world, entity, grid, func(target ecs.Entity) bool {
80 1 : return query.FactionRelation(world, entity, target) == query.RelationHostile
81 1 : })
82 1 : return nearest
83 : }
84 :
85 : // ========== 状態遷移ロジック ==========
86 :
87 : func (rp *soloPlanner) updateState(solo *gc.SoloAI, canSeePlayer bool, currentTurn consts.Turn) {
88 1 : elapsedTurns := currentTurn - solo.StartSubStateTurn
89 1 :
90 1 : switch solo.SubState {
91 : case gc.AIStateWaiting:
92 1 : rp.updateFromWaiting(solo, canSeePlayer, elapsedTurns, currentTurn)
93 : case gc.AIStateDriving:
94 1 : rp.updateFromDriving(solo, canSeePlayer, elapsedTurns, currentTurn)
95 : case gc.AIStateChasing:
96 1 : rp.updateFromChasing(solo, canSeePlayer, elapsedTurns, currentTurn)
97 : case gc.AIStateFleeing:
98 1 : rp.updateFromFleeing(solo, canSeePlayer, elapsedTurns, currentTurn)
99 : default:
100 1 : rp.initializeToWaiting(solo, currentTurn)
101 : }
102 : }
103 :
104 : func (rp *soloPlanner) updateFromWaiting(solo *gc.SoloAI, canSeePlayer bool, elapsedTurns, currentTurn consts.Turn) {
105 1 : if canSeePlayer {
106 1 : switch solo.CombatCurrent {
107 : case rawschema.Evade:
108 1 : rp.transitionToFleeing(solo, currentTurn)
109 : case rawschema.Attack:
110 1 : rp.transitionToChasing(solo, currentTurn)
111 1 : case rawschema.Ignore:
112 : }
113 1 : } else if elapsedTurns >= solo.DurationSubStateTurns {
114 1 : rp.transitionToDriving(solo, currentTurn)
115 1 : }
116 : }
117 :
118 : func (rp *soloPlanner) updateFromDriving(solo *gc.SoloAI, canSeePlayer bool, elapsedTurns, currentTurn consts.Turn) {
119 1 : if canSeePlayer {
120 1 : switch solo.CombatCurrent {
121 : case rawschema.Evade:
122 1 : rp.transitionToFleeing(solo, currentTurn)
123 : case rawschema.Attack:
124 1 : rp.transitionToChasing(solo, currentTurn)
125 1 : case rawschema.Ignore:
126 : }
127 1 : } else if elapsedTurns >= solo.DurationSubStateTurns {
128 1 : rp.transitionToWaiting(solo, currentTurn)
129 1 : }
130 : }
131 :
132 : func (rp *soloPlanner) updateFromChasing(solo *gc.SoloAI, canSeePlayer bool, elapsedTurns, currentTurn consts.Turn) {
133 1 : if !canSeePlayer {
134 1 : if elapsedTurns >= 3 {
135 1 : rp.transitionToDriving(solo, currentTurn)
136 1 : }
137 1 : } else if elapsedTurns >= solo.DurationSubStateTurns {
138 1 : rp.transitionToWaiting(solo, currentTurn)
139 1 : }
140 : }
141 :
142 : func (rp *soloPlanner) updateFromFleeing(solo *gc.SoloAI, canSeePlayer bool, elapsedTurns, currentTurn consts.Turn) {
143 1 : if !canSeePlayer && elapsedTurns >= solo.DurationSubStateTurns {
144 1 : solo.ResetCombat()
145 1 : rp.transitionToDriving(solo, currentTurn)
146 2 : } else if canSeePlayer {
147 1 : solo.StartSubStateTurn = currentTurn
148 1 : }
149 : }
150 :
151 : func (rp *soloPlanner) transitionToWaiting(solo *gc.SoloAI, currentTurn consts.Turn) {
152 1 : solo.SubState = gc.AIStateWaiting
153 1 : solo.StartSubStateTurn = currentTurn
154 1 : solo.DurationSubStateTurns = consts.Turn(2 + rp.rng.IntN(4))
155 1 : }
156 :
157 : func (rp *soloPlanner) transitionToDriving(solo *gc.SoloAI, currentTurn consts.Turn) {
158 1 : solo.SubState = gc.AIStateDriving
159 1 : solo.StartSubStateTurn = currentTurn
160 1 : solo.DurationSubStateTurns = consts.Turn(3 + rp.rng.IntN(7))
161 1 : }
162 :
163 : func (rp *soloPlanner) transitionToChasing(solo *gc.SoloAI, currentTurn consts.Turn) {
164 1 : solo.SubState = gc.AIStateChasing
165 1 : solo.StartSubStateTurn = currentTurn
166 1 : solo.DurationSubStateTurns = consts.Turn(10 + rp.rng.IntN(5))
167 1 : }
168 :
169 : func (rp *soloPlanner) transitionToFleeing(solo *gc.SoloAI, currentTurn consts.Turn) {
170 1 : solo.SubState = gc.AIStateFleeing
171 1 : solo.StartSubStateTurn = currentTurn
172 1 : solo.DurationSubStateTurns = consts.Turn(5 + rp.rng.IntN(5))
173 1 : }
174 :
175 : func (rp *soloPlanner) initializeToWaiting(solo *gc.SoloAI, currentTurn consts.Turn) {
176 1 : solo.SubState = gc.AIStateWaiting
177 1 : solo.StartSubStateTurn = currentTurn
178 1 : solo.DurationSubStateTurns = consts.Turn(2 + rp.rng.IntN(3))
179 1 : }
180 :
181 : // ========== アクション計画ロジック ==========
182 :
183 : func (rp *soloPlanner) planChaseAction(world w.World, aiEntity, playerEntity ecs.Entity, aiGrid *gc.GridElement) *gc.Activity {
184 1 : playerGrid := world.Components.GridElement.Get(playerEntity)
185 1 :
186 1 : if isAdjacent(aiGrid, playerGrid) {
187 1 : return activity.NewMeleeActivity(playerEntity)
188 1 : }
189 :
190 1 : dx := playerGrid.X - aiGrid.X
191 1 : dy := playerGrid.Y - aiGrid.Y
192 1 :
193 1 : candidates := calculateMoveCandidates(consts.Coord[consts.Tile]{X: dx, Y: dy})
194 1 : if b, ok := tryMoveCandidates(world, aiEntity, aiGrid, candidates); ok {
195 1 : return b
196 1 : }
197 :
198 1 : return waitAction()
199 : }
200 :
201 : func (rp *soloPlanner) planFleeAction(world w.World, aiEntity, playerEntity ecs.Entity, aiGrid *gc.GridElement) *gc.Activity {
202 1 : playerGrid := world.Components.GridElement.Get(playerEntity)
203 1 :
204 1 : dx := aiGrid.X - playerGrid.X
205 1 : dy := aiGrid.Y - playerGrid.Y
206 1 :
207 1 : candidates := calculateMoveCandidates(consts.Coord[consts.Tile]{X: dx, Y: dy})
208 1 : if b, ok := tryMoveCandidates(world, aiEntity, aiGrid, candidates); ok {
209 1 : return b
210 1 : }
211 :
212 0 : return rp.planRandomMoveAction(world, aiEntity, aiGrid)
213 : }
214 :
215 : func (rp *soloPlanner) planRandomMoveAction(world w.World, aiEntity ecs.Entity, aiGrid *gc.GridElement) *gc.Activity {
216 1 : if rp.rng.Float64() < 0.3 {
217 1 : return waitAction()
218 1 : }
219 :
220 1 : from := aiGrid.Coord
221 1 : for _, d := range shuffledEightDirections(rp.rng) {
222 1 : dest := from.Add(d)
223 1 : if activity.CanMoveTo(world, dest, from, aiEntity) {
224 1 : return moveAction(dest)
225 1 : }
226 : }
227 :
228 0 : return waitAction()
229 : }
230 :
231 : func (rp *soloPlanner) planDrivingAction(world w.World, aiEntity ecs.Entity, solo *gc.SoloAI, grid *gc.GridElement) *gc.Activity {
232 1 : switch solo.Movement {
233 : case rawschema.Stationary:
234 1 : return waitAction()
235 : case rawschema.Wander:
236 1 : return rp.planWanderAction(world, aiEntity, grid)
237 : case rawschema.WallHug:
238 1 : return rp.planWallHugAction(world, aiEntity, grid)
239 : case rawschema.Swarm:
240 1 : return rp.planSwarmAction(world, aiEntity, grid)
241 : case rawschema.Patrol:
242 1 : return rp.planPatrolAction(world, aiEntity, solo, grid)
243 : case rawschema.Territorial:
244 1 : return rp.planTerritorialAction(world, aiEntity, solo, grid)
245 : case rawschema.Follow:
246 0 : return rp.planFollowAction(world, aiEntity, solo, grid)
247 : default:
248 1 : return rp.planRandomMoveAction(world, aiEntity, grid)
249 : }
250 : }
251 :
252 : func (rp *soloPlanner) planWanderAction(world w.World, aiEntity ecs.Entity, aiGrid *gc.GridElement) *gc.Activity {
253 1 : if rp.rng.Float64() < 0.8 {
254 1 : return waitAction()
255 1 : }
256 1 : return rp.planRandomMoveAction(world, aiEntity, aiGrid)
257 : }
258 :
259 : func (rp *soloPlanner) planWallHugAction(world w.World, aiEntity ecs.Entity, aiGrid *gc.GridElement) *gc.Activity {
260 1 : if rp.rng.Float64() < 0.3 {
261 0 : return waitAction()
262 0 : }
263 :
264 1 : si := query.GetSpatialIndex(world)
265 1 :
266 1 : type scoredDir struct {
267 1 : consts.Coord[consts.Tile]
268 1 : score int
269 1 : }
270 1 : var candidates []scoredDir
271 1 :
272 1 : from := aiGrid.Coord
273 1 : for _, d := range eightDirections {
274 1 : dest := from.Add(d)
275 1 :
276 1 : if !activity.CanMoveTo(world, dest, from, aiEntity) {
277 1 : continue
278 : }
279 :
280 1 : wallCount := 0
281 1 : for _, adj := range []consts.Coord[consts.Tile]{{X: 0, Y: -1}, {X: 0, Y: 1}, {X: -1, Y: 0}, {X: 1, Y: 0}} {
282 1 : if si.IsBlockPass(dest.Add(adj)) {
283 1 : wallCount++
284 1 : }
285 : }
286 1 : candidates = append(candidates, scoredDir{d, wallCount})
287 : }
288 :
289 1 : if len(candidates) == 0 {
290 0 : return waitAction()
291 0 : }
292 :
293 1 : best := candidates[0].score
294 1 : for _, c := range candidates[1:] {
295 1 : if c.score > best {
296 0 : best = c.score
297 0 : }
298 : }
299 1 : var tied []scoredDir
300 1 : for _, c := range candidates {
301 1 : if c.score == best {
302 1 : tied = append(tied, c)
303 1 : }
304 : }
305 1 : chosen := tied[rp.rng.IntN(len(tied))]
306 1 :
307 1 : return moveAction(consts.Coord[consts.Tile]{X: from.X + chosen.X, Y: from.Y + chosen.Y})
308 : }
309 :
310 : func (rp *soloPlanner) planSwarmAction(world w.World, aiEntity ecs.Entity, aiGrid *gc.GridElement) *gc.Activity {
311 1 : _, nearestGrid, nearestDist := query.FindNearestCharacter(world, aiEntity, aiGrid, func(entity ecs.Entity) bool {
312 1 : return world.Components.SoloAI.Has(entity)
313 1 : })
314 :
315 1 : if nearestGrid == nil || nearestDist <= 1 {
316 1 : return rp.planRandomMoveAction(world, aiEntity, aiGrid)
317 1 : }
318 :
319 1 : dx := nearestGrid.X - aiGrid.X
320 1 : dy := nearestGrid.Y - aiGrid.Y
321 1 :
322 1 : candidates := calculateMoveCandidates(consts.Coord[consts.Tile]{X: dx, Y: dy})
323 1 : if b, ok := tryMoveCandidates(world, aiEntity, aiGrid, candidates); ok {
324 1 : return b
325 1 : }
326 :
327 0 : return rp.planRandomMoveAction(world, aiEntity, aiGrid)
328 : }
329 :
330 : func (rp *soloPlanner) planPatrolAction(world w.World, aiEntity ecs.Entity, solo *gc.SoloAI, grid *gc.GridElement) *gc.Activity {
331 1 : from := grid.Coord
332 1 :
333 1 : dest := from.Add(solo.PatrolDir)
334 1 : if activity.CanMoveTo(world, dest, from, aiEntity) {
335 1 : return moveAction(dest)
336 1 : }
337 :
338 1 : solo.PatrolDir.X = -solo.PatrolDir.X
339 1 : solo.PatrolDir.Y = -solo.PatrolDir.Y
340 1 :
341 1 : dest = from.Add(solo.PatrolDir)
342 1 : if activity.CanMoveTo(world, dest, from, aiEntity) {
343 1 : return moveAction(dest)
344 1 : }
345 :
346 1 : return waitAction()
347 : }
348 :
349 : func (rp *soloPlanner) planTerritorialAction(world w.World, aiEntity ecs.Entity, solo *gc.SoloAI, grid *gc.GridElement) *gc.Activity {
350 1 : from := grid.Coord
351 1 :
352 1 : for _, d := range shuffledEightDirections(rp.rng) {
353 1 : dest := from.Add(d)
354 1 :
355 1 : dx := geometry.Abs(dest.X - solo.Origin.X)
356 1 : dy := geometry.Abs(dest.Y - solo.Origin.Y)
357 1 : if dx > territorialRadius || dy > territorialRadius {
358 1 : continue
359 : }
360 :
361 1 : if activity.CanMoveTo(world, dest, from, aiEntity) {
362 1 : return moveAction(dest)
363 1 : }
364 : }
365 :
366 0 : return waitAction()
367 : }
368 :
369 : // planFollowAction は休む・追いつくの2状態で随伴し、状態を SubState の待機と移動で持つ。
370 : // 燃料ポイントが足りなければ待機の方針へ切り替える。展開中は方針を保ったまま休む。
371 : func (rp *soloPlanner) planFollowAction(world w.World, aiEntity ecs.Entity, solo *gc.SoloAI, grid *gc.GridElement) *gc.Activity {
372 1 : if world.Components.Deployed.Has(aiEntity) {
373 1 : solo.SubState = gc.AIStateWaiting
374 1 : return waitAction()
375 1 : }
376 1 : player, err := query.GetPlayerEntity(world)
377 1 : if err != nil {
378 0 : return waitAction()
379 0 : }
380 1 : playerGrid := world.Components.GridElement.Get(player)
381 1 : if isAdjacent(grid, playerGrid) {
382 1 : solo.SubState = gc.AIStateWaiting
383 1 : return waitAction()
384 1 : }
385 1 : if solo.SubState != gc.AIStateDriving {
386 1 : if geometry.ChebyshevDistance(grid.Coord, playerGrid.Coord) < followStartDistance {
387 1 : return waitAction()
388 1 : }
389 1 : solo.SubState = gc.AIStateDriving
390 : }
391 :
392 1 : next, ok := activity.FindNextStep(world, aiEntity, grid.Coord, playerGrid.Coord)
393 1 : if !ok {
394 0 : return waitAction()
395 0 : }
396 :
397 : // AP 不足で runAPLoop が計画を捨てると燃料だけ減るので、払う前に1歩分の AP を確かめる
398 1 : if tb := world.Components.TurnBased.Get(aiEntity); tb == nil || tb.AP.Current < consts.StandardActionCost {
399 1 : return nil
400 1 : }
401 1 : if !lifecycle.ConsumeCubeFuel(world, aiEntity, query.FollowFuelCost(query.CubeWeight(world, aiEntity))) {
402 1 : solo.Movement = rawschema.Stationary
403 1 : solo.SubState = gc.AIStateWaiting
404 1 : gamelog.New(query.GetGameLog(world)).
405 1 : Markup(query.T(world, "The cube is out of fuel and stops.")).
406 1 : Log()
407 1 : return waitAction()
408 1 : }
409 1 : return moveAction(next)
410 : }
|