aboutsummaryrefslogtreecommitdiff
path: root/go/game/ai.go
blob: 1b4b4e79279c11c1685292de6d4430ab655e3aca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
package game

import (
	"fmt"
	"log"
	"strconv"
	"strings"
	"sync"

	"github.com/RyanCarrier/dijkstra"
)

type UnitAI struct {
	s             *State
	u             *Unit
	actions       chan Action
	syncGameState *sync.WaitGroup
}

func (ai *UnitAI) NextAction() Action {
	return <-ai.actions
}

func (ai *UnitAI) PostAndContinue(a Action) bool {
	if a == nil {
		return true
	}

	ai.actions <- a
	return ai.awaitGameStateSync()
}

func (ai *UnitAI) awaitGameStateSync() bool {
	ai.syncGameState.Wait()
	ai.syncGameState.Add(1)
	return !ai.u.IsDestroyed()
}

func (ai *UnitAI) promptAction() {
	ai.syncGameState.Done()
}

func (ai *UnitAI) Execute(f func(*UnitAI)) {
	defer close(ai.actions)
	if ai.awaitGameStateSync() {
		f(ai)
	}
}

func NewUnitAI(s *State, u *Unit) *UnitAI {
	aiDesc := u.Card.getAI()
	if aiDesc == "" {
		return nil
	}

	c := make(chan Action)
	wg := new(sync.WaitGroup)
	wg.Add(1)
	ai := &UnitAI{s, u, c, wg}

	switch aiDesc {
	case "aggressive":
		go ai.Execute(AggressiveAI)
	case "shy":
		go ai.Execute(ShyAI)
	case "wandering":
		aiDesc := u.Card.getAI()
		x, err := strconv.Atoi(strings.Split(u.Card.getAI(), " ")[1])
		if err != nil {
			log.Fatalf("Invalid wandering AI description %s", aiDesc)
		}
		go ai.Execute(func(ai *UnitAI) { WanderingAI(ai, x) })
	case "target-oriented":
		go ai.Execute(TargetOrientedAI)
	}

	return ai
}

func (m *Map) generateMapGraphFor(u *Unit) *dijkstra.Graph {
	graph := dijkstra.NewGraph()
	for _, t := range m.AllTiles() {
		graph.AddMappedVertex(t.Position.String())
	}

	for _, t := range m.AllTiles() {
		tId := t.Position.String()
		for _, neighbour := range TilesInRangeFromOrigin(m, t.Position, 1) {
			if u.IsAvailableTile(neighbour) {
				cost := 2
				if t.OnDiagonal(neighbour) {
					cost = 3
				}
				err := graph.AddMappedArc(tId, neighbour.Position.String(), int64(cost))
				if err != nil {
					log.Fatalf("Failed to add mapped arc: %s", err)
				}
			}
		}
	}
	return graph
}

func findPathTo(graph *dijkstra.Graph, u *Unit, pos Position) (dijkstra.BestPath, error) {
	srcId, err := graph.GetMapping(u.GetTile().Position.String())
	if err != nil {
		log.Fatalf("No mapping %s in Graph: %s", u.GetTile().Position.String(), err)
	}

	destId, err := graph.GetMapping(pos.String())
	if err != nil {
		log.Fatalf("No mapping %s in Graph: %s", pos.String(), err)
	}

	return graph.Shortest(srcId, destId)
}

func findPathsToUnits(graph *dijkstra.Graph, m *Map, u *Unit, units []*Unit) []*dijkstra.BestPath {
	paths := []*dijkstra.BestPath{}

	for _, unit := range units {
		var bestPathToUnit *dijkstra.BestPath = nil
		for _, adjacentTile := range TilesInRangeFromOrigin(m, unit.GetTile().Position, 1) {
			path, err := findPathTo(graph, u, adjacentTile.Position)
			if err != nil {
				continue
			} else if bestPathToUnit == nil || path.Distance < bestPathToUnit.Distance {
				bestPathToUnit = &path
			}
		}
		paths = append(paths, bestPathToUnit)
	}
	return paths
}

func moveToRandomTile(ai *UnitAI) Action {
	if ai.u.AvailMoveActions == 0 {
		return nil
	}

	moveTargets := ai.u.MoveRangeTiles(ai.s.Map)
	if len(moveTargets) == 0 {
		return nil
	}

	idx := 0
	if len(moveTargets) > 1 {
		idx = ai.s.Rand.Intn(len(moveTargets) - 1)
	}
	moveTarget := moveTargets[idx]
	a := NewMoveActionPrototype(ai.u).Specialize(moveTarget)
	return a
}

