Initial commit

This commit is contained in:
Peter Stockings
2026-01-10 09:13:28 +11:00
commit 0c53496e9b
49 changed files with 3947 additions and 0 deletions

11
src/App.css Normal file
View File

@@ -0,0 +1,11 @@
.app-layout {
display: flex;
width: 100vw;
height: 100vh;
overflow: hidden;
}
.app-main {
flex: 1;
overflow: hidden;
}

29
src/App.tsx Normal file
View File

@@ -0,0 +1,29 @@
import { useState } from 'react';
import Sidebar, { type AppId } from './components/Sidebar';
import ImageApprox from './apps/ImageApprox/ImageApprox';
import SnakeAI from './apps/SnakeAI/SnakeAI';
import './App.css';
function App() {
const [currentApp, setCurrentApp] = useState<AppId>('image-approx');
const renderApp = () => {
switch (currentApp) {
case 'image-approx':
return <ImageApprox />;
case 'snake-ai':
return <SnakeAI />;
default:
return <div>App not found</div>;
}
};
return (
<div className="app-layout">
<Sidebar currentApp={currentApp} onAppChange={setCurrentApp} />
<main className="app-main">{renderApp()}</main>
</div>
);
}
export default App;

View File

@@ -0,0 +1,161 @@
.controls-panel {
display: flex;
flex-direction: column;
gap: 1.25rem;
}
.control-section {
background: var(--bg-card);
border: 1px solid var(--border-color);
border-radius: 16px;
padding: 1.5rem;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.section-title {
margin: 0 0 1rem;
font-size: 1rem;
font-weight: 600;
color: var(--text-primary);
}
.file-input {
width: 100%;
padding: 0.75rem;
background: rgba(255, 255, 255, 0.05);
border: 1px solid var(--border-color);
border-radius: 8px;
color: var(--text-secondary);
cursor: pointer;
transition: all 0.3s ease;
}
.file-input:hover {
background: rgba(255, 255, 255, 0.08);
border-color: var(--primary-gradient-start);
}
.button-group {
display: flex;
gap: 0.75rem;
}
.control-button {
flex: 1;
padding: 0.875rem 1.5rem;
font-size: 1rem;
font-weight: 600;
border: none;
border-radius: 8px;
cursor: pointer;
transition: all 0.3s ease;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
.control-button.start {
background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
color: white;
}
.control-button.start:hover:not(:disabled) {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(99, 102, 241, 0.4);
}
.control-button.pause {
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
color: white;
}
.control-button.pause:hover:not(:disabled) {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(240, 147, 251, 0.4);
}
.control-button.reset {
background: rgba(255, 255, 255, 0.1);
color: var(--text-primary);
border: 1px solid var(--border-color);
}
.control-button.reset:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.15);
}
.control-button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.slider-control {
display: flex;
flex-direction: column;
gap: 0.5rem;
margin-bottom: 1rem;
}
.slider-control:last-child {
margin-bottom: 0;
}
.slider-label {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 0.875rem;
color: var(--text-secondary);
}
.slider-value {
font-weight: 600;
color: var(--primary-gradient-start);
font-family: 'Courier New', monospace;
}
.slider {
width: 100%;
height: 6px;
border-radius: 3px;
background: rgba(255, 255, 255, 0.1);
outline: none;
-webkit-appearance: none;
appearance: none;
}
.slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 18px;
height: 18px;
border-radius: 50%;
background: linear-gradient(135deg, var(--primary) 0%, var(--accent) 100%);
cursor: pointer;
box-shadow: 0 2px 6px rgba(99, 102, 241, 0.5);
transition: all 0.2s ease;
}
.slider::-webkit-slider-thumb:hover {
transform: scale(1.2);
box-shadow: 0 3px 10px rgba(99, 102, 241, 0.7);
}
.slider::-moz-range-thumb {
width: 18px;
height: 18px;
border-radius: 50%;
background: linear-gradient(135deg, var(--primary) 0%, var(--accent) 100%);
cursor: pointer;
border: none;
box-shadow: 0 2px 6px rgba(99, 102, 241, 0.5);
transition: all 0.2s ease;
}
.slider::-moz-range-thumb:hover {
transform: scale(1.2);
box-shadow: 0 3px 10px rgba(99, 102, 241, 0.7);
}
.slider:disabled {
opacity: 0.5;
cursor: not-allowed;
}

View File

