Certainly! Below is a single HTML file that uses TensorFlow.js to implement your game. The file includes a grid where 100 dots are randomly placed, and 4 apples move to be as close as possible to the dots while trying to avoid each other.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dots and Apples Game</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<h1>Dots and Apples Game</h1>
<canvas id="gameCanvas" width="500" height="500"></canvas>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const numDots = 100;
const numApples = 4;
const learningRate = 0.01;
let dots = [];
let apples = [];
function randomPoint() {
return [Math.random(), Math.random()];
}
function drawDot(point) {
ctx.beginPath();
ctx.arc(point[0] * canvas.width, point[1] * canvas.height, 2, 0, Math.PI * 2);
ctx.fillStyle = 'blue';
ctx.fill();
}
function drawApple(point, index) {
ctx.beginPath();
ctx.arc(point[0] * canvas.width, point[1] * canvas.height, 5, 0, Math.PI * 2);
ctx.fillStyle = ['red', 'green', 'yellow', 'orange'][index];
ctx.fill();
}
function reset() {
dots = Array.from({ length: numDots }, randomPoint);
apples = Array.from({ length: numApples }, randomPoint);
}
function lossFunction(applePositions) {
let loss = 0;
// Calculate distance from each apple to each dot
dots.forEach(dot => {
applePositions.forEach((apple, index) => {
const distance = tf.tidy(() => tf.sum(apple.sub(dot).pow(2)).sqrt());
loss += distance;
});
});
// Penalize apples for being too close to each other
for (let i = 0; i < numApples; i++) {
for (let j = i + 1; j < numApples; j++) {
const distance = tf.tidy(() => tf.sum(applePositions[i].sub(applePositions[j]).pow(2)).sqrt());
loss += 1 / distance; // Inverse distance to penalize closeness
}
}
return loss;
}
async function train() {
const appleTensors = apples.map(apple => tf.variable(tf.tensor2d(apple)));
for (let step = 0; step < 100; step++) {
const loss = lossFunction(appleTensors);
const gradients = tf.grad(lossFunction)(appleTensors);
gradients.forEach((grad, i) => {
appleTensors[i].sub(grad.mul(tf.scalar(learningRate)));
});
await tf.nextFrame();
}
apples = appleTensors.map(tensor => tensor.dataSync());
draw();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
dots.forEach(drawDot);
apples.forEach(drawApple);
}
reset();
draw();
train();
</script>
</body>
</html>
Explanation:
-
HTML Structure:
- A canvas element is created to draw the dots and apples.
-
Style:
- Basic styling for the canvas to add a border.
-
JavaScript:
- TensorFlow.js is included via CDN.
- Variables for the number of dots and apples, and the learning rate for gradient descent.
- Functions to generate random points, draw dots and apples, and reset the game.
lossFunction calculates the loss based on the distance from apples to dots and the distance between apples.
train function uses gradient descent to update the positions of the apples.
- The
draw function clears the canvas and redraws the dots and apples.
This code will create a 500x500 canvas, place 100 random dots, and have 4 apples that move to minimize the loss function using gradient descent.