-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsim.cpp
More file actions
383 lines (327 loc) · 15.1 KB
/
Copy pathsim.cpp
File metadata and controls
383 lines (327 loc) · 15.1 KB
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
// ── sim.cpp — Headless simulator for Snake Byte (CG Winter 2026) ──────────────
// Compiles standalone: g++ -O2 -std=c++17 -pthread -o sim sim.cpp
// Usage:
// ./sim [N_games] [snakes_per_player] [map]
// maps: flat | platforms | mixed (default: mixed)
// e.g.: ./sim 100 2 platforms
#include "bot_core.hpp"
// ─────────────────────────────────────────────────────────────────────────────
// Game engine
// ─────────────────────────────────────────────────────────────────────────────
struct GameState {
int W, H;
bitset<2560> platforms;
bitset<2560> energy;
unordered_map<int,Snake> snakes; // all snakes, id → Snake
int turn = 0;
static const int MAX_TURNS = 200;
static const int ENERGY_SPAWN_INTERVAL = 5;
mt19937 rng;
bool inBounds(int x,int y) const { return x>=0&&x<W&&y>=0&&y<H; }
int totalLen(const vector<int>& ids) const {
int s=0;
for(int id:ids) if(snakes.count(id)&&snakes.at(id).alive) s+=snakes.at(id).length();
return s;
}
};
// Apply one move to a snake inside the game engine (similar to simMove but
// resolves collisions between all snakes simultaneously after moves are chosen)
void engineApplyGravity(Snake& s, const GameState& g) {
if(!s.alive) return;
while(true){
bool sup=false;
for(int c:s.body){
int bx=ex(c),by=ey(c)+1;
if(!g.inBounds(bx,by)){sup=true;break;}
int bc=enc(bx,by);
if(g.platforms[bc]||g.energy[bc]){sup=true;break;}
// Also supported by any other snake body cell
for(auto&[id,sn]:g.snakes)
if(sn.alive&&sn.id!=s.id)
for(int sc2:sn.body) if(sc2==bc){sup=true;break;}
if(sup) break;
}
if(sup) break;
vector<int> nb; bool fo=false;
for(int c:s.body){
int nx=ex(c),ny=ey(c)+1;
if(!g.inBounds(nx,ny)){fo=true;break;}
nb.push_back(enc(nx,ny));
}
if(fo){s.alive=false;return;}
s.body=nb;
}
}
// Resolve one full game turn given a map<id, direction>
void engineStep(GameState& g, const unordered_map<int,int>& dirs) {
// 1. Move each snake
unordered_map<int, int> newHeads; // id → new head pos
for(auto&[id,d]:dirs){
if(!g.snakes.count(id)||!g.snakes[id].alive) continue;
Snake& s=g.snakes[id];
int nx=ex(s.head())+DX[d], ny=ey(s.head())+DY[d];
if(!g.inBounds(nx,ny)){
// OOB — lose a segment
if(s.length()<=3) s.alive=false;
else { s.body.erase(s.body.begin()); }
continue;
}
newHeads[id]=enc(nx,ny);
}
// 2. Detect head→body collisions (head hits someone's non-tail body)
// Build current body cells (excl tails — they'll move away)
bitset<2560> allBodies=g.platforms;
for(auto&[id,s]:g.snakes){
if(!s.alive) continue;
for(int i=0;i<(int)s.body.size()-1;i++) allBodies.set(s.body[i]);
}
for(auto&[id,nh]:newHeads){
Snake& s=g.snakes[id];
if(!s.alive) continue;
if(allBodies[nh]&&!g.energy[nh]){
if(s.length()<=3) s.alive=false;
else { s.body.erase(s.body.begin()); newHeads[id]=-1; }
}
}
// 3. Head→head collisions
unordered_map<int,vector<int>> byPos;
for(auto&[id,nh]:newHeads) if(nh>=0&&g.snakes[id].alive) byPos[nh].push_back(id);
for(auto&[pos,ids]:byPos){
if(ids.size()<2) continue;
// longest survives; ties → both die
int maxLen=0;
for(int id:ids) maxLen=max(maxLen,g.snakes[id].length());
int survivors=0;
for(int id:ids) if(g.snakes[id].length()==maxLen) survivors++;
for(int id:ids){
if(survivors>1||g.snakes[id].length()<maxLen){
if(g.snakes[id].length()<=3) g.snakes[id].alive=false;
else { g.snakes[id].body.erase(g.snakes[id].body.begin()); newHeads[id]=-1; }
}
}
}
// 4. Actually move bodies
for(auto&[id,nh]:newHeads){
if(!g.snakes.count(id)||!g.snakes[id].alive) continue;
if(nh<0) continue;
Snake& s=g.snakes[id];
if(g.energy[nh]){
s.body.insert(s.body.begin(),nh);
g.energy.reset(nh);
} else {
s.body.insert(s.body.begin(),nh);
s.body.pop_back();
}
}
// 5. Apply gravity to all snakes
for(auto&[id,s]:g.snakes) engineApplyGravity(s,g);
// 6. Spawn energy periodically on empty, non-platform cells
if(g.turn%GameState::ENERGY_SPAWN_INTERVAL==0){
uniform_int_distribution<int> rx(0,g.W-1), ry(0,g.H-1);
for(int attempt=0;attempt<20;attempt++){
int x=rx(g.rng),y=ry(g.rng);
int c=enc(x,y);
if(g.platforms[c]||g.energy[c]) continue;
bool occ=false;
for(auto&[id,s]:g.snakes) if(s.alive) for(int b:s.body) if(b==c){occ=true;break;}
if(!occ){g.energy.set(c); break;}
}
}
g.turn++;
}
// ─────────────────────────────────────────────────────────────────────────────
// Map generators
// ─────────────────────────────────────────────────────────────────────────────
enum MapType { MAP_FLAT, MAP_PLATFORMS, MAP_MIXED };
GameState makeGame(int W, int H, int snakesPerPlayer, MapType mapType, mt19937& rng) {
GameState g;
g.W=W; g.H=H; g.rng=rng;
// Border walls
for(int x=0;x<W;x++){
g.platforms.set(enc(x,0));
g.platforms.set(enc(x,H-1));
}
for(int y=0;y<H;y++){
g.platforms.set(enc(0,y));
g.platforms.set(enc(W-1,y));
}
if(mapType==MAP_PLATFORMS||mapType==MAP_MIXED){
// Add a few horizontal platforms
uniform_int_distribution<int> rx(2,W-3), ry(2,H-3), rlen(3,8);
int nPlat=(mapType==MAP_MIXED)?3:6;
for(int i=0;i<nPlat;i++){
int y=ry(rng), x=rx(rng), len=rlen(rng);
for(int dx=0;dx<len&&x+dx<W-1;dx++) g.platforms.set(enc(x+dx,y));
}
}
// Spawn snakes: player 0 on left, player 1 on right
// Each snake starts as 3 cells horizontal on the floor row
auto floorY=[&](int x)->int{
for(int y=H-2;y>=1;y--)
if(!g.platforms[enc(x,y)]&&!g.platforms[enc(x,y+1)]) return y;
return H-2;
};
int idCounter=0;
// Player 0: heads at x = W/2 - 3 - i*4 (counting from center leftward)
// body extends further left, head faces RIGHT (toward center)
for(int i=0;i<snakesPerPlayer;i++){
int hx = W/2 - 2 - i*4; // head x, counts leftward from center
int y = floorY(hx);
Snake s; s.id=idCounter++; s.alive=true;
// head at hx, body: [hx, hx-1, hx-2]
for(int k=0;k<3;k++) s.body.push_back(enc(hx-k,y));
g.snakes[s.id]=s;
}
// Player 1: heads at x = W/2 + 2 + i*4 (counting from center rightward)
// body extends further right, head faces LEFT (toward center)
for(int i=0;i<snakesPerPlayer;i++){
int hx = W/2 + 2 + i*4; // head x, counts rightward from center
int y = floorY(hx);
Snake s; s.id=idCounter++; s.alive=true;
// head at hx, body: [hx, hx+1, hx+2]
for(int k=0;k<3;k++) s.body.push_back(enc(hx+k,y));
g.snakes[s.id]=s;
}
// Scatter initial energy
uniform_int_distribution<int> rx2(1,W-2), ry2(1,H-2);
for(int n=0;n<snakesPerPlayer*4;n++){
for(int attempt=0;attempt<50;attempt++){
int x=rx2(rng),y=ry2(rng);
int c=enc(x,y);
if(g.platforms[c]||g.energy[c]) continue;
g.energy.set(c); break;
}
}
return g;
}
// ─────────────────────────────────────────────────────────────────────────────
// Run one game, return winner (0 or 1, or -1 for draw)
// ─────────────────────────────────────────────────────────────────────────────
struct GameResult {
int winner; // 0, 1, or -1 draw
int len0, len1; // final lengths
int turns;
int energyEaten0, energyEaten1;
};
GameResult runGame(const GameState& initG,
BotState& bs0, BotState& bs1,
const vector<int>& p0ids, const vector<int>& p1ids,
bool verbose=false) {
GameState g=initG;
// Configure bot states
bs0.W=g.W; bs0.H=g.H; bs0.platforms=g.platforms;
bs0.myIds=p0ids; bs0.oppIds=p1ids;
bs0.headHist.clear();
bs1.W=g.W; bs1.H=g.H; bs1.platforms=g.platforms;
bs1.myIds=p1ids; bs1.oppIds=p0ids;
bs1.headHist.clear();
int startLen0=g.totalLen(p0ids);
int startLen1=g.totalLen(p1ids);
while(g.turn < GameState::MAX_TURNS){
// Check if any player still has alive snakes
bool anyAlive0=false, anyAlive1=false;
for(int id:p0ids) if(g.snakes.count(id)&&g.snakes[id].alive) anyAlive0=true;
for(int id:p1ids) if(g.snakes.count(id)&&g.snakes[id].alive) anyAlive1=true;
if(!anyAlive0||!anyAlive1) break;
// Build the view for each bot (all snakes currently alive)
unordered_map<int,Snake> view;
for(auto&[id,s]:g.snakes) if(s.alive) view[id]=s;
// Ask bots for their moves
auto moves0=decideTurn(view, g.energy, bs0, /*silent=*/true);
auto moves1=decideTurn(view, g.energy, bs1, /*silent=*/true);
// Merge moves
unordered_map<int,int> allMoves;
for(auto&[id,d]:moves0) allMoves[id]=d;
for(auto&[id,d]:moves1) allMoves[id]=d;
if(verbose){
cerr<<"Turn "<<g.turn<<" | ";
for(auto&[id,d]:allMoves) cerr<<id<<"→"<<DNAME[d]<<" ";
int e=0; for(int i=0;i<2560;i++) if(g.energy[i]) e++;
cerr<<"| energy="<<e<<"\n";
}
engineStep(g, allMoves);
}
int finalLen0=g.totalLen(p0ids);
int finalLen1=g.totalLen(p1ids);
int winner=-1;
if(finalLen0>finalLen1) winner=0;
else if(finalLen1>finalLen0) winner=1;
return {winner, finalLen0, finalLen1, g.turn,
finalLen0-startLen0, finalLen1-startLen1};
}
// ─────────────────────────────────────────────────────────────────────────────
// Main
// ─────────────────────────────────────────────────────────────────────────────
int main(int argc, char** argv) {
int N = (argc>1) ? atoi(argv[1]) : 50;
int SPP = (argc>2) ? atoi(argv[2]) : 2; // snakes per player
string mapArg = (argc>3) ? argv[3] : "mixed";
MapType mapType = MAP_MIXED;
if(mapArg=="flat") mapType=MAP_FLAT;
if(mapArg=="platforms") mapType=MAP_PLATFORMS;
const int GW=30, GH=18;
cout << "═══════════════════════════════════════════════════════\n";
cout << " Snake Byte Simulator — mirror match (bot vs itself)\n";
cout << " N=" << N << " snakes/player=" << SPP
<< " map=" << mapArg
<< " grid=" << GW << "×" << GH << "\n";
cout << "═══════════════════════════════════════════════════════\n\n";
int wins0=0, wins1=0, draws=0;
long long totalLen0=0, totalLen1=0;
long long totalTurns=0;
int minTurns=INT_MAX, maxTurns=0;
vector<int> len0s, len1s;
mt19937 masterRng(42);
for(int game=0;game<N;game++){
mt19937 gameRng(masterRng());
vector<int> p0ids, p1ids;
for(int i=0;i<SPP;i++) p0ids.push_back(i);
for(int i=0;i<SPP;i++) p1ids.push_back(SPP+i);
GameState g=makeGame(GW,GH,SPP,mapType,gameRng);
BotState bs0, bs1;
auto res=runGame(g, bs0, bs1, p0ids, p1ids, /*verbose=*/false);
if(res.winner==0) wins0++;
else if(res.winner==1) wins1++;
else draws++;
totalLen0+=res.len0; totalLen1+=res.len1;
totalTurns+=res.turns;
minTurns=min(minTurns,res.turns);
maxTurns=max(maxTurns,res.turns);
len0s.push_back(res.len0); len1s.push_back(res.len1);
// Progress every 10 games
if((game+1)%10==0||game==N-1){
int done=game+1;
cerr << "\r " << done << "/" << N << " games...";
cerr.flush();
}
}
cerr << "\n\n";
// Median
sort(len0s.begin(),len0s.end());
sort(len1s.begin(),len1s.end());
double med0=len0s[N/2], med1=len1s[N/2];
cout << "── Results ─────────────────────────────────────────────\n";
cout << " Player 0 wins : " << wins0 << " ("
<< fixed << setprecision(1) << 100.0*wins0/N << "%)\n";
cout << " Player 1 wins : " << wins1 << " ("
<< 100.0*wins1/N << "%)\n";
cout << " Draws : " << draws << " ("
<< 100.0*draws/N << "%)\n\n";
cout << "── Length stats ────────────────────────────────────────\n";
cout << " Avg len P0 : " << fixed << setprecision(1)
<< (double)totalLen0/N << " (median " << med0 << ")\n";
cout << " Avg len P1 : " << (double)totalLen1/N
<< " (median " << med1 << ")\n\n";
cout << "── Turn stats ──────────────────────────────────────────\n";
cout << " Avg turns : " << (double)totalTurns/N << "\n";
cout << " Min/Max : " << minTurns << " / " << maxTurns << "\n\n";
// Mirror match sanity: wins should be ~50/50
double balance=100.0*abs(wins0-wins1)/N;
cout << "── Mirror match balance ────────────────────────────────\n";
if(balance<15)
cout << " ✓ Balanced (" << balance << "% imbalance)\n";
else
cout << " ⚠ Imbalanced (" << balance << "% — positional advantage?)\n";
cout << "═══════════════════════════════════════════════════════\n";
return 0;
}