-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMyStrategy.kt
936 lines (768 loc) · 31.4 KB
/
MyStrategy.kt
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
package core
import Debug
import model.*
import model.Unit
import sim.SimScore
import sim.Simulator
import strats.*
import util.*
import java.lang.Math.abs
import java.util.*
import kotlin.math.absoluteValue
//TODO calc two sims at once
//TODO Handle two units at once
//TODO better resource management, keep to center of the map
//TODO stay away from rocket launcher (check space around) - kind of
//TODO calc potential field of danger zones
//TODO go closer when enemy reloading or near it
//TODO go away when enemy ready
//TODO do not use much rocket launcher?
//TODO add simple run to enemy strategy
//TODO aggressive potential fields for health?
//TODO handle mines
//+++ check jumppad is triggered by any intersect
//+++ handle one sim with other preselected sim
//TODO handle weapon pick trhough sim
//TODO keep smaller distance to enemy for better aiming
//TODO added smarter enemy strat
//TODO calc time and drop calculations 20*3600+20000
//TODO canshot - do sim for simulate movements if jump pad or falling down
//TODO do rush if points amount is smaller
class MyStrategy : AbstractStrategy() {
private var powerSaveMode: Boolean = false
private var accumTookMs: Long = 0L
private var forceSimTill: Int = 0
private var myLastHp = mutableMapOf<Int, Int>()
private var simTill: Int = 0
private var statBox = StatBox()
private var prevGame: Game? = null
private var timeEnd: Long = 0L
private var timeStart: Long = 0L
private var savedStrat = SavedStrat()
private var shootingStart = SmartGuyStrategy(this).apply {
isReal = true
disableShooting = false
}
init {
isReal = true
}
override fun getAction(me: Unit, game: Game, debug: Debug): UnitAction {
super.getAction(me, game, debug)
checkPrevGame()
val maxTimeMs = getMaxTimeMs()
powerSaveMode =
game.currentTick > game.properties.maxTickCount / 3 && accumTookMs.toFloat() / maxTimeMs > game.currentTick.toFloat() / game.properties.maxTickCount
log { "jumpInfo=${me.jumpState.description()}" }
timeStart = System.currentTimeMillis()
val action: UnitAction
if (game.bullets.isNotEmpty()) {
simTill =
(game.currentTick + game.properties.weaponParams[WeaponType.PISTOL]!!.reloadTime * game.properties.ticksPerSecond).toInt()
}
if (game.currentTick - simTill > 400) {
simTill = game.currentTick + 60
}
val shootAction = shootingStart.getAction(me, game, debug)
val noWeapon = me.weapon != null
var isDoSim = simTill >= game.currentTick && noWeapon
if (myLastHp.getOrPut(me.id, { game.properties.unitMaxHealth }) > me.health) {
//taking damage
forceSimTill = game.currentTick + 40
}
if (isRocketBulletsNearBy()) {
//taking damage
forceSimTill = game.currentTick + 40
}
if (!shootAction.shoot && game.bullets.isEmpty()) {
isDoSim = false
}
if (!isDoSim && noShootTick() > 150 && game.currentTick % 100 > 50) {
isDoSim = true
} else if (isDoSim && noShootTick() > 150) {
isDoSim = false
}
if (game.currentTick < forceSimTill) {
isDoSim = true
}
if (isDoSim == false && game.mines.any { it.position.distance(me.position) < 6 }) {
isDoSim = true
}
if (me.weapon == null && (getClosestWeaponItem(null)?.position?.distance(me.position) ?: 999.0) < 1) {
isDoSim = false
}
//isDoSim = true //TODO remove
if (!isDoSim) {
action = shootAction
setCurrentStrat(shootingStart)
} else {
action = doSimMove()
action.shoot = shootAction.shoot
action.aim = shootAction.aim
action.reload = shootAction.reload
action.plantMine = shootAction.plantMine
action.swapWeapon = shootAction.swapWeapon
}
fixStuck(action)
if (me.mines > 1 && action.plantMine && me.onGround && getMyLastAction()?.plantMine != true) {
var oneMineIsEnough = false
shootingStart.nearestEnemy?.let { en ->
if (en.health <= 50) {
oneMineIsEnough = true
} else if (me.weapon?.typ == WeaponType.ROCKET_LAUNCHER) {
oneMineIsEnough = true
}
}
if (!oneMineIsEnough) {
//lets stay for one tick
action.velocity = 0.0
action.jump = false
action.jumpDown = false
action.shoot = false
log { "stay for one more mine" }
} else {
log { "one mine is enough" }
}
}
// action.shoot = false //TODO remove
timeEnd = System.currentTimeMillis()
printAction(action)
printMap(action)
d { debug.draw(CustomData.Log("shoot=${action.shoot} aim=${action.aim}")) }
prevActions.getOrPut(me.id) { mutableListOf() }.add(action)
calcStats()
myLastHp[me.id] = me.health
val tookTime = timeEnd - timeStart
accumTookMs += tookTime
if (game.currentTick % 200 == 0 && (getAnotherUnit()?.id ?: -1 < me.id) || tookTime > 100) {
println("${game.currentTick} : took=$tookTime total=$accumTookMs")
}
return action
}
private fun getMaxTimeMs(): Int {
return 20 * game.properties.maxTickCount + 20000
}
private fun setCurrentStrat(newStrat: StrategyAdvCombined) {
if (savedStrat.savedAt == game.currentTick) {
return
}
savedStrat.savedAt = game.currentTick
savedStrat.strat = newStrat
savedStrat.forUnitId = me.id
}
private fun isRocketBulletsNearBy(): Boolean {
return game.bullets.any { bullet -> bullet.explosionParams != null && me.position.distance(bullet.position) < 20 }
}
private fun fixStuck(action: UnitAction) {
}
private fun noShootTick(): Int {
var count = 0
val actions = prevActions.getOrPut(me.id, { mutableListOf() })
for (i in actions.size - 1 downTo 0) {
if (!actions[i].shoot) {
count++
} else {
return count
}
}
return count
}
private fun bulletsNear(): Boolean {
return game.bullets.any { bullet -> bullet.playerId != me.playerId && bullet.position.distance(me.position) < 9 }
}
private fun calcStats() {
if (me.id != game.units.filter { it.isMy() }.minBy { it.id }!!.id) {
return
}
statBox.put(game)
if (game.currentTick % 200 == 0) {
statBox.print()
}
}
private fun checkPrevGame() {
prevGame?.let {
for (oldUnit in it.units) {
game.units.firstOrNull { it.id == oldUnit.id }
?.let { newUnit ->
if (newUnit.stand) {
}
}
}
}
prevGame = game
}
private fun drawDebugSimulator(simScores: ArrayList<SimScore>, best: SimScore) {
var colorIndex = 0
val smallSize = Point2D(1 / 10f, 1 / 10f)
val bigSize = smallSize.copy().mul(2.0)
simScores.sortedBy { it.score }.asReversed().forEach { evalAndSim ->
var myColor = simColors[colorIndex % simColors.size]
var size = smallSize
val isBest = best == evalAndSim
if (isBest) {
myColor = myColor.copy(a = 1f)
size = bigSize
}
log { "sim $colorIndex ${evalAndSim}" }
val sim = evalAndSim.simulator
val anotherMeId = getAnotherUnit()?.id
for (entry in sim.metainfo.movements) {
if (entry.key != anotherMeId && entry.value.isNotEmpty()) {
val last = entry.value.last()
entry.value.fori { movePoint ->
debug.rect(movePoint, size, myColor)
if (movePoint === last && me.id == entry.key) {
debug.text("${colorIndex}_${evalAndSim.score.f()}", movePoint, myColor)
}
}
}
}
colorIndex++
if (isBest) {
for (bullet in sim.metainfo.bulletsHistory) {
val bulletSize = Point2D(bullet.size, bullet.size)
debug.rect(bullet.position, bulletSize, myColor)
}
for (hit in sim.metainfo.unitHitRegs) {
val size = game.properties.mineSize
debug.rect(hit.point, size, ColorFloat.RED)
debug.text(
hit.bullet.weaponType.toString(),
hit.point.copy().minus(0.0, 0.5),
ColorFloat.RED,
size = 18f
)
}
for (exp in sim.metainfo.explosions) {
debug.rect(exp.point, Point2D(exp.radius * 2, exp.radius * 2), ColorFloat.EXPLOSION)
for (affectedUnit in exp.affectedUnits) {
val unitSize = game.properties.unitSize
debug.rect(
affectedUnit.copy().plus(0.0, unitSize.y / 2), unitSize,
ColorFloat.EXPLOSION_UNIT
)
}
}
for (deadUnit in sim.metainfo.deadUnits) {
val unitSize = game.properties.unitSize
val center = deadUnit.toUnitCenter()
debug.rect(
center, unitSize,
ColorFloat.DEAD_SIM_UNIT
)
debug.text("X_X", center, ColorFloat.RED)
}
}
}
}
private fun doSimMove(): UnitAction {
val variants = mutableListOf<StrategyAdvCombined>()
if (!powerSaveMode) {
val smartGuy = SmartGuyStrategy(this)
smartGuy.disableShooting = true
variants.add(smartGuy)
}
val nearestJumpPad = getNearestJumpPad()
if ((nearestJumpPad?.distance(me.position) ?: 1000.0) < 16.0) {
variants.add(GoToTileStrat(nearestJumpPad!!, "jumpPad"))
}
if (me.weapon == null && shootingStart.nearestWeapon?.let { it.position.distance(me.position) < 5.0 } == true) {
//pick weapon strat
variants.add(GoToTileStrat(shootingStart.nearestWeapon!!.position.copy().noRoundCopy(), "weapon"))
}
if (me.health < game.properties.unitMaxHealth && shootingStart.nearestHealth?.let { it.position.distance(me.position) < 5.0 } == true) {
//pick weapon strat
variants.add(GoToTileStrat(shootingStart.nearestHealth!!.position.copy().noRoundCopy(), "health"))
}
val lastRealTargetPos = shootingStart.lastRealTargetPos
if (lastRealTargetPos != null && me.position.y < lastRealTargetPos.y) {
getNearestLadder()?.let {
variants.add(GoToTileStrat(it, "ladderUp", true))
}
}
MoveLeftRight.cValues.forEach { leftRight ->
MoveUpDown.cValues.forEach { upDown ->
variants.add(MoveStrategy(leftRight, upDown))
}
}
var tickK = getMaxJumpTicks() / 3 * 3
// variants.clear()
// //variants.add(MoveStrategy(MoveLeftRight.RIGHT, MoveUpDown.STILL))
// variants.add(MoveStrategy(MoveLeftRight.RIGHT, MoveUpDown.UP))
// //variants.add(DebugAndJumpStrategy())
// tickK = getMaxJumpTicks() * 20
val strat = pickBestStrat(variants, tickK)
strat.isReal = true
setCurrentStrat(strat)
return strat.getAction(me, game, debug)
}
val ladderFindPoints = mutableListOf(
Point2D(0, 0),
Point2D(1, 0),
Point2D(-1, 0),
Point2D(2, 0),
Point2D(-2, 0),
Point2D(3, 0),
Point2D(-3, 0),
Point2D(-4, 0),
Point2D(4, 0)
)
private fun getNearestLadder(): Point2D? {
val posToCheck = me.position.copy()
ladderFindPoints.forEach {
val posToCheckReal = posToCheck.copy().plus(it)
game.level.tiles.getNoRound(posToCheckReal)?.let {
if (it == Tile.LADDER) {
return posToCheckReal.noRoundCopy()
}
}
}
return null
}
private fun getNearestJumpPad(): Point2D? {
return game.level.jumpPads.minBy { it.sqDistance(me.position) }
}
private fun pickBestStrat(strats: MutableList<StrategyAdvCombined>, tickK: Double): StrategyAdvCombined {
val evalAndSims = ArrayList<SimScore>()
var i = 0
while (!strats.isEmpty()) {
val strat = strats[0]
val simulator = startSimulator(ProxyStrategy(strat), simColors[i % simColors.size], tickK, i == 0)
val evalAndSim = eval(simulator, strat)
strats.removeAt(0)
evalAndSims.add(evalAndSim)
i++
}
//TODO stop if found good enough, add more strats if want better ones
//TODO compare calculated and actual time touch, if actual time too differs then calc backward moves
var best = evalAndSims.maxBy { it.score }!!
log { "picked strat=${best}" }
drawDebugSimulator(evalAndSims, best)
return best.strat
}
private fun eval(simulator: Simulator, strat: StrategyAdvCombined): SimScore {
val simScore = SimScore(0.0, simulator, strat)
var score = 0.0
val myUnitsSim = simulator.game.units.filter { it.playerId == me.playerId }
val remainingTeamHealth = myUnitsSim.sumBy { it.health } * 100
val enHealth = simulator.game.units.filter { !it.isMy() }.sumBy { it.health } * 1
score -= enHealth
val imRocket = me.weapon?.typ == WeaponType.ROCKET_LAUNCHER
//val myUnits = game.units.filter { it.isMy() }
// val diff = myUnitsSim.size - myUnits.size
// score -= diff * 1000
score += remainingTeamHealth.toDouble()
checkStrangeScore(score)
simScore.myHealthBonus = remainingTeamHealth
simScore.enHealthPenalty = enHealth
val currentDistToEnemies = game.getMinDistToEnemies(me)!!
val simDistToEnemies = simulator.game.getMinDistToEnemies(me)
val anotherUnit = getAnotherUnit()
if (strat is MoveStrategy) {
// if (strat.moveUpDown == MoveUpDown.UP && !me.onGround && !me.onLadder && (anotherUnit?.id ?: 0) > me.id) {
// score += 10
// }
}
val mySimUnitPos = simulator.game.getUnitPosNullable(me.id)
val mySimUnit = simulator.game.getUnitNullable(me)
//jump pad
if (mySimUnit != null && !mySimUnit.onGround && !mySimUnit.onLadder && mySimUnit.jumpState.maxTime > 0 && !mySimUnit.jumpState.canCancel) {
score -= 15
}
if (simDistToEnemies == null) {
score -= 1
}
//switch wit other unit
anotherUnit?.let { another ->
score -= simulator.metainfo.unitDamage.getOrPut(another.id, { Ref(0.0) }).ref * 5
val distAbs = (another.position.copy() - me.position).abs()
val xDist = distAbs.x
val yDist = distAbs.y
if (xDist > 5 || yDist > 7) {
val distToAnother = simulator.game.getDist(me, another)
score -= distToAnother * 5
if (me.health == 100) {
score -= distToAnother * 5
}
checkStrangeScore(score)
}
if (xDist > 2) {
return@let
}
if (simDistToEnemies == null) {
//we dead
return@let
}
val delta = simDistToEnemies - currentDistToEnemies
val sameHealthButIdLower =
another.health == me.health && another.id > me.id && another.weapon?.typ != WeaponType.ROCKET_LAUNCHER
val sameHealthButHasRocketLauncher = another.health == me.health &&
me.weapon?.typ == WeaponType.ROCKET_LAUNCHER &&
another.weapon?.typ != WeaponType.ROCKET_LAUNCHER
//sw
if (another.health < me.health || (sameHealthButIdLower || sameHealthButHasRocketLauncher)) {
score -= delta * 5
} else {
score += delta * 5
}
checkStrangeScore(score)
//log { "simDistToEnemies=${simDistToEnemies} ${currentDistToEnemies}" }
}
if (simDistToEnemies != null && me.health == 100 && mySimUnitPos != null && weaponOperable(me)) {
if (simDistToEnemies > 8) {
score -= simDistToEnemies * 10
checkStrangeScore(score)
}
}
score -= simulator.metainfo.unitDamage.getOrPut(me.id, { Ref(0.0) }).ref * 10
checkStrangeScore(score)
val distToCenter = abs(me.position.x - game.level.tiles.cellsWidth / 2)
if (distToCenter > game.level.tiles.cellsWidth / 3) {
//keep center
mySimUnitPos?.let { mySimPos ->
score -= (abs(mySimPos.x - game.level.tiles.cellsWidth / 2)) / 100
checkStrangeScore(score)
}
}
val noShootTick = noShootTick()
if (noShootTick > 150 && simDistToEnemies != null) {
score -= simDistToEnemies
if (noShootTick > 300) {
score -= simDistToEnemies * 3
}
if (noShootTick > 500) {
score -= simDistToEnemies * 5
}
}
//health
var likeGoingToHeal = false
if (me.health < game.properties.unitMaxHealth * 0.9 && simulator.game.healthCount() > 0) {
val distToHealtRaw = getMinDistToHealth(simulator.game, me)
if (distToHealtRaw < 120) {
val distToHealth = distToHealtRaw * 10
score -= distToHealth
checkStrangeScore(score)
likeGoingToHeal = true
}
}
//keep away when reloading
if (currentDistToEnemies < 9 && simDistToEnemies != null) {
var reloadThreshold = 0.15
if (me.weapon?.typ == WeaponType.ROCKET_LAUNCHER) {
reloadThreshold = 0.45
}
if (me.weapon?.fireTimer ?: 0.0 > reloadThreshold) {
val bonusDist = simDistToEnemies * 3
score += bonusDist
checkStrangeScore(score)
}
}
val simMe = simulator.game.getUnitNullable(me)
simMe?.onLadder?.then {
score += 5
}
simMe?.onGround?.not()?.then {
val simPosCopy = simMe.position.copy()
score += 5
if (game.level.isAir(simPosCopy.applyDir(Direction.DOWN)) && game.level.isAir(simPosCopy.applyDir(Direction.DOWN))) {
score += 5
}
}
val mySimPos = mySimUnitPos
val closestEnemy = getClosestEnemy()
if (me.weapon?.typ != WeaponType.ROCKET_LAUNCHER) {
//keep away from rocket mans
closestEnemy?.let {
game.units.filter {
!it.isMy() && it.weapon?.typ == WeaponType.ROCKET_LAUNCHER
}.forEach {
val dist = me.position.pathDist(it.position)
if (mySimPos != null && dist < 6) {
score += mySimPos.pathDist(closestEnemy.position)
checkStrangeScore(score)
}
}
}
}
//penalty for far dist from target
if (mySimPos != null) {
shootingStart.lastRealTargetPos?.let { smartTarget ->
val targetPathPenaly = smartTarget.pathDist(me.position) / 2
score -= targetPathPenaly
simScore.targetPathPenaly = targetPathPenaly
checkStrangeScore(score)
}
}
//keep to enemy without weapon
if (mySimPos != null && closestEnemy != null && me.weapon != null && closestEnemy.weapon == null) {
simulator.game.getUnitPosNullable(closestEnemy.id)?.let { enSimPos ->
score -= mySimPos.pathDist(enSimPos) * 40
}
}
//keep to enemy without health
if (simMe != null && mySimPos != null && closestEnemy != null && me.weapon != null && closestEnemy.health * 2 < simMe.health) {
simulator.game.getUnitPosNullable(closestEnemy.id)?.let { enSimPos ->
score -= mySimPos.pathDist(enSimPos) * 20
}
}
if (simDistToEnemies != null && me.weapon?.typ == WeaponType.ROCKET_LAUNCHER && !likeGoingToHeal) {
score -= simDistToEnemies * 3
checkStrangeScore(score)
}
//TODO avoid tight places
if (mySimPos != null && me.weapon != null) {
val potentialWalls = Potential.potential.getFastNoRound(mySimPos)
val wallsPenalty = if (likeGoingToHeal) {
potentialWalls / 2
} else {
potentialWalls * 2
}
score -= wallsPenalty
simScore.potentialWallsPenalty = wallsPenalty
checkStrangeScore(score)
}
//keep back from our rocket man
anotherUnit?.let {
if (it.weapon?.typ == WeaponType.ROCKET_LAUNCHER && closestEnemy != null && mySimPos != null) {
if (isBetween(closestEnemy.position, mySimPos, anotherUnit.position)) {
return@let
}
val distToANother = me.position.pathDist(anotherUnit.position)
if (distToANother < 4 && anotherUnit.position.pathDist(closestEnemy.position) < 4.5) {
score += mySimPos.pathDist(anotherUnit.position) / 2
score += mySimPos.pathDist(closestEnemy.position) / 2
if (anotherUnit.position.pathDist(closestEnemy.position) < 2) {
score += mySimPos.pathDist(anotherUnit.position) / 2
score += mySimPos.pathDist(closestEnemy.position) / 2
}
checkStrangeScore(score)
}
}
}
//plus pick gun
if ((me.weapon == null || (imRocket && shootingStart.ignoreRocket)) && mySimPos != null) {
var closestWeaponItem = getClosestWeaponItem(null)
if (imRocket) {
closestWeaponItem = getPrefferedWeapon(null)
}
var pathToGun = closestWeaponItem?.position?.pathDist(mySimPos)
if (pathToGun != null && pathToGun < 100) {
pathToGun += closestWeaponItem!!.position.distance(mySimPos) % 1
val pathPenalty = pathToGun * 100
score -= pathPenalty
simScore.pathToGunPenalty = pathPenalty
checkStrangeScore(score)
}
}
if (mySimPos != null) {
var path = simulator.game.getMinDistToHealth(mySimPos)
if (path != null && path < 100) {
path /= 1
score -= path
simScore.pathToHealPenalty = path
checkStrangeScore(score)
}
}
//falling
if (mySimUnit != null && !mySimUnit.onGround && !mySimUnit.onLadder && mySimUnit.jumpState.maxTime > 0 &&
!(imRocket && !likeGoingToHeal)
) {
score -= 15
if (simDistToEnemies != null) {
score += simDistToEnemies * 5
}
}
//TODO calc in game score
//TODO antistuck
return simScore.apply {
this.score = score
createdAtTick = game.currentTick
}
}
private fun weaponOperable(me: Unit): Boolean {
val weapon = me.weapon ?: return false
return when (weapon.typ) {
WeaponType.ROCKET_LAUNCHER -> (weapon.fireTimer ?: 0.0) < 0.45
WeaponType.PISTOL -> weapon.magazine > 3
WeaponType.ASSAULT_RIFLE -> weapon.magazine > 10
}
}
private fun checkStrangeScore(score: Double) {
if (score < -1000) {
val x = 10
}
}
private fun isBetween(center: Point2D, side1: Point2D, side2: Point2D): Boolean {
val minX = minOf(side1.x, side2.x)
val maxX = maxOf(side1.x, side2.x)
val isBetween = center.x > minX && center.x < maxX
if (isBetween) {
return true
}
val deltaMin = (center.x - minX).absoluteValue
val deltaMax = (center.x - maxX).absoluteValue
val deltaX = minOf(deltaMax, deltaMin)
if (deltaX < 3) {
val minY = minOf(side1.y, side2.y)
val maxY = maxOf(side1.y, side2.y)
return center.y > minY && center.y < maxY
}
return isBetween
}
private fun getMinDistToHealth(game: Game, unit: Unit): Double {
val actualUnit = game.units.firstOrNull { it.id == unit.id } ?: return 0.0
val enemies = game.units.filter { it.playerId != unit.playerId }
return game.lootBoxes
.filter { it.item is Item.HealthPack }
.map { health ->
val distToMe = health.position.pathDist(actualUnit.position)
if (enemies.map { health.position.pathDist(it.position) }.any { it < distToMe }) {
return@map 999999.0
}
distToMe
}.min() ?: 0.0
}
private fun startSimulator(
myStrat: Strategy,
color: ColorFloat,
tickK: Double,
calcActualPath: Boolean
): Simulator {
val simGame = game.copy()
val sim = Simulator(simGame)
//val enStrat = SmartGuyStrategy(this)
//enStrat.disableShooting = true
val enStrat = EmptyStrategy(this)
val simTickCount = (1 * tickK).toInt()
for (tick in 0..simTickCount) {
predictStratMoves(myStrat, sim, tick, true, simGame)
predictStratMoves(enStrat, sim, tick, false, simGame)
if (tick < simTickCount) {
sim.microTicks = game.properties.updatesPerTick / 5
} else {
sim.microTicks = (game.properties.updatesPerTick / 7)
}
sim.tick()
simGame.currentTick++
val resultGoal = sim.resultKill
if (resultGoal != null) {
break
}
}
return sim
}
private val stillStrategy = MoveStrategy(MoveLeftRight.STILL, MoveUpDown.STILL)
private fun predictStratMoves(
strat: Strategy,
sim: Simulator,
tick: Int,
isMe: Boolean,
simGame: Game
) {
val anotherMe = getAnotherUnit()
val empty = EmptyStrategy(this)
simGame.units.forEach { unit ->
if ((isMe && unit.playerId == me.playerId) || (!isMe && unit.playerId != me.playerId)) {
//val unitcopy = unit.copy()
var action: UnitAction? = null
val timePassed = System.currentTimeMillis() - timeStart
if (timePassed > 800) {
action = empty.getAction(unit, game, debug)
} else if (anotherMe?.id == unit.id) {
//use saved strat to calc teammate
if (game.currentTick == savedStrat.savedAt && unit.id == savedStrat.forUnitId) {
savedStrat.strat.isReal = false
action = savedStrat.strat.getAction(unit, simGame, debug)
savedStrat.strat.isReal = true
} else {
val delta = anotherMe.position.copy().minus(me.position).abs()
if (delta.x < 1.5 && delta.y < 2) {
action = stillStrategy.getAction(unit, simGame, debug)
}
}
}
if (action == null) {
action = strat.getAction(unit, simGame, debug)
}
unit.simAction = action
}
}
}
private fun printMap(action: UnitAction) {
d {
for (unit in game.units) {
if (unit.isMy() && unit != me) {
continue
}
var msg = unit.id.toString()
if (unit == me) {
msg += action.shoot.then { "*" } ?: ""
}
debug.text(msg, unit.position, ColorFloat.TEXT_ID)
unit.weapon?.fireTimer?.let {
debug.text(
it.f() + " " + unit.weapon!!.magazine,
unit.position.copy().minus(0.0, 1.0),
ColorFloat.GRAY
)
val x = unit.position.x - unit.size.x / 2
val y = unit.position.y - 1
debug.rect(x, y, x + 0.2f, y + it, ColorFloat.RELOAD)
}
}
@Suppress("NullableBooleanElvis")
//print map
if (getAnotherUnit()?.let { it.id < me.id } ?: true && false) {
me.position.pathDist(Point2D(0, 0))
Path.cachedAccess.getFastNoRound(me.position)?.let { access ->
access.fori { x, y, v ->
if (v > 120) {
return@fori
}
debug.text("$v", Point2D(x, y), ColorFloat.ACCESS, 18f, alignment = TextAlignment.LEFT)
}
}
}
//print passable
val clossestEnemyPos = getClosestEnemy()?.position
if (getAnotherUnit()?.let { it.id < me.id } ?: true && true && clossestEnemyPos != null && false) {
Path.getNextMoveTarget(me.position, clossestEnemyPos, 0)
Path.cachedAccessMove.get(clossestEnemyPos)?.let { access ->
access.fori { x, y, v ->
if (v > 120) {
return@fori
}
debug.text("$v", Point2D(x, y), ColorFloat.ACCESS, 18f, alignment = TextAlignment.LEFT)
}
}
}
//print map
if (getAnotherUnit()?.let { it.id < me.id } ?: true && false) {
Potential.potential.fori { x, y, v ->
if (v < 0.1) {
return@fori
}
debug.text("${v.f1()}", Point2D(x, y), ColorFloat.POTENTIAL, 13f, TextAlignment.LEFT)
}
}
}
}
private val simColors = arrayOf(
ColorFloat(1f, 0.4f, 0.4f, 0.4f),
ColorFloat(0.4f, 1f, 0.4f, 0.4f),
ColorFloat(0.4f, 0.4f, 1f, 0.4f),
ColorFloat(0.4f, 1f, 1f, 0.4f),
ColorFloat(1f, 1f, 0.4f, 0.4f)
)
private inline fun printAction(action: UnitAction) {
if (!isReal) {
return
}
log {
"final act: onGround=${me.onGround} onLadder=${me.onLadder} " +
"jumpstate=${me.jumpState.description()} \naction:$action took ${timeEnd - timeStart}ms"
}
}
fun Point2D.toUnitCenter(): Point2D {
return copy().plus(0.0, game.properties.unitSize.y / 2)
}
}