-
Notifications
You must be signed in to change notification settings - Fork 4
/
player.go
411 lines (351 loc) · 8.74 KB
/
player.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
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
package main
import (
"context"
"fmt"
"os"
"strings"
)
func NewPlayerWithUrl(url string, state PlayerState) *Player {
p := NewPlayer(state)
p.Name = url
p.Strategy = NewNormalStrategy()
return p
}
func NewPlayer(state PlayerState) *Player {
whitelisted := make(map[string]string)
urls := os.Getenv("WHITELISTED_URLS")
for _, url := range strings.Split(urls, ",") {
whitelisted[url] = url
}
p := &Player{
X: state.X,
Y: state.Y,
Direction: state.Direction,
WasHit: state.WasHit,
Score: state.Score,
Whitelisted: whitelisted,
}
p.Strategy = NewNormalStrategy()
return p
}
type Player struct {
Name string
X int `json:"x"`
Y int `json:"y"`
Direction string `json:"direction"`
WasHit bool `json:"wasHit"`
Score int `json:"score"`
Game Game `json:"-"`
State State `json:"-"`
Strategy Strategy `json:"-"`
Whitelisted map[string]string
trappedCount int
consecutiveHitCount int
}
func (p Player) Clone() Player {
return Player{
Name: p.Name,
X: p.X,
Y: p.Y,
Direction: p.Direction,
WasHit: p.WasHit,
Score: p.Score,
Game: p.Game,
Strategy: p.Strategy,
trappedCount: p.trappedCount,
}
}
func (p *Player) Play(ctx context.Context) Move {
ctx, span := tracer.Start(ctx, "Player.Play")
defer span.End()
// TODO Calculate priority whether to attack or to chase
return p.Strategy.Play(ctx, p)
}
func (p *Player) ChangeState(s State) {
p.State = s
}
func (p Player) GetDirection() Direction {
switch p.Direction {
case "N":
return North
case "W":
return West
case "E":
return East
default:
return South
}
}
// TODO testing sonarqube
func (p Player) GetPosition() Point {
return Point{
X: p.X,
Y: p.Y,
}
}
func (p Player) Walk(ctx context.Context) Move {
ctx, span := tracer.Start(ctx, "Player.Walk")
defer span.End()
destination := p.GetPosition().TranslateToDirection(1, p.GetDirection())
if !p.Game.Arena.IsValid(destination) {
return TurnRight
}
// check other player
players := p.GetPlayersInRange(ctx, p.GetDirection(), 1)
if len(players) > 0 {
return TurnRight
}
return WalkForward
}
const attackRange = 3
// GetLowestRank returned players that has lowest rank, exclude whitelisted
func (p Player) GetLowestRank(ctx context.Context) *Player {
ctx, span := tracer.Start(ctx, "Player.GetHighestRank")
defer span.End()
for idx := len(p.Game.LeaderBoard) - 1; idx >= 0; idx-- {
ps := p.Game.LeaderBoard[idx]
target := p.Game.GetPlayerByPosition(Point{ps.X, ps.Y})
if target == nil {
continue
}
_, ok := p.Whitelisted[ps.URL]
if ok {
continue
}
if p.IsMe(target) {
continue
}
if target != nil {
return target
}
}
return nil
}
func (p Player) IsMe(ap *Player) bool {
return p.X == ap.X && p.Y == ap.Y
}
// GetHighestRank returned players that has highest rank, exclude whitelisted
func (p Player) GetHighestRank(ctx context.Context) *Player {
ctx, span := tracer.Start(ctx, "Player.GetHighestRank")
defer span.End()
for _, ps := range p.Game.LeaderBoard {
target := p.Game.GetPlayerByPosition(Point{ps.X, ps.Y})
if target == nil {
continue
}
_, ok := p.Whitelisted[ps.URL]
if ok {
continue
}
return target
}
return nil
}
func (p Player) GetPlayerOnNextPodium(ctx context.Context) *Player {
ctx, span := tracer.Start(ctx, "Player.GetPlayerOnNextPodium")
defer span.End()
myRank := p.Game.LeaderBoard.GetRank(p)
if myRank == 0 {
return nil
}
ps := p.Game.LeaderBoard.GetPlayerByRank(myRank - 1)
return p.Game.GetPlayerByPosition(Point{ps.X, ps.Y})
}
// FindShooterOnDirection return other players which are in attach range and heading toward the player
func (p Player) FindShooterOnDirection(ctx context.Context, direction Direction) *Player {
ctx, span := tracer.Start(ctx, "Player.FindShooterOnDirection")
defer span.End()
var shooter *Player
opponents := p.GetPlayersInRange(ctx, direction, attackRange)
for _, opponent := range opponents {
// assumming the first opponent is the closest one
if opponent.CanHit(ctx, p) {
// filtered = append(filtered, opponent)
shooter = &opponent
break
}
}
return shooter
}
type HitOption func(*HitOptions)
type HitOptions struct {
IgnorePlayer bool
}
func WithIgnorePlayer() HitOption {
return func(options *HitOptions) {
options.IgnorePlayer = true
}
}
// CanHitPoint check whether can attack a player in pt
func (p Player) CanHitPoint(ctx context.Context, pt Point, opts ...HitOption) bool {
ctx, span := tracer.Start(ctx, "Player.CanHitPoint")
defer span.End()
options := &HitOptions{}
for _, o := range opts {
o(options)
}
var ptA = p.GetPosition()
for i := 1; i < (attackRange + 1); i++ {
npt := ptA.TranslateToDirection(i, p.GetDirection())
if !p.Game.Arena.IsValid(npt) {
break
}
if npt.X == pt.X && npt.Y == pt.Y {
return true
}
if !options.IgnorePlayer {
pl := p.Game.GetPlayerByPosition(npt)
if pl != nil {
return false
}
}
}
return false
}
func (p Player) CanHit(ctx context.Context, p2 Player, opts ...HitOption) bool {
ctx, span := tracer.Start(ctx, "Player.CanHit")
defer span.End()
return p.CanHitPoint(ctx, p2.GetPosition(), opts...)
}
func (p Player) GetRank() int {
return p.Game.LeaderBoard.GetRank(p)
}
func (p Player) FindTargetOnDirection(ctx context.Context, direction Direction) *Player {
players := p.GetPlayersInRange(ctx, direction, attackRange)
if len(players) == 0 {
return nil
}
target := players[0]
return &target
}
func (p Player) GetPlayersInRange(ctx context.Context, direction Direction, distance int) []Player {
ctx, span := tracer.Start(ctx, "Player.GetPlayersInRange")
defer span.End()
var playersInRange []Player
var ptA = p.GetPosition()
for i := 1; i < (distance + 1); i++ {
npt := ptA.TranslateToDirection(i, direction)
if !p.Game.Arena.IsValid(npt) {
break
}
if player := p.Game.GetPlayerByPosition(npt); player != nil {
playersInRange = append(playersInRange, *player)
}
}
return playersInRange
}
func (p *Player) rotateCounterClockwise() {
p.setDirection(p.GetDirection().Left())
}
func (p *Player) rotateClockwise() {
p.setDirection(p.GetDirection().Right())
}
func (p *Player) moveForward() {
newPt := p.GetPosition().TranslateToDirection(1, p.GetDirection())
if p.Game.Arena.IsValid(newPt) {
p.setLocation(newPt)
}
}
func (p *Player) setDirection(d Direction) {
p.Direction = d.Name
}
func (p *Player) setLocation(pt Point) {
p.X = pt.X
p.Y = pt.Y
}
type MoveOption func(o *MoveOptions)
type MoveOptions struct {
NextMoveOnly bool
}
func WithOnlyNextMove() MoveOption {
return func(o *MoveOptions) {
o.NextMoveOnly = true
}
}
// RequiredMoves return array of moves that should be taken to follow path
func (p Player) RequiredMoves(ctx context.Context, forPath Path, opts ...MoveOption) []Move {
ctx, span := tracer.Start(ctx, "Player.RequiredMoves")
defer span.End()
options := &MoveOptions{}
for _, o := range opts {
o(options)
}
var fMoves []Move
pc := p.Clone()
for _, pt := range forPath {
// skip the source path
if pt.Equal(p.GetPosition()) {
continue
}
moves, err := pc.MoveToAdjacent(pt)
if err != nil {
break
}
for _, move := range moves {
fMoves = append(fMoves, move)
if options.NextMoveOnly && len(fMoves) == 1 {
return fMoves
}
pc.Apply(move)
}
}
return fMoves
}
func (p *Player) Apply(m Move) {
switch m {
case WalkForward:
p.moveForward()
case TurnRight:
p.rotateClockwise()
case TurnLeft:
p.rotateCounterClockwise()
}
}
var ErrDestNotFound = fmt.Errorf("target not found")
// MoveToAdjacent return array of moves to reach adjacent cell.
// This only return non empty moves if the toPt is adjacent cell on north, east,
// west, or south.
func (p Player) MoveToAdjacent(toPt Point) ([]Move, error) {
const distance = 1
var cCount, ccCount int // clockwise and counter clockwise counter
p1 := p.Clone()
p2 := p.Clone()
var p1Move, p2Move []Move
var found = false
for i := 0; i < 4; i++ {
ptInFront := p1.GetPosition().TranslateToDirection(distance, p1.GetDirection())
if ptInFront.Equal(toPt) {
found = true
break
}
p1.rotateCounterClockwise()
p1Move = append(p1Move, TurnLeft)
ccCount++
}
if !found {
return nil, ErrDestNotFound
}
for i := 0; i < 4; i++ {
ptInFront := p2.GetPosition().TranslateToDirection(distance, p2.GetDirection())
if ptInFront.Equal(toPt) {
break
}
p2.rotateClockwise()
p2Move = append(p2Move, TurnRight)
cCount++
}
if ccCount <= cCount {
p1Move = append(p1Move, WalkForward)
return p1Move, nil
} else {
p2Move = append(p2Move, WalkForward)
return p2Move, nil
}
}
func (p *Player) UpdateHitCount() {
if p.WasHit {
p.consecutiveHitCount++
} else {
p.consecutiveHitCount = 0
}
}