-
Notifications
You must be signed in to change notification settings - Fork 0
/
ai.go
79 lines (70 loc) · 1.63 KB
/
ai.go
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
package actors
import (
"github.com/shamanr/battle_citty/internal/consts"
"github.com/shamanr/battle_citty/internal/scene/objects/tank"
"math/rand"
"time"
"github.com/faiface/pixel"
)
type AI struct {
*tank.Tank
rand *rand.Rand
prevPosition *pixel.Vec
currentOrientation consts.Orientation
wait time.Duration
}
func NewAI() *AI {
return &AI{
currentOrientation: consts.OrientationBottom,
prevPosition: &pixel.ZV,
}
}
func (ai *AI) SetTank(tank *tank.Tank) {
ai.Tank = tank
ai.rand = rand.New(rand.NewSource(time.Now().UnixNano()))
}
func (ai *AI) Tick(dt time.Duration) {
ai.RandomShoot()
if ai.wait < time.Millisecond*300 {
ai.wait += dt
ai.Move(ai.currentOrientation)
return
}
ai.wait = 0
if ai.Tank.GetPos().Eq(*ai.prevPosition) { // Танк затрял
ai.RandomDirection()
return
}
ai.Move(ai.currentOrientation)
ai.prevPosition = ai.Tank.GetPos()
}
func (ai *AI) Move(orientation consts.Orientation) {
ai.currentOrientation = orientation
switch orientation {
case consts.OrientationTop:
ai.Tank.MoveUp()
case consts.OrientationLeft:
ai.Tank.MoveLeft()
case consts.OrientationBottom:
ai.Tank.MoveDown()
case consts.OrientationRight:
ai.Tank.MoveRight()
}
}
func (ai *AI) RandomDirection() {
switch ai.rand.Intn(4) {
case consts.OrientationTop:
ai.Move(consts.OrientationTop)
case consts.OrientationLeft:
ai.Move(consts.OrientationLeft)
case consts.OrientationBottom:
ai.Move(consts.OrientationBottom)
case consts.OrientationRight:
ai.Move(consts.OrientationRight)
}
}
func (ai *AI) RandomShoot() {
if ai.rand.Intn(1000) > 950 {
ai.Tank.Shoot()
}
}