Add neat arena
This commit is contained in:
@@ -7,7 +7,6 @@ import Tips from './Tips';
|
||||
import BestSnakeDisplay from './BestSnakeDisplay';
|
||||
import {
|
||||
createPopulation,
|
||||
type Population,
|
||||
} from '../../lib/snakeAI/evolution';
|
||||
import type { EvolutionConfig } from '../../lib/snakeAI/types';
|
||||
import './SnakeAI.css';
|
||||
@@ -20,7 +19,8 @@ const DEFAULT_CONFIG: EvolutionConfig = {
|
||||
maxGameSteps: 20000,
|
||||
};
|
||||
|
||||
import EvolutionWorker from '../../lib/snakeAI/evolution.worker?worker';
|
||||
import { WorkerPool } from '../../lib/snakeAI/workerPool';
|
||||
import { evolveGeneration, updateBestStats, type Population } from '../../lib/snakeAI/evolution';
|
||||
|
||||
export default function SnakeAI() {
|
||||
const [population, setPopulation] = useState<Population>(() =>
|
||||
@@ -42,73 +42,64 @@ export default function SnakeAI() {
|
||||
const lastUpdateRef = useRef<number>(0);
|
||||
|
||||
// Compute derived values for display
|
||||
// If we have stats from the last generation, use them. Otherwise default to 0.
|
||||
const currentBestFitness = population.lastGenerationStats?.bestFitness || 0;
|
||||
const currentAverageFitness = population.lastGenerationStats?.averageFitness || 0;
|
||||
|
||||
const workerRef = useRef<Worker | null>(null);
|
||||
const workerPoolRef = useRef<WorkerPool | null>(null);
|
||||
const isProcessingRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
workerRef.current = new EvolutionWorker();
|
||||
workerRef.current.onmessage = (e) => {
|
||||
const { type, payload } = e.data; // payload is the NEW population
|
||||
if (type === 'SUCCESS') {
|
||||
// Critical: Update ref immediately to prevent race condition with next animation frame
|
||||
populationRef.current = payload;
|
||||
setPopulation(payload);
|
||||
|
||||
// Update history if we have stats
|
||||
if (payload.lastGenerationStats) {
|
||||
setFitnessHistory(prev => {
|
||||
const newEntry = {
|
||||
generation: payload.generation - 1, // The stats are for the gen that just finished
|
||||
best: payload.lastGenerationStats!.bestFitness,
|
||||
average: payload.lastGenerationStats!.averageFitness
|
||||
};
|
||||
// Keep last 100 generations to avoid memory issues if running for eternity
|
||||
const newHistory = [...prev, newEntry];
|
||||
if (newHistory.length > 100) return newHistory.slice(newHistory.length - 100);
|
||||
return newHistory;
|
||||
});
|
||||
}
|
||||
|
||||
isProcessingRef.current = false;
|
||||
} else {
|
||||
console.error("Worker error:", payload);
|
||||
isProcessingRef.current = false;
|
||||
}
|
||||
};
|
||||
// Initialize Worker Pool with logical cores (default)
|
||||
workerPoolRef.current = new WorkerPool();
|
||||
|
||||
return () => {
|
||||
workerRef.current?.terminate();
|
||||
workerPoolRef.current?.terminate();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const runGeneration = useCallback((generations: number = 1) => {
|
||||
if (isProcessingRef.current || !workerRef.current) return;
|
||||
const runGeneration = useCallback(async (generations: number = 1) => {
|
||||
if (isProcessingRef.current || !workerPoolRef.current) return;
|
||||
|
||||
isProcessingRef.current = true;
|
||||
// We need to send the *current* population.
|
||||
// Since this is inside a callback, we need to be careful about closure staleness.
|
||||
// However, we can't easily access the "latest" state inside a callback without refs or dependency.
|
||||
// But 'population' is in the dependency array of the effect calling this? No.
|
||||
// The animate loop calls this.
|
||||
let currentPop = populationRef.current;
|
||||
|
||||
// Let's use a functional update approach? No, we need to SEND data.
|
||||
// We will use a ref to track current population for the worker to ensure we always send latest
|
||||
// OR rely on the fact that 'population' is in dependency of runGeneration (it wasn't before).
|
||||
try {
|
||||
for (let i = 0; i < generations; i++) {
|
||||
// 1. Evaluate in parallel
|
||||
let evaluatedPop = await workerPoolRef.current.evaluateParallel(currentPop, config);
|
||||
|
||||
// Wait, 'runGeneration' lines 43-58 previously used setPopulation(prev => ...).
|
||||
// It didn't need 'population' in dependency.
|
||||
// Now we need it.
|
||||
// 1.5 Update Best Stats (Critical for UI)
|
||||
evaluatedPop = updateBestStats(evaluatedPop);
|
||||
|
||||
workerRef.current.postMessage({
|
||||
population: populationRef.current, // Use a ref for latest population
|
||||
config,
|
||||
generations
|
||||
});
|
||||
}, [config]); // populationRef will be handled separately
|
||||
// 2. Evolve on main thread (fast)
|
||||
currentPop = evolveGeneration(evaluatedPop, config);
|
||||
}
|
||||
|
||||
// Update state
|
||||
populationRef.current = currentPop;
|
||||
setPopulation(currentPop);
|
||||
|
||||
// Update history
|
||||
if (currentPop.lastGenerationStats) {
|
||||
setFitnessHistory(prev => {
|
||||
const newEntry = {
|
||||
generation: currentPop.generation - 1,
|
||||
best: currentPop.lastGenerationStats!.bestFitness,
|
||||
average: currentPop.lastGenerationStats!.averageFitness
|
||||
};
|
||||
const newHistory = [...prev, newEntry];
|
||||
if (newHistory.length > 100) return newHistory.slice(newHistory.length - 100);
|
||||
return newHistory;
|
||||
});
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
console.error("Evolution error:", err);
|
||||
setIsRunning(false);
|
||||
} finally {
|
||||
isProcessingRef.current = false;
|
||||
}
|
||||
}, [config]);
|
||||
|
||||
// Update stats when generation changes
|
||||
useEffect(() => {
|
||||
|
||||
Reference in New Issue
Block a user