-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgold_curr.cpp
1425 lines (1179 loc) · 51.8 KB
/
gold_curr.cpp
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
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include <map>
#include <assert.h>
#include <sstream>
#include <unordered_set>
#include <set>
#include <math.h>
#include <iomanip> // std::setprecision
#include <memory>
using namespace std;
// GLOBAL HELPERS:
template<class T>
T mod(T a, T b) {
T z = a % b;
if (a < 0) {
return z + b;
}
else {
return z;
}
}
template<class K, class V>
auto findValue(std::map<K,V>& someMap, V value) {
auto it1 = someMap.begin();
auto it2 = someMap.end();
while (it1 != it2) {
if (it1->second == value) return it1;
++it1;
}
return it2;
}
template<class K, class V>
auto findValue(std::unordered_map<K,V>& someMap, V value) {
auto it1 = someMap.begin();
auto it2 = someMap.end();
while (it1 != it2) {
if (it1->second == value) return it1;
++it1;
}
return it2;
}
void printGrid(const vector<string>& grid) {
for (auto& s : grid) {
cerr << s << endl;
}
}
class Pacman;
class Tile {
public:
int x=-1, y=-1;
int pelletValue = -1; // -1 means we don't know if pellet exists there. 0 means pellet does not exist for sure. If >0 means pellet exists of that value.
double pelletValueAdjusted = 1.0; // Must be updated each step;
vector<Tile*> neighbours;
bool visible = false;
Pacman* pacOnTile = nullptr; // If there exists any pacman on this tile.
int enemyPacOnTileExpiry = 0;
Tile() {}
Tile(int x, int y) :
x(x), y(y)
{}
double getPelletValueAdjusted() const {
return pelletValueAdjusted;
}
string toStr() const {
stringstream ss;
ss << "(" << x << "," << y << ")" << setprecision(1) << getPelletValueAdjusted() << setprecision(3);
return ss.str();
}
friend ostream& operator<<(ostream& out, const Tile& tile);
};
ostream& operator<<(ostream& out, const Tile& tile) {
out << "Tile: " << "x:" << tile.x << " y:"<< tile.y << " pelletValue:" << tile.pelletValue << " neighbours: ";
for (Tile* neighbour : tile.neighbours) {
out << "(" << neighbour->x << "," << neighbour->y << ") ";
}
return out;
}
using Coord = pair<int, int>; // (x, y) which is equivalent to (col, row). x & y must be positive.
using PacDestinationT = map<Tile*, Pacman*>;
using Path = vector<Tile*>;
using PathsValsT = vector<pair<double, Path>>;
using PacRoutesT = map<Pacman*, Path>;
class Board {
public:
std::map<Coord, Tile> tiles; // Like an adjacency list
int width, height;
set<Tile*> superPelletTiles; // NOTE: These are tiles where Super Pellets WERE present in the beginning of game. The super pellets may not be on the tiles anymore.
int numUnknownPellets; // Must be updated each step.
Board() {}
bool isInBounds(int x, int y) {
if (x >= 0 && x < width && y >=0 && y < height) return true;
return false;
}
void sortTileNeighboursByPelletValues() {
// Sort neighbours of all tiles by their value.
// This will ensure we choose a Super Pellet before normal Pellet during graph search.
for (auto& [coord, tile] : tiles) {
auto& neighbours = tile.neighbours; // reference important.
auto comp = [](const Tile* t1, const Tile* t2) {
return t1->pelletValue > t2->pelletValue;
};
sort(neighbours.begin(), neighbours.end(), comp);
}
}
void updateNumUnknownPellets() {
numUnknownPellets = count_if(tiles.begin(), tiles.end(), [](decltype(tiles)::value_type& element) {
return element.second.pelletValue == -1;
});
}
void updatePelletAdjustValues(int numOpponentAliveInvisiblePacs) {
// If we have N tiles of unknown pellets and m opponent pacmans, then after n game steps,
// the expectated value of an unknown pellet being there is roughly of the form:
// E = (N - m*n) / N
//
// Ideally, n should be number of steps taken by opponent pacmans when they were out of sight.
// Also, this is an optimistic estimate but the optimism should be compensated by the fact that there
// are fake game steps that we can't count.
//
// Since m can change due to pacmans dying, use incremental update:
// E' = E - m/N
// Now, if we make m = number of alive opponent pacs that are not visible in this turn (ideally last turn), then
// this formula is much more accurate.
//
// Also, whenever we see this tile again, we reset it.
for (auto& [_, tile] : tiles) {
if (tile.pelletValue == -1) {
tile.pelletValueAdjusted = tile.pelletValueAdjusted - 1.0*numOpponentAliveInvisiblePacs / numUnknownPellets;
if (tile.pelletValueAdjusted <= 0.0) {
tile.pelletValueAdjusted = 0.1; // Keep a minimum expected value.
}
}
else {
// This resets the values of previously unknown tiles.
tile.pelletValueAdjusted = tile.pelletValue;
}
}
}
};
ostream& operator<<(ostream& out, const Board& board) {
// for (auto& [key, tile] : board.tiles) {
// out << "(" << key.first << "," << key.second << ") : " << tile << endl;
// }
unordered_map<int, char> valMap = {
{-1, '?'},
{0, '0'},
{1, '1'},
{10, '*'},
};
vector<string> grid(board.height, string(board.width, '#'));
for (auto& [key, tile] : board.tiles) {
grid[tile.y][tile.x] = valMap[tile.pelletValue];
}
for (auto& row : grid) {
out << row << endl;
}
return out;
}
class Route {
public:
Path fullPath;
Path pathUptoFirstPellet;
Path additionalPath;
Tile* firstPelletTile = nullptr;
double totalReward = 0;
double additionalPathValue = -9999;
int horizon = -1;
vector<Tile*> superPellets;
vector<Pacman*> enemyPacsOnRoute;
double rewardModifier = 1.0; // This should ideally not be part of this class, but laziness.
Tile* firstStep() {
return fullPath.size() < 1 ? nullptr : fullPath[0];
}
Tile* secondStep() {
return fullPath.size() < 2 ? nullptr : fullPath[1];
}
bool empty() {
return fullPath.empty();
}
bool hasSuperPellets() {
return !superPellets.empty();
}
friend ostream& operator<<(ostream& out, const Route& route);
};
ostream& operator<<(ostream& out, const Route& route) {
out << "Rt:" << setprecision(3) << route.totalReward << " ";
for (auto t : route.fullPath) {
if (t == route.firstPelletTile) out << "[";
if (t->getPelletValueAdjusted() == 10) out << "<";
out << t->toStr();
if (t->getPelletValueAdjusted() == 10) out << ">";
if (t == route.firstPelletTile) out << "]";
out << " ";
}
return out;
}
class Pacman {
public:
int pacId; // pac number (unique within a team)
bool mine; // true if this pac is yours
Tile* pos;
string typeId; // unused in wood leagues
int speedTurnsLeft; // unused in wood leagues
int abilityCooldown; // unused in wood leagues
const Board& board;
bool visible = true; // Can be false for enemy pacs
unordered_map<Tile*, int> distanceToTile;
Route route; // Will change each step.
Pacman(int pacId, int mine, Tile* pos, string typeId, int speedTurnsLeft, int abilityCooldown, const Board& b)
: pacId(pacId), mine(mine), pos(pos), typeId(typeId), speedTurnsLeft(speedTurnsLeft), abilityCooldown(abilityCooldown), board(b)
{}
unordered_set<Tile*> getVisibleTiles() {
unordered_set<Tile*> visibleTiles;
dfs(pos, visibleTiles);
return visibleTiles;
}
bool operator<(const Pacman& other) {
return pacId < other.pacId;
}
bool isSpeedActive() {
return speedTurnsLeft > 0;
}
Tile* getClaimedTile() { // Return the pellet tile claimed by this pac on its boundary of pellets
return route.firstPelletTile;
}
Tile* getMoveDestination() {
if (isSpeedActive()) {
auto ret = route.secondStep();
if (!ret) ret = route.firstStep();
return ret;
}
else {
return route.firstStep();
}
}
Tile* getClosestSuperPellet() {
int minDist = 9999;
Tile* closest = nullptr;
for (auto t : board.superPelletTiles) {
if (t->pelletValue == 10) {
if (distanceToTile[t] < minDist) {
minDist = distanceToTile[t];
closest = t;
}
}
}
return closest;
}
string routeToStr() {
stringstream out;
out << "Rt:" << setprecision(3) << route.totalReward << "";
for (auto t : route.fullPath) {
if (t == getClaimedTile()) out << "[";
if (t == getMoveDestination()) out << "{";
if (t->getPelletValueAdjusted() == 10) out << "<";
if (t->pacOnTile) out << "|";
out << t->toStr();
if (t->pacOnTile) out << "|";
if (t->getPelletValueAdjusted() == 10) out << ">";
if (t == getMoveDestination()) out << "}";
if (t == getClaimedTile()) out << "]";
out << " ";
}
return out.str();
}
private:
void dfs(Tile* tile, unordered_set<Tile*>& visibleTiles) {
if (tile->x == pos->x || tile->y == pos->y) {
visibleTiles.insert(tile);
for (auto n : tile->neighbours) {
if(visibleTiles.count(n) == 0) {
dfs(n, visibleTiles);
}
}
}
}
friend ostream& operator<<(ostream& out, const Pacman& pac);
};
ostream& operator<<(ostream& out, const Pacman& pac) {
out << "Pacman: " << "Id:"<< pac.pacId << " x:"<< pac.pos->x << " y:" << pac.pos->y << " mine:" << pac.mine;
return out;
}
class Game { // Main class, like the Solution class.
public:
int gameSteps = 0;
int myScore;
int opponentScore;
int visiblePacCount; // all your pacs and enemy pacs in sight
map<int, Pacman> myPacs;
map<int, Pacman> theirPacs;
map<int, Pacman> theirVisiblePacs;
map<int, Pacman> myDeadPacs;
map<int, Pacman> theirDeadPacs;
int visiblePelletCount; // all pellets in sight
Board board;
map<string, string> typeWeakAgainst = {
{"ROCK", "SCISSORS"},
{"SCISSORS", "PAPER"},
{"PAPER", "ROCK"}
};
map<string, string> typeStrongAgainst = {
{"ROCK", "PAPER"},
{"SCISSORS", "ROCK"},
{"PAPER", "SCISSORS"}
};
map<Pacman*, unordered_map<Tile*, int>> pacDistances; // Flood-fill distances from each pac in each step.
Game() {}
void buildBoard(vector<string>& grid) {
board.height = grid.size();
board.width = grid[0].size();
// Add Nodes to graph
for (int y = 0; y < board.height; y++) {
for (int x = 0; x < board.width; x++) {
if (grid[y][x] == ' ') {
board.tiles[{x, y}] = Tile(x, y);
}
}
}
// Connect the tiles/nodes:
for (int y = 0; y < board.height; y++) {
for (int x = 0; x < board.width; x++) {
if (grid[y][x] == ' ') {
assert(board.tiles.find({x,y}) != board.tiles.end());
vector<int> nx = {x+1, x-1, x, x};
vector<int> ny = {y, y, y+1, y-1};
// E, W, S, N
for (int i = 0; i < nx.size(); i++) {
int adjX = nx[i];
int adjY = ny[i];
adjX = mod(adjX, board.width);
adjY = mod(adjY, board.height);
if (board.isInBounds(adjX, adjY) && grid[adjY][adjX] == ' ') {
assert(board.tiles.find({adjX,adjY}) != board.tiles.end());
board.tiles.at({x,y}).neighbours.push_back(&board.tiles.at({adjX, adjY}));
}
}
}
}
}
}
// Runs before input.
void resetPacs() {
for (auto& [id, pac] : myPacs) {
pac.pos->pacOnTile = nullptr;
}
for (auto& [id, pac] : theirPacs) {
pac.visible = false; // reset for new input.
}
}
// Runs after input.
void updateVisiblePacsList() {
theirVisiblePacs.clear();
for (auto& [id, pac] : theirPacs) {
if (pac.visible) {
theirVisiblePacs.emplace(id, pac);
}
}
}
/// Marks pellets for all tiles to be unknown (-1) except for the ones that are known to be gone (0).
/// This function must be run BEFORE receiving input of visible pellets.
void clearPellets() {
for (auto& [_, tile] : board.tiles) {
if(tile.pelletValue != 0) {
tile.pelletValue = -1;
}
}
}
/// For all Visible Tiles, if there is no pellet input received (-1), mark pelletValue=0 i.e. gone for sure.
/// This function must be run AFTER receiving input of visible pellets.
/// Do similar thing for Super Pellet Tiles.
void updateGonePellets() {
for(auto& [id, pac] : myPacs) {
auto visibleTiles = pac.getVisibleTiles();
for (Tile* tile : visibleTiles) {
if (tile->pelletValue == -1) {
tile->pelletValue = 0;
}
}
}
for (Tile* tile: board.superPelletTiles) {
if (tile->pelletValue == -1) {
tile->pelletValue = 0;
}
}
}
/// Update ghost pacs on tile. Runs after input.
void updateGhostPacsOnVisibleTiles() {
for(auto& [id, pac] : myPacs) {
auto visibleTiles = pac.getVisibleTiles();
for (Tile* tile : visibleTiles) {
Pacman* pacOnTile = tile->pacOnTile;
if (pacOnTile && !pacOnTile->visible) {
tile->pacOnTile = nullptr;
// pacOnTile->pos; // Leave this as is. It's unused when that pac is not visible anyway.
}
}
}
}
/// Runs after input.
void updateEnemyPacsLastSeenPos() {
for (auto& [id, pac] : theirPacs) {
if (!pac.visible) {
pac.pos->enemyPacOnTileExpiry--;
if (pac.pos->enemyPacOnTileExpiry == 0) {
pac.pos->pacOnTile = nullptr; // Forget the pac from that tile.
}
}
}
}
void updateGonePelletsBasedOnEnemyPacLocation() {
for (auto& [id, pac] : theirPacs) {
if (pac.visible && gameSteps > 0) {
// Count how many of this pac's neighbouring tiles have a pellet for sure.
// They definitely did not come from there.
// If remaining neighbours is only 1, then they came from there. Else we dont know, skip.
vector<Tile*> potentialSources;
for (auto t : pac.pos->neighbours) {
if (t->pelletValue == 1 || t->pelletValue == 10) {
continue;
}
potentialSources.push_back(t);
}
if (potentialSources.size() == 1) {
// They came from here. Trace back from here.
unordered_set<Tile*> visited = {pac.pos, potentialSources[0]};
queue<Tile*> q;
q.push(potentialSources[0]);
int steps = 0;
while(!q.empty() && steps < gameSteps) {
Tile* curr = q.front(); q.pop();
curr->pelletValue = 0;
if (curr->neighbours.size() == 2) {
for (auto& neighbour : curr->neighbours) {
if (visited.count(neighbour) == 0) {
q.push(neighbour);
visited.insert(neighbour);
}
}
}
steps++;
}
}
}
}
}
void estimateTheirDestinations(PacDestinationT& theirPacDestinations) {
for (auto& [id, pac] : theirVisiblePacs) {
bool noPelletNeighbours = all_of(pac.pos->neighbours.begin(), pac.pos->neighbours.end(),
[](Tile* t) {
return t->pelletValue == 0;
});
if (noPelletNeighbours) {
for (Tile* tile : pac.pos->neighbours) {
theirPacDestinations.emplace(tile, &pac);
}
}
else {
for (Tile* tile : pac.pos->neighbours) {
if(tile->pelletValue == 0) continue;
theirPacDestinations.emplace(tile, &pac);
}
}
}
}
void printPacDestinations(PacDestinationT& pacDestinations) {
multimap<Pacman*, Tile*> tempmap;
for (auto [tile, pac] : pacDestinations) {
tempmap.emplace(pac, tile);
}
Pacman* prev = nullptr;
for (auto [pac, tile] : tempmap) {
if (pac != prev) {
cerr << "| " << pac->pacId << ": ";
prev = pac;
}
cerr << "(" << tile->x << "," << tile->y << ") ";
}
cerr << endl;
}
void printPath(const Path& path) {
cerr << "Path:";
for (auto t : path) {
cerr << t->toStr() << " ";
}
}
void floodFillFromPacmansAndCache() {
for (auto& [_, pac] : myPacs) {
queue<Tile*> q;
unordered_map<Tile*, int> discoveredDistances;
q.push(pac.pos);
discoveredDistances.emplace(pac.pos, 0);
while(!q.empty()) {
Tile* currTile = q.front(); q.pop();
for (Tile* n : currTile->neighbours) {
if (discoveredDistances.count(n) == 0) {
discoveredDistances[n] = discoveredDistances.at(currTile) + 1;
q.push(n);
}
}
}
pac.distanceToTile = move(discoveredDistances);
}
}
int calcDistanceBetween(Tile* source, Tile* dest) {
queue<Tile*> q;
unordered_map<Tile*, int> discoveredDistances;
q.push(source);
discoveredDistances.emplace(source, 0);
while(!q.empty()) {
Tile* currTile = q.front(); q.pop();
if (currTile == dest) {
return discoveredDistances.at(currTile);
}
for (Tile* n : currTile->neighbours) {
if (discoveredDistances.count(n) == 0) {
discoveredDistances[n] = discoveredDistances.at(currTile) + 1;
q.push(n);
}
}
}
}
Pacman* tileClaimedByPac(Tile* tile) {
for (auto& [_, pac] : myPacs) {
if (tile == pac.getClaimedTile()) {
return &pac;
}
}
return nullptr;
}
bool isAnyPacsFirstStep(Tile* tile) {
for (auto& [_, pac] : myPacs) {
if (tile == pac.route.firstStep()) {
return true;
}
}
return false;
}
void step() {
stringstream cmd;
PacDestinationT myPacDestinations;
PacDestinationT theirPacDestinations;
// Estimate Opponent Destinations:
estimateTheirDestinations(theirPacDestinations);
cerr << "OppDests: ";
printPacDestinations(theirPacDestinations);
// Calculate distance to all tiles from each Pacman:
floodFillFromPacmansAndCache();
// Clear all Pac Routes:
for (auto& [id, pac] : myPacs) {
pac.route = Route();
}
for (auto& [id, pac] : myPacs) {
cerr << "Pac" << id << ". Pos: " << pac.pos->x << "," << pac.pos->y << " STL: " << pac.speedTurnsLeft << " AC: " << pac.abilityCooldown << endl;
auto switchCommand = step_switch(pac);
if (switchCommand) {
addCmd(cmd, *switchCommand);
}
else {
auto speedCommand = step_speedUp(pac);
if (speedCommand) {
addCmd(cmd, *speedCommand);
}
else {
auto moveCommand = step_move(pac, myPacDestinations, theirPacDestinations);
if (moveCommand) {
addCmd(cmd, *moveCommand);
}
}
}
}
// Output the final command:
// cerr << cmd.str() << endl; cerr.flush();
cout << cmd.str() << endl;
gameSteps++;
}
optional<string> step_switch(Pacman& myPac) {
//cerr << " Step switch check for Pac" << myPac.pacId << endl;
int thresholdForSwitch = 3;
if (!theirVisiblePacs.empty() && myPac.abilityCooldown == 0) {
using DistT = pair<int, Pacman*>; // <dist, theirpac>
priority_queue<DistT, vector<DistT>, std::greater<DistT>> distances;
for (auto& [theirId, theirPac] : theirVisiblePacs) {
int dist = myPac.distanceToTile[theirPac.pos];
distances.push({dist, &theirPac});
// cerr << " Dist to theirPac" << theirPac.pacId << ": "<< dist << endl;
}
auto& closest = distances.top();
if (closest.first <= thresholdForSwitch) {
// Should switch if not already stronger type.
Pacman* theirPac = closest.second;
string toType = typeStrongAgainst.at(theirPac->typeId);
if (myPac.typeId != toType) {
cerr << " Switching Pac" << myPac.pacId << " to " << toType << endl;
stringstream cmd;
cmd << "SWITCH " << myPac.pacId << " " << toType; // SWITCH pacId pacType
return cmd.str();
}
}
}
return nullopt;
}
optional<string> step_speedUp(Pacman& myPac) {
// Speed Up only if:
// - Opponents are more than threshold tiles away
// - or if within threshold, then if they are weak to my type
//cerr << " Step Speed check for Pac" << myPac.pacId << endl;
int thresholdForSpeed = 3;
if(myPac.abilityCooldown == 0 && myPac.speedTurnsLeft == 0) {
using DistT = pair<int, Pacman*>; // <dist, theirpac>
priority_queue<DistT, vector<DistT>, std::greater<DistT>> distances;
for (auto& [theirId, theirPac] : theirVisiblePacs) {
int dist = myPac.distanceToTile[theirPac.pos];
distances.push({dist, &theirPac});
// cerr << " Dist to theirPac" << theirPac.pacId << ": "<< dist << endl;
}
// If any of the close opponent pacmans are strong against me, then dont speed up.
if(!distances.empty()) {
auto closest = distances.top();
int closestDist = closest.first;
Pacman* closestPac = closest.second;
while (closestDist <= thresholdForSpeed && !distances.empty()) {
closest = distances.top(); distances.pop();
closestDist = closest.first;
closestPac = closest.second;
if (typeStrongAgainst.at(myPac.typeId) == closestPac->typeId) {
// Don't speed up.
cerr << " Skip speedup coz oppPac " << closestPac->pacId << " is close." << endl;
return nullopt;
}
}
}
// Else we are safe to speed up:
cerr << " Speeding Pac" << myPac.pacId << endl;
stringstream cmd;
cmd << "SPEED " << myPac.pacId; // SPEED pacId
return cmd.str();
}
return nullopt;
}
optional<string> step_move(Pacman& mypac, PacDestinationT& myPacDestinations, PacDestinationT& theirPacDestinations) {
//cerr << " Step Move check for Pac" << mypac.pacId << endl; cerr.flush();
///------ New Logic: ----///
int N = 20; // Total length of path to have.
// 0. Reset / Clear previous route and other things:
// QUESTION: Should I clear one by one for each pac, or should they be all cleared at once outside this?
// 1. Get path to closest pellet that is not beyond boundary and is not claimed by other mypacs.
vector<Path> paths = pathsToClosestPellets(mypac, theirPacDestinations);
//cerr << " Ran pathsToClosestVisiblePellets. paths.size:" << paths.size() << endl;
// 2. Also get path to closestPotentialPellet. (TODO)
// 3. Also get path to closest Super Pellet.
// 4. Extend each path upto N (or until deadend) if not already >= N. (Convert Path into Route. Route contains more information.)
// 5. Evaluate each routes's total rewards - this is where we'll give incentive to kill or flee if opponent is next to us. Can also make potential pellet values probabilistic.
//cerr << " ";
vector<Route> routes;
for (auto& path : paths) {
vector<Route> routesForThisPath = extendPathIntoRouteOfN(path, N, mypac);
// cerr << "R:"; cerr.flush();
// for_each(routesForThisPath.begin(), routesForThisPath.end(), [this, &mypac](Route& rt) {
// calculateRouteReward3(rt, mypac);
// });
// cerr << route.totalReward << " ";cerr.flush();
routes.insert(routes.end(), routesForThisPath.begin(), routesForThisPath.end());
}
// cerr << "R:"; cerr.flush();
// for_each(routesForThisPath.begin(), routesForThisPath.end(), [this, &mypac](Route& rt) {
// calculateRouteReward3(rt, mypac);
// });
// cerr << route.totalReward << " ";cerr.flush();
// cerr << endl;
// cerr << " Ran extendPathIntoRouteOfN. route.size:" << route.fullPath.size() << endl;
// { // Debugging:
// if(mypac.pacId == 2) {
// // cerr << " Routes: " << routes.size() << " | ";
// // for (auto& route : routes) {
// // cerr << route.totalReward << ", ";
// // }
// // cerr << endl;
// for (auto& route : routes) {
// if (route.hasSuperPellets()) cerr << " " << route << endl;
// }
// for (auto& route : routes) {
// Tile* t = &board.tiles.at({9,3});
// if (find(route.fullPath.begin(), route.fullPath.end(), t) != route.fullPath.end()) {
// cerr << " Rt w/ (9,3):" << route << endl;
// }
// }
// cerr << " ...";
// for (auto& route : routes) {
// cerr << " " << route << endl;
// }
// }
// }
// 6. Pick the best of these routes, and set that as the final route for this pac.
sort(routes.begin(), routes.end(), [](const Route& rt1, const Route& rt2) {
return rt1.totalReward > rt2.totalReward;
});
// pair<double, double> rewardRange = (routes.empty())? {0.0, 0.0} : {routes.front().totalReward, routes.back().totalReward}; // This syntax doesnt work :(
pair<double, double> rewardRange = (routes.empty())? pair<double, double>(0.0, 0.0) : pair<double, double>(routes.front().totalReward, routes.back().totalReward);
cerr << " pathsToClosestPellets: " << paths.size() << " Total Routes: " << routes.size() << " RewardRange: [" << rewardRange.first << ", " << rewardRange.second << "]" << endl;
if (routes.empty()) {
// This can happen when there are more Pacs than pellets remaining towards the end.
// For now just choose the first Pac's claimed pellet.
Tile* pelletTile = nullptr;
for(auto& [otherId, otherPac] : myPacs) {
pelletTile = otherPac.getClaimedTile();
if(pelletTile) {
cerr << " Moving to otherPac" << otherId << "'s destination" << " {[" << pelletTile->x << "," << pelletTile->y << "]} " << endl;
break;
}
}
stringstream cmd;
cmd << "MOVE " << mypac.pacId << " " << pelletTile->x << " " << pelletTile->y;
cmd << " {[" << pelletTile->x << "," << pelletTile->y << "]} ";
return cmd.str();
// TODO: Make this ^ better by creating path & route and then storing the route on pac.
}
if (!routes.empty()) {
// Set this as the final Route
mypac.route = routes[0];
cerr << " " << mypac.routeToStr() << endl;
cerr.flush();
// Move to first tile in route:
Tile* pelletTile = mypac.getClaimedTile();
Tile* dest = mypac.getMoveDestination();
myPacDestinations[dest] = &mypac;
// MOVE <pacId> <x> <y> <extraInfo>
stringstream cmd;
cmd << "MOVE " << mypac.pacId << " " << dest->x << " " << dest->y;
if (pelletTile == dest) {
cmd << " {[" << pelletTile->x << "," << pelletTile->y << "]} ";
}
else {
cmd << " [" << pelletTile->x << "," << pelletTile->y << "] {" << dest->x << "," << dest->y << "}";
}
return cmd.str();
}
else {
cerr << " Couldn't determine destination for Pac: " << mypac.pacId << endl;
return nullopt;
}
}
/// Route to closest pellet (visible or not) by BFS on the graph.
/// If that pellet is claimed by other mypac, then choose another BUT IMP choose one that is on the boundary. (not beyond the first accessible pellet on any path).
/// Goal Criteria: Pellet to this pac; my other pac on a tile is a blocking tile.
vector<Path> pathsToClosestPellets(Pacman& pac, PacDestinationT& theirPacDestinations) {
vector<Path> pathsToAllClosestPellets;
Tile* source = pac.pos;
auto visibleTilesToThisPac = pac.getVisibleTiles();
queue<Tile*> q;
unordered_map<Tile*, Tile*> discoveredBy; // aka visited + parent combined. <child, parent>
unordered_map<Tile*, int> pathLength;
q.push(source);
discoveredBy.emplace(source, nullptr);
pathLength.emplace(source, 0);
while (!q.empty()) {
Tile* currTile = q.front(); q.pop();
if (currTile->pacOnTile) {
Pacman* otherPac = currTile->pacOnTile;
if (otherPac->mine) {
if (otherPac != &pac) {
// Don't go beyond this node if this tile has another Pac of mine on it. only if this tile is close to mypac.
//if (pathLength[currTile] <= 3) {
continue;
//}
}
}
else { // enemy pac
if (pathLength[currTile] == 1 || pathLength[currTile] == 2) {
if (typeWeakAgainst.at(otherPac->typeId) == pac.typeId) { // I'm weak against them. So dont go to/beyond this node.
continue;
}
else if (typeStrongAgainst.at(otherPac->typeId) == pac.typeId) {
// It's fine; we may eat them. nothing to do in this if-case.
// Actually, no. They can transform in that turn and we'll be dead. It depends:
if (otherPac->speedTurnsLeft == 0 && pathLength[currTile] == 1) {
// We can definitely eat them right now
// Include this path.
}
else {
// Even if we can eat them, they will probably get the pellets, so why bother?
continue;
}
}
else if (findValue(theirPacDestinations, otherPac)->first == source) {
continue; // Probable collision.
}
else {
// Probably no collision; so it's probably fine. nothing to do in this if-case.
// Actually Not fine, atleast in this case:
// if (currTile->neighbours.size() == 2) {
continue;
// }
}
// If this is the first step, and if it is also the first step of any other mypacs, then drop this path.
// NOTE: This also equally applicable whether this pac is sped up or other pacs is sped up or both.
if (isAnyPacsFirstStep(currTile)) {
continue;
}
}
else if (pathLength[currTile] <= 5) {
continue;
}
}
}
// GOAL:
if(currTile->getPelletValueAdjusted() > 0 && tileClaimedByPac(currTile) == nullptr) {
Path path;
while (currTile != source) {
path.push_back(currTile);
currTile = discoveredBy.at(currTile);
}
reverse(path.begin(), path.end());
pathsToAllClosestPellets.push_back(move(path));
}
// Only add neighbours of tiles without pellets. This ensures that we don't go beyond the boundary of first pellets.
if (currTile->pelletValue == 0) {
for (Tile* neighbour : currTile->neighbours) {
if (discoveredBy.count(neighbour)==0) {
pathLength[neighbour] = pathLength.at(currTile) + 1;
discoveredBy.emplace(neighbour, currTile);
q.push(neighbour);
}
}
}
}
return pathsToAllClosestPellets;
}
/// Extend given path upto total N nodes by using BFS from the end of given path.
/// Select best path beyond end of given path some reward system accumulated value in M nodes. Use discounted rewards.
/// Goal Criteria: m additional steps or dead end.
vector<Route> extendPathIntoRouteOfN(const Path& startingPath, int N, Pacman& mypac) {
vector<Route> routes;
if (startingPath.empty()) return routes;
int M = N - startingPath.size(); // M tiles more to add to the path beyond firstPelletTile.