Make neural network using HTML + JS that learn how to play snake game with each generation, provide full code in one file
Assistant
Sure! Below is a complete HTML file that includes the implementation of a Snake game along with a simple neural network that learns to play the game over generations using a genetic algorithm. This code combines all elements into one file for ease of use.
Please note that implementing a fully functional neural network that learns how to play Snake from scratch is a complex task. The code provided simplifies many aspects to keep it understandable and runnable in a browser environment.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Snake AI with Neural Network</title>
<style>
body { margin: 0; }
canvas { display: block; background: #000; margin: 0 auto; }
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="400"></canvas>
<script>
// Game constants
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const canvasSize = 400;
const gridSize = 20;
const tileCount = canvasSize / gridSize;
// Genetic Algorithm parameters
const populationSize = 50;
const mutationRate = 0.1;
const generations = 1000;
// Neural Network parameters
const inputNodes = 6;
const hiddenNodes = 10;
const outputNodes = 3; // Move: [left, straight, right]
// Define the Snake class
class Snake {
constructor(brain) {
this.x = Math.floor(tileCount / 2);
this.y = Math.floor(tileCount / 2);
this.xVelocity = 0;
this.yVelocity = -1;
this.tail = [];
this.score = 0;
this.alive = true;
this.food = this.placeFood();
// Initialize neural network
if (brain) {
this.brain = brain.copy();
this.brain.mutate(mutationRate);
} else {
this.brain = new NeuralNetwork(inputNodes, hiddenNodes, outputNodes);
}
this.fitness = 0;
}
placeFood() {
return {
x: Math.floor(Math.random() * tileCount),
y: Math.floor(Math.random() * tileCount),
};
}
think() {
// Inputs to the neural network
let inputs = [];
// Distance to walls (up, right, down, left)
inputs[0] = this.y / tileCount; // Up
inputs[1] = (tileCount - this.x) / tileCount; // Right
inputs[2] = (tileCount - this.y) / tileCount; // Down
inputs[3] = this.x / tileCount; // Left
// Food location relative to the snake's head
inputs[4] = (this.food.x - this.x) / tileCount;
inputs[5] = (this.food.y - this.y) / tileCount;
// Get outputs from the neural network
let outputs = this.brain.predict(inputs);
// Decide action based on outputs
let maxIndex = outputs.indexOf(Math.max(...outputs));
if (maxIndex === 0) {
this.turnLeft();
} else if (maxIndex === 2) {
this.turnRight();
}
// If maxIndex === 1, go straight (do nothing)
}
turnLeft() {
if (this.xVelocity === 0) {
let temp = this.xVelocity;
this.xVelocity = this.yVelocity;
this.yVelocity = temp;
} else {
let temp = this.xVelocity;
this.xVelocity = -this.yVelocity;
this.yVelocity = temp;
}
}
turnRight() {
if (this.xVelocity === 0) {
let temp = this.xVelocity;
this.xVelocity = -this.yVelocity;
this.yVelocity = temp;
} else {
let temp = this.xVelocity;
this.xVelocity = this.yVelocity;
this.yVelocity = -temp;
}
}
update() {
if (!this.alive) return;
this.think();
this.x += this.xVelocity;
this.y += this.yVelocity;
// Check wall collision
if (this.x < 0 || this.x >= tileCount || this.y < 0 || this.y >= tileCount) {
this.alive = false;
}
// Check self collision
for (let cell of this.tail) {
if (cell.x === this.x && cell.y === this.y) {
this.alive = false;
break;
}
}
// Move tail
this.tail.unshift({ x: this.x, y: this.y });
if (this.tail.length > this.score + 1) {
this.tail.pop();
}
// Check food collision
if (this.x === this.food.x && this.y === this.food.y) {
this.score++;
this.food = this.placeFood();
}
// Update fitness
this.fitness = this.score;
}
draw() {
if (!this.alive) return;
// Draw snake
ctx.fillStyle = 'lime';
for (let cell of this.tail) {
ctx.fillRect(cell.x * gridSize, cell.y * gridSize, gridSize, gridSize);
}
// Draw food
ctx.fillStyle = 'red';
ctx.fillRect(this.food.x * gridSize, this.food.y * gridSize, gridSize, gridSize);
}
}
// Define the Neural Network class
class NeuralNetwork {
constructor(input_nodes, hidden_nodes, output_nodes) {
this.input_nodes = input_nodes;
this.hidden_nodes = hidden_nodes;
this.output_nodes = output_nodes;
this.weights_ih = new Matrix(this.hidden_nodes, this.input_nodes);
this.weights_ho = new Matrix(this.output_nodes, this.hidden_nodes);
this.weights_ih.randomize();
this.weights_ho.randomize();
this.bias_h = new Matrix(this.hidden_nodes, 1);
this.bias_o = new Matrix(this.output_nodes, 1);
this.bias_h.randomize();
this.bias_o.randomize();
this.learning_rate = 0.1;
}
predict(input_array) {
// Generating the Hidden Outputs
let inputs = Matrix.fromArray(input_array);
let hidden = Matrix.multiply(this.weights_ih, inputs);
hidden.add(this.bias_h);
// Activation function
hidden.map(sigmoid);
// Generating the output's output!
let output = Matrix.multiply(this.weights_ho, hidden);
output.add(this.bias_o);
output.map(sigmoid);
// Sending back to the caller!
return output.toArray();
}
copy() {
let nn = new NeuralNetwork(this.input_nodes, this.hidden_nodes, this.output_nodes);
nn.weights_ih = this.weights_ih.copy();
nn.weights_ho = this.weights_ho.copy();
nn.bias_h = this.bias_h.copy();
nn.bias_o = this.bias_o.copy();
return nn;
}
mutate(rate) {
function mutate(val) {
if (Math.random() < rate) {
return val + randomGaussian();
} else {
return val;
}
}
this.weights_ih.map(mutate);
this.weights_ho.map(mutate);
this.bias_h.map(mutate);
this.bias_o.map(mutate);
}
}
// Helper functions
function sigmoid(x) {
return 1 / (1 + Math.exp(-x));
}
function randomGaussian() {
let u = 0, v = 0;
while(u === 0) u = Math.random();
while(v === 0) v = Math.random();
let num = Math.sqrt(-2.0 * Math.log(u)) * Math.cos(2.0 * Math.PI * v);
return num / 10.0;
}
// Define the Matrix class
class Matrix {
constructor(rows, cols) {
this.rows = rows;
this.cols = cols;
this.data = [];
for (let i = 0; i < this.rows; i++) {
this.data[i] = [];
for (let j = 0; j < this.cols; j++) {
this.data[i][j] = 0;
}
}
}
copy() {
let m = new Matrix(this.rows, this.cols);
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++) {
m.data[i][j] = this.data[i][j];
}
}
return m;
}
static fromArray(arr) {
let m = new Matrix(arr.length, 1);
for (let i = 0; i < arr.length; i++) {
m.data[i][0] = arr[i];
}
return m;
}
toArray() {
let arr = [];
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++) {
arr.push(this.data[i][j]);
}
}
return arr;
}
randomize() {
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++) {
this.data[i][j] = Math.random() * 2 - 1;
}
}
}
static multiply(a, b) {
// Matrix product
if (a.cols !== b.rows) {
console.log('Columns of A must match rows of B.');
return undefined;
}
let result = new Matrix(a.rows, b.cols);
for (let i = 0; i < result.rows; i++) {
for (let j = 0; j < result.cols; j++) {
let sum = 0;
for (let k = 0; k < a.cols; k++) {
sum += a.data[i][k] * b.data[k][j];
}
result.data[i][j] = sum;
}
}
return result;
}
add(n) {
if (n instanceof Matrix) {
if (this.rows !== n.rows || this.cols !== n.cols) {
console.log('Matrices must have same dimensions.');
return undefined;
}
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++) {
this.data[i][j] += n.data[i][j];
}
}
} else {
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++) {
this.data[i][j] += n;
}
}
}
}
map(func) {
for (let i = 0; i < this.rows; i++) {
for (let j = 0; j < this.cols; j++) {
let val = this.data[i][j];
this.data[i][j] = func(val);
}
}
}
}
// Genetic Algorithm functions
let snakes = [];
let bestSnake;
let generation = 0;
let frameCount = 0;
for (let i = 0; i < populationSize; i++) {
snakes[i] = new Snake();
}
function nextGeneration() {
calculateFitness();
snakes = generateNewSnakes();
generation++;
frameCount = 0;
}
function calculateFitness() {
let sum = 0;
for (let snake of snakes) {
sum += snake.fitness;
}
for (let snake of snakes) {
snake.fitness = snake.fitness / sum;
}
}
function pickOne() {
let index = 0;
let r = Math.random();
while (r > 0) {
r = r - snakes[index].fitness;
index++;
}
index--;
let snake = snakes[index];
let child = new Snake(snake.brain);
return child;
}
function generateNewSnakes() {
let newSnakes = [];
for (let i = 0; i < snakes.length; i++) {
newSnakes[i] = pickOne();
}
return newSnakes;
}
// Main game loop
function gameLoop() {
frameCount++;
ctx.clearRect(0, 0, canvasSize, canvasSize);
let allDead = true;
for (let snake of snakes) {
if (snake.alive) {
allDead = false;
snake.update();
snake.draw();
}
}
if (allDead || frameCount > 500) {
nextGeneration();
}
// Display generation count
ctx.fillStyle = 'white';
ctx.font = '16px Arial';
ctx.fillText('Generation: ' + generation, 10, 20);
requestAnimationFrame(gameLoop);
}
// Start the game
gameLoop();
</script>
</body>
</html>
Explanation:
Snake Class: Represents the snake in the game. Each snake has a neural network (brain) that decides its moves.
Neural Network Class: A simple feedforward neural network with one hidden layer.
Genetic Algorithm:
Population: A group of snakes.
Fitness Calculation: Based on the score (length of the snake).
Selection and Mutation: Create a new generation by selecting snakes based on fitness and applying mutation.
Game Loop: Runs the game and updates each snake in the population.
How to Use:
Save the Code: Copy and paste the entire code into a file and save it with a .html extension (e.g., snake_ai.html).
Run in Browser: Open the HTML file in a modern web browser (e.g., Chrome, Firefox).
Watch the AI Learn: The canvas will display the snakes as they attempt to learn how to play the game over generations.
Note:
This is a simplified implementation to demonstrate the concept.
Training may take time, and due to the simplified nature of the neural network and genetic algorithm, the snakes might not perform optimally.
For more advanced learning, consider implementing techniques like deep learning with convolutional neural networks or reinforcement learning with Q-learning.