-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.cpp
More file actions
430 lines (357 loc) · 15.6 KB
/
Copy pathMain.cpp
File metadata and controls
430 lines (357 loc) · 15.6 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
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
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
#include <algorithm>
#include <fstream>
#include <cstdlib>
#include "AI.h"
#include "Evolution.h"
#include "snake.h"
#include "food.h"
#include "HitCheck.h"
#include "Observe.h"
float SCREEN_WIDTH = 625.0f;
float SCREEN_HEIGHT = 625.0f;
int amt = 0;
extern const int GRID_SIZE = 25;
float wallthickness = GRID_SIZE / 2.0f;
extern const float CELL_SIZE = (SCREEN_WIDTH - 2.0f * wallthickness) / GRID_SIZE;
bool gameOver = false;
bool specialmessage = false;
bool ContinueGame = true;
bool AIMODE = true;
// Simulation parameters
const int MAX_STEPS = 10000; //Mostly legacy, kept just in case it decides to wander forever
const int THREADS = 20;
const int GENERATIONS = 300;
// Fitness evaluation function (runs headless)
double evaluateFitness(const std::vector<double>& genome, int gridSize)
{
Snake snake;
Food food;
sf::Vector2i appleXY = food.apple(snake);
int steps = 0;
int stepsSinceLastFood = 0;
int foodEaten = 0;
bool gameOver = false;
while (!gameOver && steps < MAX_STEPS) {
// Get sensor inputs
std::vector<double> inputs = AI::getSensorInputs(snake, appleXY, gridSize);
// Run neural network
std::vector<double> outputs = AI::forward(inputs, genome);
// Get direction decision
sf::Vector2i newDir = AI::getDirection(outputs, snake);
snake.SetDirection(newDir.x, newDir.y);
// Move snake
snake.move();
steps++;
stepsSinceLastFood++;
// Check wall collision
if (DidItHitWall(snake)) {
gameOver = true;
break;
}
// Check self collision
if (snake.checkSelfCollision()) {
gameOver = true;
break;
}
// Check if ate food
sf::Vector2i head = snake.body.back();
if (head.x == appleXY.x && head.y == appleXY.y) {
snake.grow();
foodEaten++;
stepsSinceLastFood = 0;
appleXY = food.apple(snake);
}
// Timeout if stuck wandering
if (stepsSinceLastFood > 100) {
gameOver = true;
break;
}
}
// Fitness function: heavily reward food, reward survival, penalize wandering
double fitness = (foodEaten);
return fitness;
}
// Thread worker function
void evaluateIndividuals(std::vector<Individual>& individuals, int start, int end, int gridSize, std::mutex& mtx)
{
for (int i = start; i < end; i++) {
double fitness = evaluateFitness(individuals[i].genome, gridSize);
// Thread-safe update
std::lock_guard<std::mutex> lock(mtx);
individuals[i].fitness = fitness;
}
}
// Run a single experiment with given config, returns the best individual
Individual runExperiment(EvolutionConfig config, int experimentNum, int totalExperiments)
{
std::cout << "\n========================================" << std::endl;
std::cout << "EXPERIMENT " << experimentNum << " / " << totalExperiments << std::endl;
std::cout << "========================================" << std::endl;
std::cout << "Population: " << config.populationSize << std::endl;
std::cout << "Parents (μ): " << config.numParents << std::endl;
std::cout << "Offspring (λ): " << config.numOffspring << std::endl;
std::cout << "Crossover rate: " << config.crossoverRate << std::endl;
std::cout << "Tau global: " << config.tauGlobal << std::endl;
std::cout << "Tau local: " << config.tauLocal << std::endl;
std::cout << "========================================\n" << std::endl;
Evolution evolution(config);
evolution.initializePopulation();
std::mutex mtx;
for (int gen = 0; gen < GENERATIONS; gen++) {
// Get population
std::vector<Individual>& population = evolution.getPopulation();
// Evaluate fitness using multiple threads
std::vector<std::thread> threads;
int individualsPerThread = config.populationSize / THREADS;
for (int t = 0; t < THREADS; t++) {
int start = t * individualsPerThread;
int end = (t == THREADS - 1) ? config.populationSize : (t + 1) * individualsPerThread;
threads.emplace_back(evaluateIndividuals, std::ref(population), start, end, GRID_SIZE, std::ref(mtx));
}
// Wait for all threads to complete
for (auto& thread : threads) {
thread.join();
}
// Update all-time best tracker
evolution.updateAllTimeBest();
// Log generation stats to file
evolution.logGeneration();
// Get statistics
Individual best = evolution.getBest();
double avgFitness = 0.0;
// double avgSigma = 0.0;
for (const auto& ind : population) {
avgFitness += ind.fitness;
// Calculate average sigma across all genes for this individual
// for (double s : ind.sigmas) {
// avgSigma += s;
// }
}
avgFitness /= config.populationSize;
// avgSigma /= (config.populationSize * GENOME_SIZE); // Average of all sigmas across all individuals
// Print progress
Individual allTimeBest = evolution.getAllTimeBest();
std::cout << "Generation " << gen + 1
<< " | Best: " << best.fitness
<< " | Avg Fitness: " << avgFitness
// << " | Average Sigma: " << avgSigma
<< " | All-Time Best: " << allTimeBest.fitness << '\n';
// // Check for population collapse and inject diversity if needed
// if (best.fitness < 0) {
// std::cout << "*** WARNING: Population collapse detected! Injecting diversity... ***" << std::endl;
//
// std::sort(population.begin(), population.end(),
// [](const Individual& a, const Individual& b) {
// return a.fitness > b.fitness;
// });
//
// int keepTop = config.populationSize / 10; // Keep top 10%
// for (int i = keepTop; i < config.populationSize; i++) {
// // Reinitialize genome
// for (int j = 0; j < GENOME_SIZE; j++) {
// population[i].genome[j] = (rand() / (double)RAND_MAX) * 2.0 - 1.0;
// }
// // Reinitialize ALL sigmas (per-gene sigmas!)
// for (int j = 0; j < GENOME_SIZE; j++) {
// population[i].sigmas[j] = 0.5 + (rand() / (double)RAND_MAX); // sigmas[j] not sigma
// }
// population[i].fitness = 0.0;
// }
// }
// Evolve to next generation
evolution.evolve();
}
Individual allTimeBest = evolution.getAllTimeBest();
std::cout << "\nExperiment " << experimentNum << " complete. All-time best: " << allTimeBest.fitness << std::endl;
return allTimeBest;
}
int main()
{
// Menu system
std::cout << "=== Snake AI Experiments ===" << std::endl;
std::cout << "Press 0 to RUN EXPERIMENTS" << std::endl;
std::cout << "Press 1 to OBSERVE best snake" << std::endl;
std::cout << "Your choice: ";
int choice;
std::cin >> choice;
std::cin.ignore();
std::cout << std::endl;
if (choice == 1) {
// OBSERVE MODE
std::cout << "=== Observation Mode ===" << std::endl;
std::cout << "Loading best genome from file..." << std::endl;
std::vector<double> bestGenome;
std::ifstream file("Best Snake Final.txt");
if (!file.is_open()) {
std::cerr << "Error: Could not load 'Best Snake Final.txt'" << std::endl;
std::cerr << "Please run experiments first." << std::endl;
return 1;
}
double gene;
while (file >> gene) {
bestGenome.push_back(gene);
}
file.close();
std::cout << "Genome loaded successfully!" << std::endl;
std::cout << "Starting observation..." << std::endl;
Observe observer(bestGenome);
observer.Run();
return 0;
}
else if (choice != 0) {
std::cout << "Invalid choice. Please restart and select 0 or 1." << std::endl;
return 1;
}
// EXPERIMENT MODE
std::cout << "=== Snake AI Parameter Experiments ===" << std::endl;
std::cout << "This will run 12 experiments testing:" << std::endl;
std::cout << " - populationSize: [200, 500, 700]" << std::endl;
std::cout << " - crossoverRate: [0, 0.5, 0.8]" << std::endl;
std::cout << " - tauGlobal: [0.5, 1.0, 1.5]" << std::endl;
std::cout << " - eliteCount: [25, 50, 100]" << std::endl;
std::cout << "\nResults will be logged to evolution_log.txt" << std::endl;
std::cout << "\nPress Enter to start experiments...";
std::cin.get();
// ============================================================
// DEFAULT VALUES (used when parameter is held constant)
// ============================================================
const int DEFAULT_POP_SIZE = 500;
const int DEFAULT_NUM_PARENTS = 155;
const int DEFAULT_NUM_OFFSPRING = 995;
const double DEFAULT_CROSSOVER_RATE = 0.1;
const double DEFAULT_TAU_GLOBAL = 1.0;
const double DEFAULT_TAU_LOCAL = 1.0;
// ============================================================
// EXPERIMENT VALUES
// ============================================================
int popSizes[] = {200, 500, 700};
double crossoverRates[] = {0.0, 0.5, 0.8};
double tauGlobalValues[] = {0.5, 1.0, 1.5};
int eliteCounts[] = {25, 50, 100};
int experimentNum = 0;
int totalExperiments = 12;
// Track absolute best across ALL experiments
Individual absoluteBest;
absoluteBest.fitness = -999999.0;
// ============================================================
// EXPERIMENT SET 1: Vary populationSize
// Hold crossoverRate=0.1, tauGlobal=1.0, tauLocal=1.0
// ============================================================
std::cout << "\n\n*** EXPERIMENT SET 1: Varying Population Size ***" << std::endl;
for (int popSize : popSizes) {
experimentNum++;
EvolutionConfig config;
config.populationSize = popSize;
// Scale parents and offspring proportionally
config.numParents = static_cast<int>(popSize * 0.31); // ~31% of pop
config.numOffspring = static_cast<int>(popSize * 1.99); // ~199% of pop
config.eliteCount = 25;
config.crossoverRate = DEFAULT_CROSSOVER_RATE;
config.tauGlobal = DEFAULT_TAU_GLOBAL;
config.tauLocal = DEFAULT_TAU_LOCAL;
config.sigmaMin = 0.02;
config.sigmaMax = 2.0;
config.genomeInitMin = -1.0;
config.genomeInitMax = 1.0;
Individual expBest = runExperiment(config, experimentNum, totalExperiments);
if (expBest.fitness > absoluteBest.fitness) {
absoluteBest = expBest;
std::cout << "*** NEW ABSOLUTE BEST: " << absoluteBest.fitness << " ***" << std::endl;
}
}
// ============================================================
// EXPERIMENT SET 2: Vary crossoverRate
// Hold populationSize=500, tauGlobal=1.0, tauLocal=1.0
// ============================================================
std::cout << "\n\n*** EXPERIMENT SET 2: Varying Crossover Rate ***" << std::endl;
for (double crossRate : crossoverRates) {
experimentNum++;
EvolutionConfig config;
config.populationSize = DEFAULT_POP_SIZE;
config.numParents = DEFAULT_NUM_PARENTS;
config.numOffspring = DEFAULT_NUM_OFFSPRING;
config.eliteCount = 25;
config.crossoverRate = crossRate;
config.tauGlobal = DEFAULT_TAU_GLOBAL;
config.tauLocal = DEFAULT_TAU_LOCAL;
config.sigmaMin = 0.02;
config.sigmaMax = 2.0;
config.genomeInitMin = -1.0;
config.genomeInitMax = 1.0;
Individual expBest = runExperiment(config, experimentNum, totalExperiments);
if (expBest.fitness > absoluteBest.fitness) {
absoluteBest = expBest;
std::cout << "*** NEW ABSOLUTE BEST: " << absoluteBest.fitness << " ***" << std::endl;
}
}
// ============================================================
// EXPERIMENT SET 3: Vary tauGlobal
// Hold populationSize=500, crossoverRate=0.1, tauLocal=1.0
// ============================================================
std::cout << "\n\n*** EXPERIMENT SET 3: Varying Tau Global ***" << std::endl;
for (double tau : tauGlobalValues) {
experimentNum++;
EvolutionConfig config;
config.populationSize = DEFAULT_POP_SIZE;
config.numParents = DEFAULT_NUM_PARENTS;
config.numOffspring = DEFAULT_NUM_OFFSPRING;
config.eliteCount = 25;
config.crossoverRate = DEFAULT_CROSSOVER_RATE;
config.tauGlobal = tau;
config.tauLocal = DEFAULT_TAU_LOCAL;
config.sigmaMin = 0.02;
config.sigmaMax = 2.0;
config.genomeInitMin = -1.0;
config.genomeInitMax = 1.0;
Individual expBest = runExperiment(config, experimentNum, totalExperiments);
if (expBest.fitness > absoluteBest.fitness) {
absoluteBest = expBest;
std::cout << "*** NEW ABSOLUTE BEST: " << absoluteBest.fitness << " ***" << std::endl;
}
}
// ============================================================
// EXPERIMENT SET 4: Vary eliteCount
// Hold populationSize=500, crossoverRate=0.1, tauGlobal=1.0, tauLocal=1.0
// ============================================================
std::cout << "\n\n*** EXPERIMENT SET 4: Varying Elite Count ***" << std::endl;
for (int elite : eliteCounts) {
experimentNum++;
EvolutionConfig config;
config.populationSize = DEFAULT_POP_SIZE;
config.numParents = DEFAULT_NUM_PARENTS;
config.numOffspring = DEFAULT_NUM_OFFSPRING;
config.eliteCount = elite;
config.crossoverRate = DEFAULT_CROSSOVER_RATE;
config.tauGlobal = DEFAULT_TAU_GLOBAL;
config.tauLocal = DEFAULT_TAU_LOCAL;
config.sigmaMin = 0.02;
config.sigmaMax = 2.0;
config.genomeInitMin = -1.0;
config.genomeInitMax = 1.0;
Individual expBest = runExperiment(config, experimentNum, totalExperiments);
if (expBest.fitness > absoluteBest.fitness) {
absoluteBest = expBest;
std::cout << "*** NEW ABSOLUTE BEST: " << absoluteBest.fitness << " ***" << std::endl;
}
}
// ============================================================
// SAVE ABSOLUTE BEST
// ============================================================
std::cout << "\n========================================" << std::endl;
std::cout << "ALL EXPERIMENTS COMPLETE!" << std::endl;
std::cout << "Results saved to evolution_log.txt" << std::endl;
std::cout << "Absolute best fitness: " << absoluteBest.fitness << std::endl;
std::cout << "========================================" << std::endl;
// Save the absolute best genome
std::ofstream bestFile("Best Snake Final.txt");
for (double gene : absoluteBest.genome) {
bestFile << gene << "\n";
}
bestFile.close();
std::cout << "Absolute best genome saved to Best Snake Final.txt" << std::endl;
return 0;
}