func moveTowardsNearestEnemyUnit(ai *UnitAI) Action {
	if ai.u.AvailMoveActions == 0 {
		return nil
	}

	graph := ai.s.Map.generateMapGraphFor(ai.u)
	enemyUnits := ai.s.EnemyUnits(ai.u.GetController())
	if len(enemyUnits) == 0 {
		return nil
	}

	paths := findPathsToUnits(graph, ai.s.Map, ai.u, enemyUnits)
	nearest := 0
	for i, p := range paths {
		if p == nil {
			continue
		}

		if paths[nearest] == nil || p.Distance < paths[nearest].Distance {
			nearest = i
		}
	}

	if paths[nearest] == nil {
		return nil
	}

	var target Position
	for _, id := range paths[nearest].Path[1:] {
		mapping, _ := graph.GetMapped(id)
		var x, y int
		fmt.Sscanf(mapping, "(%d, %d)", &x, &y)
		nextStep := Position{X: x, Y: y}
		if IsPositionInRange(ai.u.GetTile().Position, nextStep, ai.u.Movement.Range) {
			target = nextStep
		} else {
			break
		}
	}
	a := NewMoveActionPrototype(ai.u).Specialize(ai.s.Map.TileAt(target))
	return a
}

func attackAttackableEnemyPerm(ai *UnitAI) Action {
	attackablePerms := ai.u.AttackableEnemyPermanents(ai.s.Map)
	if ai.u.AvailAttackActions == 0 || len(attackablePerms) == 0 {
		return nil
	}

	idx := 0
	if len(attackablePerms) > 1 {
		idx = ai.s.Rand.Intn(len(attackablePerms) - 1)
	}
	attackablePerm := attackablePerms[idx]
	a := NewAttackActionPrototype(ai.u).Specialize(attackablePerm)
	return a
}

//  1. If enemy Unit in attack Range then
//     attack enemy Unit in Range
//  2. While move action available do
//     3a. If enemy unit exists
//     move towards nearest enemy unit until it is in attack range
//     if attack action avail then proceed at 1.
//     3b. Otherwise
//     move to random tile in movement range
func AggressiveAI(ai *UnitAI) {
	// 1.
	a := attackAttackableEnemyPerm(ai)
	if !ai.PostAndContinue(a) {
		return
	}

	// 2.
	if ai.u.AvailMoveActions > 0 {
		a = moveTowardsNearestEnemyUnit(ai)
		if !ai.PostAndContinue(a) {
			return
		}

		if a != nil && ai.u.AvailAttackActions > 0 {
			AggressiveAI(ai)
		} else { // 3b.
			a = moveToRandomTile(ai)
			if a != nil {
				ai.actions <- a
			}
		}
	}
}

// 2.2 Shy
//  1. If not in the attack Range of an enemy Unit then
//     activate full action if available
//  2. If move action available then
//     move to most distant point from all enemy units
//  3. If enemy Unit in attack Range then
//     attack enemy Unit in Range
func ShyAI(ai *UnitAI) {
	// 1.
	inEnemyAttackRange := false
out:
	for _, enemyUnit := range ai.s.EnemyUnits(ai.u.GetController()) {
		for _, p := range enemyUnit.AttackablePermanents(ai.s.Map) {
			if p == ai.u {
				inEnemyAttackRange = true
				break out
			}
		}
	}
	if !inEnemyAttackRange && ai.u.HasFullAction() {
		// return NewFullActionPrototype(u).Specialize(u.FullActionResolveFunc())
		a := NewFullActionPrototype(ai.u).Specialize()
		ai.actions <- a
	}

	// 2.
	// TODO: implement path finding
	// if u.AvailMoveActions > 0 {
	// }

	// 3.
	if ai.u.AvailAttackActions > 0 {
		attackAttackableEnemyPerm(ai)
	}
}

// 2.3 Wandering X
//  1. If enemy unit in Range X then
//     execute aggressive AI
//  2. If move action available then
//     move to random tile in movement Range
//     proceed at 1.
func WanderingAI(ai *UnitAI, x int) {
	// 1.
	for _, enemyUnit := range ai.s.EnemyUnits(ai.u.GetController()) {
		if IsPositionInRange(ai.u.GetTile().Position, enemyUnit.GetTile().Position, x) {
			AggressiveAI(ai)
			break
		}
	}
	// 2.
	if ai.u.AvailMoveActions > 0 {
		moveToRandomTile(ai)
		WanderingAI(ai, x)
	}
}

// 2.4 Target-oriented TARGET
// 1. Use full action if possible
// 2a. If a TARGET exists and is reachable
//
//	Move onto or towards nearest TARGET
//	3a. If enemy Unit in attack Range
//	    attack enemy Unit in Range
//
// 2b. Otherwise
//
//	execute wandering 3 AI
func TargetOrientedAI(ai *UnitAI) {
	// 1.
	if ai.u.HasFullAction() {
		ai.u.FullAction()
	}

	// if ai.t != nil {
	// // TODO: path finding again
	// attackAttackableEnemyPerm(ai)
	// } else {
	WanderingAI(ai, 3)
	// }
}