@@ -0,0 +1,140 @@
import './Controls.css';
interface ControlsProps {
isRunning: boolean;
hasTarget: boolean;
mutationStrength: number;
childrenCount: number;
triangleCount: number;
sampleStep: number;
generationsPerFrame: number;
onToggleRunning: () => void;
onReset: () => void;
onMutationStrengthChange: (value: number) => void;
onChildrenCountChange: (value: number) => void;
onTriangleCountChange: (value: number) => void;
onSampleStepChange: (value: number) => void;
onGenerationsPerFrameChange: (value: number) => void;
}
export default function Controls({
isRunning,
hasTarget,
mutationStrength,
childrenCount,
triangleCount,
sampleStep,
generationsPerFrame,
onToggleRunning,
onReset,
onMutationStrengthChange,
onChildrenCountChange,
onTriangleCountChange,
onSampleStepChange,
onGenerationsPerFrameChange,
}: ControlsProps) {
return (
<div className="controls-panel">
<div className="control-section">
<h3 className="section-title">Evolution Controls</h3>
<div className="button-group">
<button
onClick={onToggleRunning}
disabled={!hasTarget}
className={`control-button ${isRunning ? 'pause' : 'start'}`}
>
{isRunning ? '⏸ Pause' : '▶ Start'}
</button>
<button onClick={onReset} disabled={!hasTarget} className="control-button reset">
🔄 Reset
</button>
</div>
</div>
<div className="control-section">
<h3 className="section-title">Parameters</h3>
<div className="slider-control">
<label className="slider-label">
<span>Mutation Strength:</span>
<span className="slider-value">{mutationStrength.toFixed(2)}</span>
</label>
<input
type="range"
min="0.01"
max="1"
step="0.01"
value={mutationStrength}
onChange={(e) => onMutationStrengthChange(parseFloat(e.target.value))}
className="slider"
/>
</div>
<div className="slider-control">
<label className="slider-label">
<span>Children per Gen (λ):</span>
<span className="slider-value">{childrenCount}</span>
</label>
<input
type="range"
min="1"
max="30"
step="1"
value={childrenCount}
onChange={(e) => onChildrenCountChange(parseInt(e.target.value))}
className="slider"
/>
</div>
<div className="slider-control">
<label className="slider-label">
<span>Triangle Count:</span>
<span className="slider-value">{triangleCount}</span>
</label>
<input
type="range"
min="50"
max="200"
step="10"
value={triangleCount}
onChange={(e) => onTriangleCountChange(parseInt(e.target.value))}
className="slider"
disabled={isRunning}
/>
</div>
<div className="slider-control">
<label className="slider-label">
<span>Sample Step:</span>
<span className="slider-value">{sampleStep}px</span>
</label>
<input
type="range"
min="1"
max="8"
step="1"
value={sampleStep}
onChange={(e) => onSampleStepChange(parseInt(e.target.value))}
className="slider"
/>
</div>
<div className="slider-control">
<label className="slider-label">
<span>Speed (Gen/Frame):</span>
<span className="slider-value">{generationsPerFrame}</span>
</label>
<input
type="range"
min="1"
max="100"
step="1"
value={generationsPerFrame}
onChange={(e) => onGenerationsPerFrameChange(parseInt(e.target.value))}
className="slider"
/>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,23 @@
.fitness-chart-container {
background: rgba(255, 255, 255, 0.02);
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 16px;
padding: 1.5rem;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}
.chart-title {
margin: 0 0 1rem;
font-size: 0.875rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--text-secondary);
}
.fitness-chart {
width: 100%;
height: auto;
border-radius: 8px;
background: rgba(0, 0, 0, 0.2);
}

View File

@@ -0,0 +1,152 @@
import { useEffect, useRef } from 'react';
import './FitnessChart.css';
interface FitnessChartProps {
fitnessHistory: number[];
maxPoints?: number;
}
export default function FitnessChart({ fitnessHistory, maxPoints = 500 }: FitnessChartProps) {
const canvasRef = useRef<HTMLCanvasElement>(null);
useEffect(() => {
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
const width = canvas.width;
const height = canvas.height;
// Clear canvas
ctx.fillStyle = '#0f0f1e';
ctx.fillRect(0, 0, width, height);
if (fitnessHistory.length < 2) return;
const maxMSE = 255 * 255 * 3;
// Convert fitness (error) to similarity percentage
const similarityHistory = fitnessHistory.map(fitness =>
Math.max(0, Math.min(100, ((maxMSE - fitness) / maxMSE) * 100))
);
// ALL-TIME scale: fixed 0-100%
const allTimeMin = 0;
const allTimeMax = 100;
const allTimeRange = 100;
// RECENT scale: auto-scaled to recent data
const recentHistory = similarityHistory.slice(-maxPoints);
const recentMin = Math.min(...recentHistory);
const recentMax = Math.max(...recentHistory);
const recentRange = recentMax - recentMin || 1;
// Draw grid lines and left axis (0-100%)
ctx.strokeStyle = 'rgba(255, 255, 255, 0.05)';
ctx.lineWidth = 1;
ctx.fillStyle = 'rgba(255, 255, 255, 0.4)';
ctx.font = '10px Inter, sans-serif';
ctx.textAlign = 'left';
for (let i = 0; i <= 5; i++) {
const y = (height / 5) * i;
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(width, y);
ctx.stroke();
// Left axis labels (0-100%)
const value = allTimeMax - (allTimeRange / 5) * i;
ctx.fillText(value.toFixed(0) + '%', 5, y - 2);
}
// LAYER 1: All-time history (0-100% scale, faded)
const downsampleRate = Math.max(1, Math.floor(similarityHistory.length / 100));
const downsampledHistory = similarityHistory.filter((_, i) => i % downsampleRate === 0);
if (downsampledHistory.length >= 2) {
ctx.strokeStyle = 'rgba(102, 126, 234, 0.2)';
ctx.lineWidth = 1.5;
ctx.beginPath();
downsampledHistory.forEach((similarity, index) => {
const x = (index / (downsampledHistory.length - 1)) * width;
const normalizedSimilarity = (similarity - allTimeMin) / allTimeRange;
const y = height - normalizedSimilarity * height;
if (index === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
});
ctx.stroke();
}
// LAYER 2: Recent progress (auto-scaled, bright)
if (recentHistory.length >= 2) {
ctx.strokeStyle = '#667eea';
ctx.lineWidth = 2.5;
ctx.beginPath();
recentHistory.forEach((similarity, index) => {
const x = (index / (recentHistory.length - 1)) * width;
const normalizedSimilarity = (similarity - recentMin) / recentRange;
const y = height - normalizedSimilarity * height;
if (index === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
});
ctx.stroke();
// Gradient fill under recent line
const gradient = ctx.createLinearGradient(0, 0, 0, height);
gradient.addColorStop(0, 'rgba(102, 126, 234, 0.25)');
gradient.addColorStop(1, 'rgba(102, 126, 234, 0)');
ctx.fillStyle = gradient;
ctx.beginPath();
recentHistory.forEach((similarity, index) => {
const x = (index / (recentHistory.length - 1)) * width;
const normalizedSimilarity = (similarity - recentMin) / recentRange;
const y = height - normalizedSimilarity * height;
if (index === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
});
ctx.lineTo(width, height);
ctx.lineTo(0, height);
ctx.closePath();
ctx.fill();
}
// Right axis labels (recent auto-scale)
ctx.fillStyle = 'rgba(102, 126, 234, 0.7)';
ctx.textAlign = 'right';
for (let i = 0; i <= 5; i++) {
const y = (height / 5) * i;
const value = recentMax - (recentRange / 5) * i;
ctx.fillText(value.toFixed(2) + '%', width - 5, y - 2);
}
}, [fitnessHistory, maxPoints]);
return (
<div className="fitness-chart-container">
<h3 className="chart-title">Similarity Progress</h3>
<canvas ref={canvasRef} width={600} height={200} className="fitness-chart" />
</div>
);
}

View File

@@ -0,0 +1,35 @@
.image-approx-layout {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 2rem;
max-width: 1600px;
margin: 0 auto;
}
.left-panel {
display: flex;
flex-direction: column;
gap: 1.5rem;
}
.right-panel {
display: flex;
flex-direction: column;
gap: 1.5rem;
}
.canvases-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1.5rem;
}
@media (max-width: 1200px) {
.image-approx-layout {
grid-template-columns: 1fr;
}
.canvases-row {
grid-template-columns: 1fr;
}
}

View File

@@ -0,0 +1,283 @@
import { useRef, useState, useEffect, useCallback } from 'react';
import AppContainer from '../../components/AppContainer';
import ImageCanvas from './ImageCanvas';
import Controls from './Controls';
import Stats from './Stats';
import FitnessChart from './FitnessChart';
import Tips from './Tips';
import { createRandomGenome, type Genome } from '../../lib/imageApprox/genome';
import { renderGenome } from '../../lib/imageApprox/renderer';
import { calculateFitness } from '../../lib/imageApprox/fitness';
import { evolve, type EvolutionConfig } from '../../lib/imageApprox/evolution';
import './ImageApprox.css';
const CANVAS_SIZE = 256; // Increased from 128 for better visibility
export default function ImageApprox() {
const targetCanvasRef = useRef<HTMLCanvasElement>(null);
const evolvedCanvasRef = useRef<HTMLCanvasElement>(null);
const offscreenCanvasRef = useRef<HTMLCanvasElement | null>(null);
const animationFrameRef = useRef<number | null>(null);
const [targetImageData, setTargetImageData] = useState<ImageData | null>(null);
const [bestGenome, setBestGenome] = useState<Genome | null>(null);
const [bestFitness, setBestFitness] = useState<number>(Infinity);
const [fitnessHistory, setFitnessHistory] = useState<number[]>([]);
const [generation, setGeneration] = useState<number>(0);
const [isRunning, setIsRunning] = useState<boolean>(false);
// Configuration
const [mutationStrength, setMutationStrength] = useState<number>(0.2);
const [childrenCount, setChildrenCount] = useState<number>(15);
const [triangleCount, setTriangleCount] = useState<number>(100);
const [sampleStep, setSampleStep] = useState<number>(2);
const [generationsPerFrame, setGenerationsPerFrame] = useState<number>(20);
// Initialize offscreen canvas
useEffect(() => {
offscreenCanvasRef.current = document.createElement('canvas');
offscreenCanvasRef.current.width = CANVAS_SIZE;
offscreenCanvasRef.current.height = CANVAS_SIZE;
// Load default image
loadDefaultImage();
}, []);
const loadDefaultImage = () => {
const img = new Image();
img.onload = () => {
const canvas = targetCanvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
// Draw image to target canvas
ctx.drawImage(img, 0, 0, CANVAS_SIZE, CANVAS_SIZE);
const imageData = ctx.getImageData(0, 0, CANVAS_SIZE, CANVAS_SIZE);
setTargetImageData(imageData);
// Initialize genome
const genome = createRandomGenome(CANVAS_SIZE, CANVAS_SIZE, triangleCount);
setBestGenome(genome);
// Calculate initial fitness
const offscreenCanvas = offscreenCanvasRef.current;
if (offscreenCanvas) {
const offscreenCtx = offscreenCanvas.getContext('2d');
if (offscreenCtx) {
renderGenome(offscreenCtx, genome, CANVAS_SIZE, CANVAS_SIZE);
const candidateData = offscreenCtx.getImageData(0, 0, CANVAS_SIZE, CANVAS_SIZE);
const fitness = calculateFitness(imageData, candidateData, sampleStep);
setBestFitness(fitness);
setFitnessHistory([fitness]);
}
}
setGeneration(0);
setIsRunning(false);
};
// Create a simple default image (yellow circle on blue background)
const defaultCanvas = document.createElement('canvas');
defaultCanvas.width = CANVAS_SIZE;
defaultCanvas.height = CANVAS_SIZE;
const defaultCtx = defaultCanvas.getContext('2d');
if (defaultCtx) {
// Blue background
defaultCtx.fillStyle = '#4A90E2';
defaultCtx.fillRect(0, 0, CANVAS_SIZE, CANVAS_SIZE);
// Yellow circle
defaultCtx.fillStyle = '#FFD700';
defaultCtx.beginPath();
defaultCtx.arc(CANVAS_SIZE / 2, CANVAS_SIZE / 2, 40, 0, Math.PI * 2);
defaultCtx.fill();
}
img.src = defaultCanvas.toDataURL();
};
const handleImageUpload = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
const img = new Image();
img.onload = () => {
const canvas = targetCanvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext('2d');
if (!ctx) return;
// Draw image to target canvas
ctx.drawImage(img, 0, 0, CANVAS_SIZE, CANVAS_SIZE);
const imageData = ctx.getImageData(0, 0, CANVAS_SIZE, CANVAS_SIZE);
setTargetImageData(imageData);
// Initialize genome
const genome = createRandomGenome(CANVAS_SIZE, CANVAS_SIZE, triangleCount);
setBestGenome(genome);
// Calculate initial fitness
const offscreenCanvas = offscreenCanvasRef.current;
if (offscreenCanvas) {
const offscreenCtx = offscreenCanvas.getContext('2d');
if (offscreenCtx) {
renderGenome(offscreenCtx, genome, CANVAS_SIZE, CANVAS_SIZE);
const candidateData = offscreenCtx.getImageData(0, 0, CANVAS_SIZE, CANVAS_SIZE);
const fitness = calculateFitness(imageData, candidateData, sampleStep);
setBestFitness(fitness);
setFitnessHistory([fitness]);
}
}
setGeneration(0);
setIsRunning(false);
};
img.src = URL.createObjectURL(file);
}, [triangleCount, sampleStep]);
const handleReset = useCallback(() => {
if (!targetImageData) return;
const genome = createRandomGenome(CANVAS_SIZE, CANVAS_SIZE, triangleCount);
setBestGenome(genome);
// Calculate initial fitness
const offscreenCanvas = offscreenCanvasRef.current;
if (offscreenCanvas) {
const offscreenCtx = offscreenCanvas.getContext('2d');
if (offscreenCtx) {
renderGenome(offscreenCtx, genome, CANVAS_SIZE, CANVAS_SIZE);
const candidateData = offscreenCtx.getImageData(0, 0, CANVAS_SIZE, CANVAS_SIZE);
const fitness = calculateFitness(targetImageData, candidateData, sampleStep);
setBestFitness(fitness);
setFitnessHistory([fitness]);
}
}
setGeneration(0);
setIsRunning(false);
}, [targetImageData, triangleCount, sampleStep]);
// Evolution loop - batched for performance
useEffect(() => {
if (!isRunning || !targetImageData || !bestGenome || !offscreenCanvasRef.current) {
return;
}
const DISPLAY_UPDATE_INTERVAL = 5; // Update display every 5 frames
let frameCount = 0;
const runEvolution = () => {
let currentGenome = bestGenome;
let currentFitness = bestFitness;
// Run multiple generations per frame (user configurable)
for (let i = 0; i < generationsPerFrame; i++) {
const config: EvolutionConfig = {
width: CANVAS_SIZE,
height: CANVAS_SIZE,
mutationStrength,
childrenCount,
sampleStep,
};
const result = evolve(
currentGenome,
currentFitness,
targetImageData,
config,
offscreenCanvasRef.current!
);
currentGenome = result.genome;
currentFitness = result.fitness;
// Update state
setBestGenome(result.genome);
setBestFitness(result.fitness);
// Only keep last 1000 fitness values to prevent memory bloat
setFitnessHistory((prev) => {
const newHistory = [...prev, result.fitness];
return newHistory.length > 1000 ? newHistory.slice(-1000) : newHistory;
});
setGeneration((g) => g + 1);
}
// Only update display canvas periodically, not every generation
frameCount++;
if (frameCount % DISPLAY_UPDATE_INTERVAL === 0) {
const canvas = evolvedCanvasRef.current;
if (canvas) {
const ctx = canvas.getContext('2d', { willReadFrequently: false });
if (ctx) {
renderGenome(ctx, currentGenome, CANVAS_SIZE, CANVAS_SIZE);
}
}
}
animationFrameRef.current = requestAnimationFrame(runEvolution);
};
animationFrameRef.current = requestAnimationFrame(runEvolution);
return () => {
if (animationFrameRef.current !== null) {
cancelAnimationFrame(animationFrameRef.current);
}
};
}, [isRunning, targetImageData, bestGenome, bestFitness, mutationStrength, childrenCount, sampleStep, generationsPerFrame]);
// Initial render of evolved canvas
useEffect(() => {
if (bestGenome && evolvedCanvasRef.current) {
const ctx = evolvedCanvasRef.current.getContext('2d');
if (ctx) {
renderGenome(ctx, bestGenome, CANVAS_SIZE, CANVAS_SIZE);
}
}
}, [bestGenome]);
return (
<AppContainer title="Image Approximation">
<div className="image-approx-layout">
<div className="left-panel">
<Controls
isRunning={isRunning}
hasTarget={targetImageData !== null}
mutationStrength={mutationStrength}
childrenCount={childrenCount}
triangleCount={triangleCount}
sampleStep={sampleStep}
generationsPerFrame={generationsPerFrame}
onToggleRunning={() => setIsRunning(!isRunning)}
onReset={handleReset}
onMutationStrengthChange={setMutationStrength}
onChildrenCountChange={setChildrenCount}
onTriangleCountChange={setTriangleCount}
onSampleStepChange={setSampleStep}
onGenerationsPerFrameChange={setGenerationsPerFrame}
/>
<Tips />
</div>
<div className="right-panel">
<Stats generation={generation} fitness={bestFitness} />
<FitnessChart fitnessHistory={fitnessHistory} />
<div className="canvases-row">
<ImageCanvas
label="Target Image"
canvasRef={targetCanvasRef}
showFileUpload={true}
onImageUpload={handleImageUpload}
/>
<ImageCanvas label="Evolved Image" canvasRef={evolvedCanvasRef} />
</div>
</div>
</div>
</AppContainer>
);
}

View File

@@ -0,0 +1,66 @@
.image-canvas-container {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.canvas-header {
display: flex;
align-items: center;
gap: 0.5rem;
}
.canvas-label {
margin: 0;
font-size: 0.875rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--text-secondary);
flex: 1;
}
.file-input-hidden {
display: none;
}
.upload-icon-button {
display: flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
background: rgba(99, 102, 241, 0.15);
border: 1px solid rgba(99, 102, 241, 0.3);
border-radius: 8px;
font-size: 1rem;
cursor: pointer;
transition: all 0.2s ease;
}
.upload-icon-button:hover {
background: rgba(99, 102, 241, 0.25);
border-color: var(--primary);
transform: scale(1.05);
}
.image-canvas {
display: block;
border-radius: 12px;
background: rgba(0, 0, 0, 0.3);
border: 1px solid var(--border-color);
image-rendering: pixelated;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
width: 256px;
height: 256px;
}
.pixel-canvas {
display: block;
width: 256px;
height: 256px;
image-rendering: pixelated;
image-rendering: -moz-crisp-edges;
image-rendering: crisp-edges;
border-radius: 4px;
}

View File

@@ -0,0 +1,33 @@
import './ImageCanvas.css';
interface ImageCanvasProps {
label: string;
canvasRef: React.RefObject<HTMLCanvasElement | null>;
showFileUpload?: boolean;
onImageUpload?: (e: React.ChangeEvent<HTMLInputElement>) => void;
}
export default function ImageCanvas({ label, canvasRef, showFileUpload, onImageUpload }: ImageCanvasProps) {
return (
<div className="image-canvas-container">
<div className="canvas-header">
<h3 className="canvas-label">{label}</h3>
{showFileUpload && (
<>
<input
type="file"
accept="image/*"
onChange={onImageUpload}
className="file-input-hidden"
id="image-upload"
/>
<label htmlFor="image-upload" className="upload-icon-button" title="Choose Image">
📁
</label>
</>
)}
</div>
<canvas ref={canvasRef} width={256} height={256} className="image-canvas" />
</div>
);
}

View File

@@ -0,0 +1,49 @@
.stats-panel {
background: linear-gradient(135deg, var(--primary) 0%, var(--accent) 100%);
border-radius: 16px;
padding: 1.5rem 2rem;
box-shadow: 0 8px 32px rgba(99, 102, 241, 0.3);
}
.stats-title {
margin: 0 0 1rem;
font-size: 1.125rem;
font-weight: 600;
color: var(--text-primary);
}
.stats-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 2rem;
}
.stat-item {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.stat-item.highlight {
text-align: right;
}
.stat-item:last-child {
border-bottom: none;
}
.stat-label {
font-size: 0.75rem;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.05em;
color: rgba(255, 255, 255, 0.8);
}
.stat-value {
font-size: 2.25rem;
font-weight: 700;
line-height: 1;
color: #fff;
font-family: 'Inter', system-ui, sans-serif;
}

View File

@@ -0,0 +1,29 @@
import './Stats.css';
interface StatsProps {
generation: number;
fitness: number;
}
export default function Stats({ generation, fitness }: StatsProps) {
// Convert fitness (MSE) to similarity percentage
// MSE is mean squared error per pixel, so max possible is 255^2 * 3 (RGB channels)
// Lower fitness = better, so we invert it
const maxMSE = 255 * 255 * 3; // Max error per pixel across RGB
const similarity = Math.max(0, Math.min(100, ((maxMSE - fitness) / maxMSE) * 100));
return (
<div className="stats-panel">
<div className="stats-grid">
<div className="stat-item">
<span className="stat-label">Generation</span>
<span className="stat-value">{generation.toLocaleString()}</span>
</div>
<div className="stat-item highlight">
<span className="stat-label">Similarity</span>
<span className="stat-value">{similarity.toFixed(1)}%</span>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,44 @@
.tips-panel {
background: linear-gradient(135deg, rgba(99, 102, 241, 0.05) 0%, rgba(139, 92, 246, 0.05) 100%);
border: 1px solid rgba(99, 102, 241, 0.2);
border-radius: 16px;
padding: 1.5rem;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
.tips-title {
margin: 0 0 0.75rem;
font-size: 0.95rem;
font-weight: 600;
color: var(--text-primary);
}
.tips-list {
margin: 0;
padding-left: 1.25rem;
list-style: none;
}
.tips-list li {
position: relative;
font-size: 0.8rem;
color: var(--text-secondary);
margin-bottom: 0.5rem;
line-height: 1.4;
}
.tips-list li:before {
content: '→';
position: absolute;
left: -1.25rem;
color: var(--primary);
}
.tips-list li:last-child {
margin-bottom: 0;
}
.tips-list strong {
color: var(--text-primary);
font-weight: 600;
}

View File

@@ -0,0 +1,16 @@
import './Tips.css';
export default function Tips() {
return (
<div className="tips-panel">
<h3 className="tips-title">💡 Tips</h3>
<ul className="tips-list">
<li>Start with simple images (circles, logos) for best results</li>
<li>Increase <strong>Speed slider to 50-100</strong> for max performance!</li>
<li>Increase <strong>Children per Gen</strong> to 20-30 for faster convergence</li>
<li>Visible shapes typically appear after <strong>5k-10k</strong> generations</li>
<li>Lower mutation strength once you see rough shapes forming</li>
</ul>
</div>
);
}

View File

@@ -0,0 +1,33 @@
import SnakeCanvas from './SnakeCanvas';
import type { Network } from '../../lib/snakeAI/network';
interface BestSnakeDisplayProps {
network: Network | null;
gridSize: number;
fitness: number;
}
export default function BestSnakeDisplay({ network, gridSize, fitness }: BestSnakeDisplayProps) {
if (!network) return null;
return (
<div className="best-snake-panel">
<div className="best-header">
<h3>👑 All-Time Best</h3>
<div className="best-stats">
<span className="label">Fitness Record:</span>
<span className="value">{Math.round(fitness)}</span>
</div>
</div>
<div className="best-canvas-wrapper">
<SnakeCanvas
network={network}
gridSize={gridSize}
size="large"
showGrid={true}
showStats={true}
/>
</div>
</div>
);
}

View File

@@ -0,0 +1,86 @@
interface ControlsProps {
isRunning: boolean;
onToggleRunning: () => void;
onReset: () => void;
speed: number;
onSpeedChange: (speed: number) => void;
mutationRate: number;
onMutationRateChange: (rate: number) => void;
populationSize: number;
}
export default function Controls({
isRunning,
onToggleRunning,
onReset,
speed,
onSpeedChange,
mutationRate,
onMutationRateChange,
populationSize,
}: ControlsProps) {
return (
<div className="controls-panel">
<h3>Evolution Controls</h3>
<div className="control-group">
<div className="button-group">
<button
className={`btn ${isRunning ? 'btn-pause' : 'btn-play'}`}
onClick={onToggleRunning}
>
{isRunning ? '⏸ Pause' : '▶ Play'}
</button>
<button className="btn btn-reset" onClick={onReset}>
🔄 Reset
</button>
</div>
</div>
<div className="control-group">
<label htmlFor="speed-slider">
Playback Speed: <strong>{speed}x</strong>
</label>
<input
id="speed-slider"
type="range"
min="1"
max="20"
step="1"
value={speed}
onChange={(e) => onSpeedChange(Number(e.target.value))}
/>
<div className="slider-labels">
<span>Slow</span>
<span>Fast</span>
</div>
</div>
<div className="control-group">
<label htmlFor="mutation-slider">
Mutation Rate: <strong>{(mutationRate * 100).toFixed(0)}%</strong>
</label>
<input
id="mutation-slider"
type="range"
min="0.01"
max="0.5"
step="0.01"
value={mutationRate}
onChange={(e) => onMutationRateChange(Number(e.target.value))}
/>
<div className="slider-labels">
<span>1%</span>
<span>50%</span>
</div>
</div>
<div className="control-info">
<div className="info-row">
<span className="info-label">Population Size:</span>
<span className="info-value">{populationSize}</span>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,476 @@
.snake-ai-layout {
display: grid;
grid-template-columns: 2fr 1fr;
gap: 2rem;
height: 100%;
padding: 1rem;
}
.left-panel,
.right-panel {
display: flex;
flex-direction: column;
gap: 1.5rem;
}
/* Canvas */
.snake-canvas-container {
display: flex;
flex-direction: column;
gap: 1rem;
align-items: center;
}
/* Snake Grid */
.snake-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1rem;
width: 100%;
max-width: 700px;
}
.snake-grid-cell {
position: relative;
background: linear-gradient(135deg, #2a2a3e 0%, #1a1a2e 100%);
border-radius: 8px;
border: 2px solid #3a3a4e;
padding: 0.5rem;
transition: all 0.3s ease;
}
.snake-grid-cell:hover {
transform: scale(1.05);
border-color: #4ecdc4;
box-shadow: 0 4px 12px rgba(78, 205, 196, 0.3);
z-index: 10;
}
.snake-grid-cell.best {
border-color: #4ecdc4;
background: linear-gradient(135deg, rgba(78, 205, 196, 0.15) 0%, #1a1a2e 100%);
box-shadow: 0 0 20px rgba(78, 205, 196, 0.2);
}
.snake-grid-label {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.5rem;
font-size: 0.85rem;
font-weight: 600;
color: #4ecdc4;
}
.snake-grid-cell.best .snake-grid-label {
color: #4ecdc4;
text-shadow: 0 0 10px rgba(78, 205, 196, 0.5);
}
.fitness-badge {
background: #3a3a4e;
padding: 0.2rem 0.5rem;
border-radius: 12px;
font-size: 0.75rem;
color: #fff;
}
.snake-grid-cell.best .fitness-badge {
background: linear-gradient(135deg, #4ecdc4 0%, #44a59d 100%);
}
.snake-grid-cell canvas {
width: 100%;
height: auto;
}
.canvas-info {
display: flex;
gap: 2rem;
padding: 0.75rem 1.5rem;
background: linear-gradient(135deg, #2a2a3e 0%, #1a1a2e 100%);
border-radius: 8px;
border: 1px solid #3a3a4e;
}
.info-item {
display: flex;
gap: 0.5rem;
align-items: baseline;
}
.info-item .label {
color: #888;
font-size: 0.9rem;
}
.info-item .value {
color: #4ecdc4;
font-weight: 600;
font-size: 1.1rem;
}
/* Controls */
.controls-panel {
background: linear-gradient(135deg, #2a2a3e 0%, #1a1a2e 100%);
padding: 1.5rem;
border-radius: 12px;
border: 1px solid #3a3a4e;
}
.controls-panel h3 {
margin: 0 0 1.5rem 0;
color: #fff;
font-size: 1.2rem;
}
.control-group {
margin-bottom: 1.5rem;
}
.control-group:last-child {
margin-bottom: 0;
}
.button-group {
display: flex;
gap: 0.75rem;
}
.btn {
flex: 1;
padding: 0.75rem 1.5rem;
border: none;
border-radius: 8px;
font-size: 1rem;
font-weight: 600;
cursor: pointer;
transition: all 0.2s ease;
font-family: inherit;
}
.btn-play {
background: linear-gradient(135deg, #4ecdc4 0%, #44a59d 100%);
color: #fff;
}
.btn-play:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(78, 205, 196, 0.4);
}
.btn-pause {
background: linear-gradient(135deg, #f39c12 0%, #e67e22 100%);
color: #fff;
}
.btn-pause:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(243, 156, 18, 0.4);
}
.btn-reset {
background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
color: #fff;
}
.btn-reset:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(231, 76, 60, 0.4);
}
.control-group label {
display: block;
margin-bottom: 0.5rem;
color: #ccc;
font-size: 0.95rem;
}
.control-group label strong {
color: #4ecdc4;
}
input[type='range'] {
width: 100%;
height: 6px;
border-radius: 3px;
background: #3a3a4e;
outline: none;
-webkit-appearance: none;
}
input[type='range']::-webkit-slider-thumb {
appearance: none;
-webkit-appearance: none;
width: 18px;
height: 18px;
border-radius: 50%;
background: linear-gradient(135deg, #4ecdc4 0%, #44a59d 100%);
cursor: pointer;
box-shadow: 0 2px 8px rgba(78, 205, 196, 0.4);
transition: all 0.2s ease;
}
input[type='range']::-webkit-slider-thumb:hover {
transform: scale(1.2);
}
input[type='range']::-moz-range-thumb {
width: 18px;
height: 18px;
border-radius: 50%;
background: linear-gradient(135deg, #4ecdc4 0%, #44a59d 100%);
cursor: pointer;
border: none;
box-shadow: 0 2px 8px rgba(78, 205, 196, 0.4);
}
.slider-labels {
display: flex;
justify-content: space-between;
margin-top: 0.25rem;
font-size: 0.8rem;
color: #888;
}
.control-info {
background: #1a1a2e;
padding: 1rem;
border-radius: 8px;
border: 1px solid #3a3a4e;
}
.info-row {
display: flex;
justify-content: space-between;
align-items: center;
}
.info-label {
color: #888;
font-size: 0.9rem;
}
.info-value {
color: #4ecdc4;
font-weight: 600;
font-size: 1.1rem;
}
/* Stats */
.stats-panel {
background: linear-gradient(135deg, #2a2a3e 0%, #1a1a2e 100%);
padding: 1.5rem;
border-radius: 12px;
border: 1px solid #3a3a4e;
}
.stats-panel h3 {
margin: 0 0 1.5rem 0;
color: #fff;
font-size: 1.2rem;
}
.stat-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 1rem;
margin-bottom: 1.5rem;
}
.stat-item {
background: #1a1a2e;
padding: 1rem;
border-radius: 8px;
border: 1px solid #3a3a4e;
text-align: center;
}
.stat-item.highlight {
border-color: #4ecdc4;
background: linear-gradient(135deg, rgba(78, 205, 196, 0.1) 0%, #1a1a2e 100%);
}
.stat-label {
color: #888;
font-size: 0.85rem;
margin-bottom: 0.5rem;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.stat-value {
color: #4ecdc4;
font-size: 1.8rem;
font-weight: 700;
}
.progress-indicator {
background: #1a1a2e;
padding: 1rem;
border-radius: 8px;
border: 1px solid #3a3a4e;
}
.progress-label {
color: #ccc;
font-size: 0.9rem;
margin-bottom: 0.5rem;
}
.progress-bar {
width: 100%;
height: 8px;
background: #3a3a4e;
border-radius: 4px;
overflow: hidden;
}
.progress-fill {
height: 100%;
background: linear-gradient(90deg, #4ecdc4 0%, #44a59d 100%);
transition: width 0.3s ease;
box-shadow: 0 0 10px rgba(78, 205, 196, 0.5);
}
/* Tips */
.tips-panel {
background: linear-gradient(135deg, #2a2a3e 0%, #1a1a2e 100%);
padding: 1.5rem;
border-radius: 12px;
border: 1px solid #3a3a4e;
max-height: 600px;
overflow-y: auto;
}
.tips-panel h3 {
margin: 0 0 1.5rem 0;
color: #fff;
font-size: 1.2rem;
}
.tip-section {
margin-bottom: 1.5rem;
}
.tip-section:last-child {
margin-bottom: 0;
}
.tip-section h4 {
color: #4ecdc4;
font-size: 1rem;
margin: 0 0 0.75rem 0;
}
.tip-section p {
color: #ccc;
line-height: 1.6;
margin: 0 0 0.75rem 0;
}
.tip-section ul,
.tip-section ol {
color: #ccc;
line-height: 1.8;
margin: 0;
padding-left: 1.5rem;
}
.tip-section li {
margin-bottom: 0.5rem;
}
.tip-section strong {
color: #4ecdc4;
font-weight: 600;
}
/* Scrollbar styling for tips panel */
.tips-panel::-webkit-scrollbar {
width: 8px;
}
.tips-panel::-webkit-scrollbar-track {
background: #1a1a2e;
border-radius: 4px;
}
.tips-panel::-webkit-scrollbar-thumb {
background: #3a3a4e;
border-radius: 4px;
}
.tips-panel::-webkit-scrollbar-thumb:hover {
background: #4a4a5e;
}
/* Responsive */
@media (max-width: 1200px) {
.snake-ai-layout {
grid-template-columns: 1fr;
}
.stat-grid {
grid-template-columns: repeat(3, 1fr);
}
}
/* Best Snake Display */
.best-snake-panel {
background: linear-gradient(135deg, #2a2a3e 0%, #1a1a2e 100%);
padding: 1.5rem;
border-radius: 12px;
border: 2px solid #4ecdc4;
box-shadow: 0 0 20px rgba(78, 205, 196, 0.15);
display: flex;
flex-direction: column;
align-items: center;
gap: 1rem;
}
.best-header {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
margin-bottom: 0.5rem;
}
.best-header h3 {
margin: 0;
color: #4ecdc4;
font-size: 1.4rem;
text-shadow: 0 0 10px rgba(78, 205, 196, 0.3);
}
.best-stats {
display: flex;
gap: 0.75rem;
align-items: baseline;
background: rgba(78, 205, 196, 0.1);
padding: 0.5rem 1rem;
border-radius: 20px;
border: 1px solid rgba(78, 205, 196, 0.3);
}
.best-stats .label {
color: #ccc;
font-size: 0.9rem;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.best-stats .value {
color: #fff;
font-weight: 700;
font-size: 1.2rem;
}
.best-canvas-wrapper {
padding: 1rem;
background: #151525;
border-radius: 12px;
border: 1px solid #3a3a4e;
}

View File

@@ -0,0 +1,164 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import AppContainer from '../../components/AppContainer';
import SnakeGrid from './SnakeGrid';
import Controls from './Controls';
import Stats from './Stats';
import Tips from './Tips';
import BestSnakeDisplay from './BestSnakeDisplay';
import {
createPopulation,
evaluatePopulation,
evolveGeneration,
getBestIndividual,
getAverageFitness,
type Population,
} from '../../lib/snakeAI/evolution';
import type { EvolutionConfig } from '../../lib/snakeAI/types';
import './SnakeAI.css';
const DEFAULT_CONFIG: EvolutionConfig = {
populationSize: 25,
mutationRate: 0.1,
eliteCount: 5,
gridSize: 20,
maxGameSteps: 500,
};
export default function SnakeAI() {
const [population, setPopulation] = useState<Population>(() =>
createPopulation(DEFAULT_CONFIG)
);
const [config, setConfig] = useState<EvolutionConfig>(DEFAULT_CONFIG);
const [isRunning, setIsRunning] = useState(false);
const [speed, setSpeed] = useState(5);
const [gamesPlayed, setGamesPlayed] = useState(0);
// Compute derived values from population
const bestIndividual = getBestIndividual(population);
const averageFitness = getAverageFitness(population);
const animationFrameRef = useRef<number>();
const lastUpdateRef = useRef<number>(0);
const runGeneration = useCallback(() => {
setPopulation((prev) => {
try {
// Evaluate current generation
const evaluated = evaluatePopulation(prev, config);
// Evolve to next generation
const nextGen = evolveGeneration(evaluated, config);
return nextGen;
} catch (error) {
console.error("SnakeAI: Generation update failed", error);
return prev;
}
});
}, [config]);
// Update stats when generation changes
useEffect(() => {
if (population.generation > 1) {
setGamesPlayed((count) => count + config.populationSize);
}
}, [population.generation, config.populationSize]);
useEffect(() => {
if (!isRunning) {
if (animationFrameRef.current) {
cancelAnimationFrame(animationFrameRef.current);
}
return;
}
const animate = (timestamp: number) => {
const elapsed = timestamp - lastUpdateRef.current;
// Non-linear speed scaling:
// Speed 1: ~5000ms (5s) per generation - Observation mode
// Speed 5: ~1000ms (1s)
// Speed 20: ~50ms - Turbo training
// Formula: Base delay divided by speed, with a visual observation bias
let updateInterval;
if (speed <= 5) {
// Speeds 1-5: 10s down to 2s
updateInterval = 12000 / speed;
} else {
// Speeds 6-20: Linear fast
updateInterval = 1000 / (speed - 4);
}
if (elapsed >= updateInterval) {
runGeneration();
lastUpdateRef.current = timestamp;
}
animationFrameRef.current = requestAnimationFrame(animate);
};
animationFrameRef.current = requestAnimationFrame(animate);
return () => {
if (animationFrameRef.current) {
cancelAnimationFrame(animationFrameRef.current);
}
};
}, [isRunning, speed, runGeneration]);
const handleReset = () => {
setIsRunning(false);
setPopulation(createPopulation(config));
setGamesPlayed(0);
};
const handleMutationRateChange = (rate: number) => {
setConfig((prev) => ({ ...prev, mutationRate: rate }));
};
return (
<AppContainer title="Neural Network Snake Evolution">
<div className="snake-ai-layout">
<div className="left-panel">
<BestSnakeDisplay
network={population.bestNetworkEver}
gridSize={config.gridSize}
fitness={population.bestFitnessEver}
/>
<SnakeGrid
individuals={population.individuals}
gridSize={config.gridSize}
count={config.populationSize}
columns={5}
/>
</div>
<div className="right-panel">
<Controls
isRunning={isRunning}
onToggleRunning={() => setIsRunning(!isRunning)}
onReset={handleReset}
speed={speed}
onSpeedChange={setSpeed}
mutationRate={config.mutationRate}
onMutationRateChange={handleMutationRateChange}
populationSize={config.populationSize}
/>
<Stats
generation={population.generation}
bestFitness={bestIndividual.fitness}
bestFitnessEver={population.bestFitnessEver}
averageFitness={averageFitness}
gamesPlayed={gamesPlayed}
/>
<Tips />
</div>
</div>
</AppContainer>
);
}

View File

@@ -0,0 +1,196 @@
import { useRef, useEffect, useState } from 'react';
import type { GameState } from '../../lib/snakeAI/game';
import { createGame, step, getInputs } from '../../lib/snakeAI/game';
import { getAction, type Network } from '../../lib/snakeAI/network';
interface SnakeCanvasProps {
network: Network | null;
gridSize: number;
showGrid?: boolean;
size?: 'small' | 'normal' | 'large';
showStats?: boolean; // Show score/length/steps even in small mode
}
const CELL_SIZES = {
small: 8,
normal: 20,
large: 30,
};
const CANVAS_PADDING = 10;
export default function SnakeCanvas({ network, gridSize, showGrid = true, size = 'normal', showStats = false }: SnakeCanvasProps) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const [currentGame, setCurrentGame] = useState<GameState | null>(null);
const animationFrameRef = useRef<number>();
const lastUpdateRef = useRef<number>(0);
const CELL_SIZE = CELL_SIZES[size];
// Initialize game when network or gridSize changes
useEffect(() => {
if (network) {
setCurrentGame(createGame(gridSize));
}
}, [network, gridSize]);
// Animation loop to step through game
useEffect(() => {
if (!network || !currentGame) return;
const STEPS_PER_SECOND = 10; // Speed of game playback
const UPDATE_INTERVAL = 1000 / STEPS_PER_SECOND;
const animate = (timestamp: number) => {
const elapsed = timestamp - lastUpdateRef.current;
if (elapsed >= UPDATE_INTERVAL) {
setCurrentGame((prevGame) => {
if (!prevGame) return prevGame;
// If game is over, start a new one
if (!prevGame.alive) {
return createGame(gridSize);
}
// Get neural network decision
const inputs = getInputs(prevGame);
const action = getAction(network, inputs);
// Step the game forward
return step(prevGame, action);
});
lastUpdateRef.current = timestamp;
}
animationFrameRef.current = requestAnimationFrame(animate);
};
animationFrameRef.current = requestAnimationFrame(animate);
return () => {
if (animationFrameRef.current) {
cancelAnimationFrame(animationFrameRef.current);
}
};
}, [network, currentGame, gridSize]);
// Set canvas size once when props change (not on every render)
useEffect(() => {
if (!canvasRef.current) return;
const canvas = canvasRef.current;
const canvasSize = gridSize * CELL_SIZE + CANVAS_PADDING * 2;
canvas.width = canvasSize;
canvas.height = canvasSize;
}, [gridSize, size]);
// Render game to canvas
useEffect(() => {
if (!currentGame || !canvasRef.current) return;
const canvas = canvasRef.current;
const ctx = canvas.getContext('2d');
if (!ctx) return;
const canvasSize = gridSize * CELL_SIZE + CANVAS_PADDING * 2;
// Clear canvas
ctx.fillStyle = '#1a1a2e';
ctx.fillRect(0, 0, canvasSize, canvasSize);
// Draw grid
if (showGrid) {
ctx.strokeStyle = '#2a2a3e';
ctx.lineWidth = 1;
for (let i = 0; i <= currentGame.gridSize; i++) {
const pos = i * CELL_SIZE + CANVAS_PADDING;
ctx.beginPath();
ctx.moveTo(pos, CANVAS_PADDING);
ctx.lineTo(pos, currentGame.gridSize * CELL_SIZE + CANVAS_PADDING);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(CANVAS_PADDING, pos);
ctx.lineTo(currentGame.gridSize * CELL_SIZE + CANVAS_PADDING, pos);
ctx.stroke();
}
}
// Draw food
ctx.fillStyle = '#ff6b6b';
ctx.shadowBlur = 15;
ctx.shadowColor = '#ff6b6b';
const foodX = currentGame.food.x * CELL_SIZE + CANVAS_PADDING + CELL_SIZE / 2;
const foodY = currentGame.food.y * CELL_SIZE + CANVAS_PADDING + CELL_SIZE / 2;
ctx.beginPath();
ctx.arc(foodX, foodY, CELL_SIZE / 3, 0, Math.PI * 2);
ctx.fill();
ctx.shadowBlur = 0;
// Draw snake
currentGame.snake.forEach((segment, index) => {
const x = segment.x * CELL_SIZE + CANVAS_PADDING;
const y = segment.y * CELL_SIZE + CANVAS_PADDING;
if (index === 0) {
// Head - brighter and larger
ctx.fillStyle = currentGame.alive ? '#4ecdc4' : '#e74c3c';
ctx.shadowBlur = 10;
ctx.shadowColor = currentGame.alive ? '#4ecdc4' : '#e74c3c';
} else {
// Body - gradient from head to tail
const alpha = 1 - (index / currentGame.snake.length) * 0.5;
ctx.fillStyle = `rgba(78, 205, 196, ${alpha})`;
ctx.shadowBlur = 0;
}
ctx.fillRect(x + 2, y + 2, CELL_SIZE - 4, CELL_SIZE - 4);
});
ctx.shadowBlur = 0;
// Draw death overlay if dead
if (!currentGame.alive) {
ctx.fillStyle = 'rgba(231, 76, 60, 0.2)';
ctx.fillRect(0, 0, canvasSize, canvasSize);
ctx.fillStyle = '#e74c3c';
ctx.font = `bold ${size === 'small' ? '16' : '24'}px Inter, sans-serif`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('DEAD', canvasSize / 2, canvasSize / 2);
}
}, [currentGame, showGrid]);
// Calculate canvas size from props, not state, to prevent shaking
const canvasSize = gridSize * CELL_SIZE + CANVAS_PADDING * 2;
return (
<div className="snake-canvas-container">
<canvas
ref={canvasRef}
width={canvasSize}
height={canvasSize}
style={{
width: `${canvasSize}px`,
height: `${canvasSize}px`,
border: '2px solid #3a3a4e',
borderRadius: '8px',
backgroundColor: '#1a1a2e',
}}
/>
{currentGame && (size !== 'small' || showStats) && (
<div className="canvas-info" style={size === 'small' ? { fontSize: '0.7rem', gap: '0.5rem', padding: '0.4rem 0.8rem' } : {}}>
<div className="info-item">
<span className="label">Score:</span>
<span className="value" style={{ fontVariantNumeric: 'tabular-nums', minWidth: '2ch', display: 'inline-block' }}>{currentGame.score}</span>
</div>
<div className="info-item">
<span className="label">Steps:</span>
<span className="value" style={{ fontVariantNumeric: 'tabular-nums', minWidth: '3ch', display: 'inline-block' }}>{currentGame.steps}</span>
</div>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,38 @@
import SnakeCanvas from './SnakeCanvas';
import type { Individual } from '../../lib/snakeAI/evolution';
interface SnakeGridProps {
individuals: Individual[];
gridSize: number;
count?: number; // How many snakes to show (default: 9)
columns?: number; // Number of columns in grid (default: 3)
}
export default function SnakeGrid({ individuals, gridSize, count = 9, columns = 3 }: SnakeGridProps) {
// Take the top N individuals (sorted by fitness)
const topIndividuals = [...individuals]
.sort((a, b) => b.fitness - a.fitness)
.slice(0, count);
return (
<div className="snake-grid" style={{ gridTemplateColumns: `repeat(${columns}, 1fr)` }}>
{topIndividuals.map((individual, index) => (
<div key={index} className={`snake-grid-cell ${index === 0 ? 'best' : ''}`}>
<div className="snake-grid-label">
#{index + 1}
{individual.fitness > 0 && (
<span className="fitness-badge">{Math.round(individual.fitness)}</span>
)}
</div>
<SnakeCanvas
network={individual.network}
gridSize={gridSize}
size="small"
showGrid={false}
showStats={true}
/>
</div>
))}
</div>
);
}

View File

@@ -0,0 +1,62 @@
interface StatsProps {
generation: number;
bestFitness: number;
bestFitnessEver: number;
averageFitness: number;
gamesPlayed: number;
}
export default function Stats({
generation,
bestFitness,
bestFitnessEver,
averageFitness,
gamesPlayed,
}: StatsProps) {
return (
<div className="stats-panel">
<h3>Evolution Statistics</h3>
<div className="stat-grid">
<div className="stat-item highlight">
<div className="stat-label">Generation</div>
<div className="stat-value">{generation}</div>
</div>
<div className="stat-item highlight">
<div className="stat-label">Best Ever</div>
<div className="stat-value">{Math.round(bestFitnessEver)}</div>
</div>
<div className="stat-item">
<div className="stat-label">Current Best</div>
<div className="stat-value">{Math.round(bestFitness)}</div>
</div>
<div className="stat-item">
<div className="stat-label">Average</div>
<div className="stat-value">{Math.round(averageFitness)}</div>
</div>
<div className="stat-item">
<div className="stat-label">Games Played</div>
<div className="stat-value">{gamesPlayed.toLocaleString()}</div>
</div>
</div>
<div className="progress-indicator">
<div className="progress-label">
Improvement: {bestFitnessEver > 0 ? ((bestFitness / bestFitnessEver) * 100).toFixed(1) : 0}%
</div>
<div className="progress-bar">
<div
className="progress-fill"
style={{
width: `${bestFitnessEver > 0 ? Math.min(100, (bestFitness / bestFitnessEver) * 100) : 0}%`,
}}
/>
</div>
</div>
</div>
);
}

54
src/apps/SnakeAI/Tips.tsx Normal file
View File

@@ -0,0 +1,54 @@
export default function Tips() {
return (
<div className="tips-panel">
<h3>How It Works</h3>
<div className="tip-section">
<h4>🧠 Neural Network</h4>
<p>
Each snake is controlled by a neural network with <strong>8 inputs</strong>:
</p>
<ul>
<li>Direction to food (X and Y)</li>
<li>Danger sensors (up, down, left, right)</li>
<li>Current direction</li>
<li>Snake length</li>
</ul>
<p>
The network outputs <strong>3 actions</strong>: turn left, go straight, or turn right.
</p>
</div>
<div className="tip-section">
<h4>🧬 Evolution Process</h4>
<ol>
<li><strong>Play:</strong> All snakes play until they die</li>
<li><strong>Evaluate:</strong> Calculate fitness score</li>
<li><strong>Select:</strong> Best performers become parents</li>
<li><strong>Reproduce:</strong> Create new generation via crossover and mutation</li>
<li><strong>Repeat:</strong> New generation plays the game</li>
</ol>
</div>
<div className="tip-section">
<h4>📊 Fitness Function</h4>
<p>Snakes are scored based on:</p>
<ul>
<li><strong>Food collected</strong> × 100 (primary goal)</li>
<li><strong>Survival time</strong> × 1 (stay alive)</li>
<li><strong>Snake length</strong> × 10 (growth bonus)</li>
</ul>
</div>
<div className="tip-section">
<h4>💡 Tips for Best Results</h4>
<ul>
<li>Higher mutation rate = more exploration</li>
<li>Lower mutation rate = refine existing strategies</li>
<li>Evolution improves around generation 10-20</li>
<li>Watch for emergent behaviors and patterns!</li>
</ul>
</div>
</div>
);
}

1
src/assets/react.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

View File

@@ -0,0 +1,28 @@
.app-container {
height: 100vh;
display: flex;
flex-direction: column;
background: var(--bg-dark);
}
.app-header {
padding: 2rem 3rem;
background: rgba(255, 255, 255, 0.02);
border-bottom: 1px solid var(--border-color);
}
.app-title {
margin: 0;
font-size: 2rem;
font-weight: 700;
background: linear-gradient(135deg, var(--primary) 0%, var(--accent) 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.app-content {
flex: 1;
padding: 2rem 3rem;
overflow-y: auto;
}

View File

@@ -0,0 +1,18 @@
import type { ReactNode } from 'react';
import './AppContainer.css';
interface AppContainerProps {
title: string;
children: ReactNode;
}
export default function AppContainer({ title, children }: AppContainerProps) {
return (
<div className="app-container">
<header className="app-header">
<h2 className="app-title">{title}</h2>
</header>
<div className="app-content">{children}</div>
</div>
);
}

View File

@@ -0,0 +1,92 @@
.sidebar {
width: 280px;
height: 100vh;
background: var(--bg-darker);
border-right: 1px solid var(--border-color);
display: flex;
flex-direction: column;
padding: 2rem 0;
box-shadow: 4px 0 24px rgba(0, 0, 0, 0.5);
}
.sidebar-header {
padding: 0 1.5rem 2rem;
border-bottom: 1px solid var(--border-color);
}
.sidebar-logo {
font-size: 1.75rem;
font-weight: 700;
margin: 0;
background: linear-gradient(135deg, var(--primary) 0%, var(--accent) 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.sidebar-tagline {
margin: 0.25rem 0 0;
font-size: 0.875rem;
color: rgba(255, 255, 255, 0.5);
font-weight: 300;
}
.sidebar-nav {
flex: 1;
padding: 2rem 1rem;
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.nav-item {
display: flex;
align-items: center;
gap: 1rem;
padding: 1rem 1.25rem;
background: transparent;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 12px;
color: rgba(255, 255, 255, 0.7);
cursor: pointer;
transition: all 0.3s ease;
font-size: 1rem;
text-align: left;
}
.nav-item:hover {
background: rgba(255, 255, 255, 0.05);
border-color: var(--primary);
color: rgba(255, 255, 255, 0.9);
transform: translateX(4px);
}
.nav-item.active {
background: linear-gradient(135deg, rgba(99, 102, 241, 0.15) 0%, rgba(139, 92, 246, 0.15) 100%);
border-color: var(--primary);
color: #fff;
box-shadow: 0 4px 15px rgba(99, 102, 241, 0.3);
}
.nav-icon {
font-size: 1.5rem;
line-height: 1;
}
.nav-name {
font-weight: 500;
}
.sidebar-footer {
padding: 0 1.5rem;
border-top: 1px solid rgba(255, 255, 255, 0.1);
padding-top: 1.5rem;
}
.footer-text {
margin: 0;
font-size: 0.75rem;
color: rgba(255, 255, 255, 0.4);
text-align: center;
font-style: italic;
}

View File

@@ -0,0 +1,59 @@
import './Sidebar.css';
export type AppId = 'image-approx' | 'snake-ai';
export interface AppInfo {
id: AppId;
name: string;
icon: string;
description: string;
}
export const APPS: AppInfo[] = [
{
id: 'image-approx',
name: 'Image Approximation',
icon: '🎨',
description: 'Evolve triangles to approximate images',
},
{
id: 'snake-ai',
name: 'Neural Network Snake',
icon: '🐍',
description: 'Evolve neural networks to play Snake',
},
];
interface SidebarProps {
currentApp: AppId;
onAppChange: (appId: AppId) => void;
}
export default function Sidebar({ currentApp, onAppChange }: SidebarProps) {
return (
<aside className="sidebar">
<div className="sidebar-header">
<h1 className="sidebar-logo">🧬 Evolution</h1>
<p className="sidebar-tagline">Mini-Apps</p>
</div>
<nav className="sidebar-nav">
{APPS.map((app) => (
<button
key={app.id}
className={`nav-item ${currentApp === app.id ? 'active' : ''}`}
onClick={() => onAppChange(app.id)}
title={app.description}
>
<span className="nav-icon">{app.icon}</span>
<span className="nav-name">{app.name}</span>
</button>
))}
</nav>
<div className="sidebar-footer">
<p className="footer-text">Select an app to begin</p>
</div>
</aside>
);
}

55
src/index.css Normal file
View File

@@ -0,0 +1,55 @@
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
:root {
/* Color palette - lighter, less dark */
--primary: #6366f1;
--primary-dark: #4f46e5;
--primary-light: #818cf8;
--accent: #8b5cf6;
--bg-dark: #1a1a2e;
--bg-darker: #0f1729;
--bg-card: rgba(255, 255, 255, 0.05);
--text-primary: rgba(255, 255, 255, 0.95);
--text-secondary: rgba(255, 255, 255, 0.7);
--text-muted: rgba(255, 255, 255, 0.5);
--border-color: rgba(255, 255, 255, 0.12);
/* Typography */
font-family: 'Inter', system-ui, -apple-system, sans-serif;
line-height: 1.6;
font-weight: 400;
color: var(--text-primary);
/* Rendering */
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
margin: 0;
background: var(--bg-dark);
color: var(--text-primary);
overflow: hidden;
}
#root {
width: 100vw;
height: 100vh;
}
button {
font-family: inherit;
cursor: pointer;
}
input {
font-family: inherit;
}

View File

@@ -0,0 +1,61 @@
import type { Genome } from './genome';
import { mutateGenome } from './mutation';
import { renderGenome } from './renderer';
import { calculateFitness } from './fitness';
export interface EvolutionConfig {
width: number;
height: number;
mutationStrength: number;
childrenCount: number;
sampleStep: number;
}
export interface EvolutionResult {
genome: Genome;
fitness: number;
improved: boolean;
}
export function evolve(
parent: Genome,
parentFitness: number,
targetData: ImageData,
config: EvolutionConfig,
offscreenCanvas: HTMLCanvasElement
): EvolutionResult {
const ctx = offscreenCanvas.getContext('2d');
if (!ctx) {
return { genome: parent, fitness: parentFitness, improved: false };
}
let bestGenome = parent;
let bestFitness = parentFitness;
let improved = false;
// Generate and evaluate λ (lambda) children
for (let i = 0; i < config.childrenCount; i++) {
const child = mutateGenome(
parent,
config.mutationStrength,
config.width,
config.height
);
// Render child to offscreen canvas
renderGenome(ctx, child, config.width, config.height);
const childData = ctx.getImageData(0, 0, config.width, config.height);
// Evaluate fitness
const childFitness = calculateFitness(targetData, childData, config.sampleStep);
// Keep if better (lower error)
if (childFitness < bestFitness) {
bestGenome = child;
bestFitness = childFitness;
improved = true;
}
}
return { genome: bestGenome, fitness: bestFitness, improved };
}

View File

@@ -0,0 +1,29 @@
/**
* Calculate fitness using mean squared error on RGB channels
* @param targetData - ImageData from target image
* @param candidateData - ImageData from candidate genome
* @param sampleStep - Sample every N pixels for performance (1 = sample all)
* @returns Fitness score (lower is better)
*/
export function calculateFitness(
targetData: ImageData,
candidateData: ImageData,
sampleStep: number = 1
): number {
const target = targetData.data;
const candidate = candidateData.data;
let totalError = 0;
let sampleCount = 0;
for (let i = 0; i < target.length; i += 4 * sampleStep) {
const rDiff = target[i] - candidate[i];
const gDiff = target[i + 1] - candidate[i + 1];
const bDiff = target[i + 2] - candidate[i + 2];
totalError += rDiff * rDiff + gDiff * gDiff + bDiff * bDiff;
sampleCount++;
}
return totalError / sampleCount;
}

View File

@@ -0,0 +1,43 @@
export interface Triangle {
x1: number;
y1: number;
x2: number;
y2: number;
x3: number;
y3: number;
r: number;
g: number;
b: number;
a: number;
}
export type Genome = Triangle[];
export function createRandomGenome(
width: number,
height: number,
count: number
): Genome {
const genome: Genome = [];
for (let i = 0; i < count; i++) {
genome.push({
x1: Math.random() * width,
y1: Math.random() * height,
x2: Math.random() * width,
y2: Math.random() * height,
x3: Math.random() * width,
y3: Math.random() * height,
r: Math.floor(Math.random() * 256),
g: Math.floor(Math.random() * 256),
b: Math.floor(Math.random() * 256),
a: Math.random(),
});
}
return genome;
}
export function cloneGenome(genome: Genome): Genome {
return genome.map((triangle) => ({ ...triangle }));
}

View File

@@ -0,0 +1,85 @@
import type { Genome, Triangle } from './genome';
import { cloneGenome } from './genome';
function clamp(value: number, min: number, max: number): number {
return Math.max(min, Math.min(max, value));
}
function mutateTriangle(
triangle: Triangle,
strength: number,
width: number,
height: number
): Triangle {
const mutated = { ...triangle };
// Occasionally replace entire triangle (15% chance - increased from 10%)
if (Math.random() < 0.15) {
return {
x1: Math.random() * width,
y1: Math.random() * height,
x2: Math.random() * width,
y2: Math.random() * height,
x3: Math.random() * width,
y3: Math.random() * height,
r: Math.floor(Math.random() * 256),
g: Math.floor(Math.random() * 256),
b: Math.floor(Math.random() * 256),
a: Math.random(),
};
}
// Otherwise, perturb existing values
const mutationType = Math.random();
if (mutationType < 0.5) {
// Mutate vertex positions - allow bigger jumps
const vertexChoice = Math.floor(Math.random() * 3);
// Occasional large jump (20% of the time)
const multiplier = Math.random() < 0.2 ? 30 : 15;
const delta = (Math.random() - 0.5) * 2 * strength * multiplier;
if (vertexChoice === 0) {
mutated.x1 = clamp(mutated.x1 + delta, 0, width);
mutated.y1 = clamp(mutated.y1 + delta, 0, height);
} else if (vertexChoice === 1) {
mutated.x2 = clamp(mutated.x2 + delta, 0, width);
mutated.y2 = clamp(mutated.y2 + delta, 0, height);
} else {
mutated.x3 = clamp(mutated.x3 + delta, 0, width);
mutated.y3 = clamp(mutated.y3 + delta, 0, height);
}
} else {
// Mutate color/alpha - more aggressive
const colorMultiplier = Math.random() < 0.2 ? 100 : 50;
const colorDelta = (Math.random() - 0.5) * 2 * strength * colorMultiplier;
const colorChoice = Math.floor(Math.random() * 4);
if (colorChoice === 0) {
mutated.r = clamp(Math.floor(mutated.r + colorDelta), 0, 255);
} else if (colorChoice === 1) {
mutated.g = clamp(Math.floor(mutated.g + colorDelta), 0, 255);
} else if (colorChoice === 2) {
mutated.b = clamp(Math.floor(mutated.b + colorDelta), 0, 255);
} else {
mutated.a = clamp(mutated.a + (Math.random() - 0.5) * 2 * strength * 0.3, 0, 1);
}
}
return mutated;
}
export function mutateGenome(
genome: Genome,
strength: number,
width: number,
height: number
): Genome {
const mutated = cloneGenome(genome);
// Randomly select one triangle to mutate
const index = Math.floor(Math.random() * mutated.length);
mutated[index] = mutateTriangle(mutated[index], strength, width, height);
return mutated;
}

View File

@@ -0,0 +1,24 @@
import type { Genome } from './genome';
export function renderGenome(
ctx: CanvasRenderingContext2D,
genome: Genome,
width: number,
height: number
): void {
// Clear canvas
ctx.fillStyle = '#000';
ctx.fillRect(0, 0, width, height);
// Draw each triangle
for (const triangle of genome) {
ctx.beginPath();
ctx.moveTo(triangle.x1, triangle.y1);
ctx.lineTo(triangle.x2, triangle.y2);
ctx.lineTo(triangle.x3, triangle.y3);
ctx.closePath();
ctx.fillStyle = `rgba(${triangle.r}, ${triangle.g}, ${triangle.b}, ${triangle.a})`;
ctx.fill();
}
}

View File

@@ -0,0 +1,234 @@
import { createNetwork, cloneNetwork, getAction, type Network } from './network';
import { createGame, step, getInputs, calculateFitness, type GameState } from './game';
import type { EvolutionConfig } from './types';
export interface Individual {
network: Network;
fitness: number;
game: GameState;
}
export interface Population {
individuals: Individual[];
generation: number;
bestFitnessEver: number;
bestNetworkEver: Network | null;
}
export function createPopulation(config: EvolutionConfig): Population {
const individuals: Individual[] = [];
for (let i = 0; i < config.populationSize; i++) {
individuals.push({
network: createNetwork(),
fitness: 0,
game: createGame(config.gridSize),
});
}
return {
individuals,
generation: 1,
bestFitnessEver: 0,
bestNetworkEver: null,
};
}
export function evaluatePopulation(
population: Population,
config: EvolutionConfig
): Population {
// Create a working copy of individuals to avoid mutating state
const evaluatedIndividuals = population.individuals.map(ind => ({ ...ind }));
// Play each individual's game to completion or max steps
for (const individual of evaluatedIndividuals) {
let game = individual.game;
while (game.alive && game.steps < config.maxGameSteps) {
const inputs = getInputs(game);
const action = getAction(individual.network, inputs);
game = step(game, action);
}
individual.game = game;
individual.fitness = calculateFitness(game);
}
// Update best ever
let newBestEver = population.bestFitnessEver;
let newBestNetwork = population.bestNetworkEver;
for (const individual of evaluatedIndividuals) {
if (individual.fitness > newBestEver) {
newBestEver = individual.fitness;
newBestNetwork = cloneNetwork(individual.network);
}
}
return {
...population,
individuals: evaluatedIndividuals,
bestFitnessEver: newBestEver,
bestNetworkEver: newBestNetwork,
};
}
export function evolveGeneration(
population: Population,
config: EvolutionConfig
): Population {
// Sort by fitness (descending)
const sorted = [...population.individuals].sort((a, b) => b.fitness - a.fitness);
const newIndividuals: Individual[] = [];
// Elite preservation (top performers survive unchanged)
for (let i = 0; i < config.eliteCount; i++) {
newIndividuals.push({
network: cloneNetwork(sorted[i].network),
fitness: 0,
game: createGame(config.gridSize),
});
}
// Fill rest with offspring
while (newIndividuals.length < config.populationSize) {
const parent1 = selectParent(sorted);
const parent2 = selectParent(sorted);
let childNetwork: Network;
if (Math.random() < 0.7) {
// 70% chance of crossover
childNetwork = crossover(parent1.network, parent2.network);
} else {
// 30% chance of just cloning
childNetwork = cloneNetwork(parent1.network);
}
// Mutate
childNetwork = mutate(childNetwork, config.mutationRate);
newIndividuals.push({
network: childNetwork,
fitness: 0,
game: createGame(config.gridSize),
});
}
return {
individuals: newIndividuals,
generation: population.generation + 1,
bestFitnessEver: population.bestFitnessEver,
bestNetworkEver: population.bestNetworkEver,
};
}
function selectParent(sorted: Individual[]): Individual {
// Tournament selection: pick best of 3 random individuals
const tournamentSize = 3;
let best = sorted[Math.floor(Math.random() * Math.min(sorted.length, 20))];
for (let i = 1; i < tournamentSize; i++) {
const competitor = sorted[Math.floor(Math.random() * Math.min(sorted.length, 20))];
if (competitor.fitness > best.fitness) {
best = competitor;
}
}
return best;
}
function crossover(parent1: Network, parent2: Network): Network {
const child = cloneNetwork(parent1);
// Single-point crossover on weights and biases
const crossoverRate = 0.5;
// Crossover input-hidden weights
for (let i = 0; i < child.weightsIH.length; i++) {
for (let j = 0; j < child.weightsIH[i].length; j++) {
if (Math.random() < crossoverRate) {
child.weightsIH[i][j] = parent2.weightsIH[i][j];
}
}
}
// Crossover hidden-output weights
for (let i = 0; i < child.weightsHO.length; i++) {
for (let j = 0; j < child.weightsHO[i].length; j++) {
if (Math.random() < crossoverRate) {
child.weightsHO[i][j] = parent2.weightsHO[i][j];
}
}
}
// Crossover biases
for (let i = 0; i < child.biasH.length; i++) {
if (Math.random() < crossoverRate) {
child.biasH[i] = parent2.biasH[i];
}
}
for (let i = 0; i < child.biasO.length; i++) {
if (Math.random() < crossoverRate) {
child.biasO[i] = parent2.biasO[i];
}
}
return child;
}
function mutate(network: Network, mutationRate: number): Network {
const mutated = cloneNetwork(network);
// Mutate input-hidden weights
for (let i = 0; i < mutated.weightsIH.length; i++) {
for (let j = 0; j < mutated.weightsIH[i].length; j++) {
if (Math.random() < mutationRate) {
mutated.weightsIH[i][j] += (Math.random() * 2 - 1) * 0.5;
// Clamp to reasonable range
mutated.weightsIH[i][j] = Math.max(-2, Math.min(2, mutated.weightsIH[i][j]));
}
}
}
// Mutate hidden-output weights
for (let i = 0; i < mutated.weightsHO.length; i++) {
for (let j = 0; j < mutated.weightsHO[i].length; j++) {
if (Math.random() < mutationRate) {
mutated.weightsHO[i][j] += (Math.random() * 2 - 1) * 0.5;
mutated.weightsHO[i][j] = Math.max(-2, Math.min(2, mutated.weightsHO[i][j]));
}
}
}
// Mutate biases
for (let i = 0; i < mutated.biasH.length; i++) {
if (Math.random() < mutationRate) {
mutated.biasH[i] += (Math.random() * 2 - 1) * 0.5;
mutated.biasH[i] = Math.max(-2, Math.min(2, mutated.biasH[i]));
}
}
for (let i = 0; i < mutated.biasO.length; i++) {
if (Math.random() < mutationRate) {
mutated.biasO[i] += (Math.random() * 2 - 1) * 0.5;
mutated.biasO[i] = Math.max(-2, Math.min(2, mutated.biasO[i]));
}
}
return mutated;
}
export function getBestIndividual(population: Population): Individual {
return population.individuals.reduce((best, current) =>
current.fitness > best.fitness ? current : best
);
}
export function getAverageFitness(population: Population): number {
const sum = population.individuals.reduce((acc, ind) => acc + ind.fitness, 0);
return sum / population.individuals.length;
}

179
src/lib/snakeAI/game.ts Normal file
View File

@@ -0,0 +1,179 @@
import { Direction, Action, type Position } from './types';
export interface GameState {
snake: Position[];
food: Position;
direction: Direction;
score: number;
steps: number;
stepsSinceLastFood: number;
alive: boolean;
gridSize: number;
}
export function createGame(gridSize: number = 20): GameState {
const center = Math.floor(gridSize / 2);
return {
snake: [
{ x: center, y: center },
{ x: center - 1, y: center },
{ x: center - 2, y: center },
],
food: spawnFood(gridSize, [
{ x: center, y: center },
{ x: center - 1, y: center },
{ x: center - 2, y: center },
]),
direction: Direction.RIGHT,
score: 0,
steps: 0,
stepsSinceLastFood: 0,
alive: true,
gridSize,
};
}
export function step(state: GameState, action: Action): GameState {
if (!state.alive) return state;
const STARVATION_LIMIT = 200; // Die if no food for 200 steps
// Update direction based on action (turn left/right or go straight)
const newDirection = (state.direction + action + 4) % 4;
// Calculate new head position
const head = state.snake[0];
let newHead: Position;
switch (newDirection) {
case Direction.UP:
newHead = { x: head.x, y: head.y - 1 };
break;
case Direction.DOWN:
newHead = { x: head.x, y: head.y + 1 };
break;
case Direction.LEFT:
newHead = { x: head.x - 1, y: head.y };
break;
case Direction.RIGHT:
newHead = { x: head.x + 1, y: head.y };
break;
default:
newHead = head;
}
// Check wall collision
if (
newHead.x < 0 ||
newHead.x >= state.gridSize ||
newHead.y < 0 ||
newHead.y >= state.gridSize
) {
return { ...state, alive: false, steps: state.steps + 1, stepsSinceLastFood: state.stepsSinceLastFood + 1 };
}
// Check self-collision
if (state.snake.some((seg) => seg.x === newHead.x && seg.y === newHead.y)) {
return { ...state, alive: false, steps: state.steps + 1, stepsSinceLastFood: state.stepsSinceLastFood + 1 };
}
// Check starvation (no food for too long)
if (state.stepsSinceLastFood >= STARVATION_LIMIT) {
return { ...state, alive: false, steps: state.steps + 1, stepsSinceLastFood: state.stepsSinceLastFood + 1 };
}
// Create new snake body
const newSnake = [newHead, ...state.snake];
// Check if food was eaten
const ateFood = newHead.x === state.food.x && newHead.y === state.food.y;
if (ateFood) {
// Grow snake, spawn new food, reset starvation counter
return {
...state,
snake: newSnake,
food: spawnFood(state.gridSize, newSnake),
direction: newDirection,
score: state.score + 1,
steps: state.steps + 1,
stepsSinceLastFood: 0,
};
} else {
// Remove tail (no growth), increment starvation counter
newSnake.pop();
return {
...state,
snake: newSnake,
direction: newDirection,
steps: state.steps + 1,
stepsSinceLastFood: state.stepsSinceLastFood + 1,
};
}
}
function spawnFood(gridSize: number, snake: Position[]): Position {
let food: Position;
let attempts = 0;
const maxAttempts = 1000;
do {
food = {
x: Math.floor(Math.random() * gridSize),
y: Math.floor(Math.random() * gridSize),
};
attempts++;
} while (
attempts < maxAttempts &&
snake.some((seg) => seg.x === food.x && seg.y === food.y)
);
return food;
}
export function getInputs(state: GameState): number[] {
const head = state.snake[0];
const food = state.food;
// 8 inputs for the neural network:
// 4 food direction indicators (normalized -1 to 1)
const foodDirX = (food.x - head.x) / state.gridSize;
const foodDirY = (food.y - head.y) / state.gridSize;
// 4 danger sensors (1 if danger, 0 if safe)
const dangerUp = isDanger(state, head.x, head.y - 1);
const dangerDown = isDanger(state, head.x, head.y + 1);
const dangerLeft = isDanger(state, head.x - 1, head.y);
const dangerRight = isDanger(state, head.x + 1, head.y);
return [
foodDirX,
foodDirY,
dangerUp ? 1 : 0,
dangerDown ? 1 : 0,
dangerLeft ? 1 : 0,
dangerRight ? 1 : 0,
state.direction / 3, // Normalized direction
state.snake.length / (state.gridSize * state.gridSize), // Normalized length
];
}
function isDanger(state: GameState, x: number, y: number): boolean {
// Check wall
if (x < 0 || x >= state.gridSize || y < 0 || y >= state.gridSize) {
return true;
}
// Check self-collision
return state.snake.some((seg) => seg.x === x && seg.y === y);
}
export function calculateFitness(state: GameState): number {
// Fitness formula balancing food collection and survival
const foodScore = state.score * 100;
const survivalScore = state.steps;
// Bonus for longer snakes
const lengthBonus = state.snake.length * 10;
return foodScore + survivalScore + lengthBonus;
}

110
src/lib/snakeAI/network.ts Normal file
View File

@@ -0,0 +1,110 @@
import { Action } from './types';
export interface Network {
inputSize: number;
hiddenSize: number;
outputSize: number;
weightsIH: number[][]; // Input to Hidden weights
weightsHO: number[][]; // Hidden to Output weights
biasH: number[]; // Hidden layer biases
biasO: number[]; // Output layer biases
}
export function createNetwork(
inputSize: number = 8,
hiddenSize: number = 12,
outputSize: number = 3
): Network {
return {
inputSize,
hiddenSize,
outputSize,
weightsIH: createRandomMatrix(inputSize, hiddenSize),
weightsHO: createRandomMatrix(hiddenSize, outputSize),
biasH: createRandomArray(hiddenSize),
biasO: createRandomArray(outputSize),
};
}
function createRandomMatrix(rows: number, cols: number): number[][] {
const matrix: number[][] = [];
for (let i = 0; i < rows; i++) {
matrix[i] = [];
for (let j = 0; j < cols; j++) {
matrix[i][j] = Math.random() * 2 - 1; // Random between -1 and 1
}
}
return matrix;
}
function createRandomArray(size: number): number[] {
const array: number[] = [];
for (let i = 0; i < size; i++) {
array[i] = Math.random() * 2 - 1;
}
return array;
}
export function forward(network: Network, inputs: number[]): number[] {
// Hidden layer activation
const hidden: number[] = [];
for (let h = 0; h < network.hiddenSize; h++) {
let sum = network.biasH[h];
for (let i = 0; i < network.inputSize; i++) {
sum += inputs[i] * network.weightsIH[i][h];
}
hidden[h] = tanh(sum);
}
// Output layer activation
const outputs: number[] = [];
for (let o = 0; o < network.outputSize; o++) {
let sum = network.biasO[o];
for (let h = 0; h < network.hiddenSize; h++) {
sum += hidden[h] * network.weightsHO[h][o];
}
outputs[o] = tanh(sum);
}
return outputs;
}
function tanh(x: number): number {
return Math.tanh(x);
}
export function getAction(network: Network, inputs: number[]): Action {
const outputs = forward(network, inputs);
// Find index of maximum output
let maxIndex = 0;
for (let i = 1; i < outputs.length; i++) {
if (outputs[i] > outputs[maxIndex]) {
maxIndex = i;
}
}
// Map output index to action
switch (maxIndex) {
case 0:
return Action.TURN_LEFT;
case 1:
return Action.STRAIGHT;
case 2:
return Action.TURN_RIGHT;
default:
return Action.STRAIGHT;
}
}
export function cloneNetwork(network: Network): Network {
return {
inputSize: network.inputSize,
hiddenSize: network.hiddenSize,
outputSize: network.outputSize,
weightsIH: network.weightsIH.map((row) => [...row]),
weightsHO: network.weightsHO.map((row) => [...row]),
biasH: [...network.biasH],
biasO: [...network.biasO],
};
}

29
src/lib/snakeAI/types.ts Normal file
View File

@@ -0,0 +1,29 @@
export type Direction = 0 | 1 | 2 | 3;
export const Direction = {
UP: 0 as Direction,
RIGHT: 1 as Direction,
DOWN: 2 as Direction,
LEFT: 3 as Direction,
};
export type Action = -1 | 0 | 1;
export const Action = {
TURN_LEFT: -1 as Action,
STRAIGHT: 0 as Action,
TURN_RIGHT: 1 as Action,
};
export interface Position {
x: number;
y: number;
}
export interface EvolutionConfig {
populationSize: number;
mutationRate: number;
eliteCount: number;
gridSize: number;
maxGameSteps: number;
}

10
src/main.tsx Normal file
View File

@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)