Below is a complete HTML file that implements your game using TensorFlow.js. The game places 100 dots randomly on a 1x1 grid and uses gradient descent to optimize the positions of 4 apples. Each apple tries to minimize its distance to the closest dots while maximizing its distance to other apples, creating a competitive dynamic.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Apple Dot Game</title>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@3.18.0/dist/tf.min.js"></script>
<style>
canvas { border: 1px solid black; }
.controls { margin-bottom: 10px; }
</style>
</head>
<body>
<div class="controls">
<label for="dots">Number of Dots:</label>
<input type="number" id="dots" value="100" min="10" max="500">
<label for="apples">Number of Apples:</label>
<input type="number" id="apples" value="4" min="2" max="10">
<button onclick="resetGame()">Reset Game</button>
</div>
<canvas id="canvas" width="500" height="500"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let dots = [];
let apples = [];
let numDots = 100;
let numApples = 4;
const learningRate = 0.01;
const canvasSize = 500;
// Initialize TensorFlow variables
let appleVars = [];
function initGame() {
numDots = parseInt(document.getElementById('dots').value);
numApples = parseInt(document.getElementById('apples').value);
dots = Array.from({ length: numDots }, () => [Math.random(), Math.random()]);
apples = Array.from({ length: numApples }, () => [Math.random(), Math.random()]);
// Initialize TensorFlow variables for apples
appleVars = apples.map(apple => tf.variable(tf.tensor2d([apple]), false, 'float32'));
}
function resetGame() {
initGame();
trainApples();
}
function draw() {
ctx.clearRect(0, 0, canvasSize, canvasSize);
// Draw dots
ctx.fillStyle = 'blue';
dots.forEach(dot => {
ctx.beginPath();
ctx.arc(dot[0] * canvasSize, dot[1] * canvasSize, 2, 0, Math.PI * 2);
ctx.fill();
});
// Draw apples
ctx.fillStyle = 'red';
apples.forEach(apple => {
ctx.beginPath();
ctx.arc(apple[0] * canvasSize, apple[1] * canvasSize, 4, 0, Math.PI * 2);
ctx.fill();
});
}
function lossFunction(applePos) {
const dotDistances = dots.map(dot => tf.norm(tf.sub(applePos, tf.tensor2d([dot]))));
const closestDotDistances = tf.min(tf.stack(dotDistances, 0), 0);
const appleDistances = apples
.map(apple => tf.norm(tf.sub(applePos, tf.tensor2d([apple]))))
.filter(d => d.arraySync()[0] > 0) // Exclude self-distance
.map(d => tf.square(d));
const repulsion = tf.sum(tf.stack(appleDistances, 0), 0).div(tf.scalar(numApples - 1 || 1));
return tf.neg(tf.sum(tf.reciprocal(closestDotDistances))).add(repulsion);
}
async function trainStep() {
for (let i = 0; i < appleVars.length; i++) {
const applePos = appleVars[i];
const loss = () => lossFunction(applePos.reshape([2]));
const gradients = tf.grad(loss)();
appleVars[i] = applePos.sub(gradients.mul(learningRate));
// Clamp apple positions to [0, 1]
appleVars[i] = tf.clipByValue(appleVars[i], 0, 1);
}
// Update apples array
apples = appleVars.map(varTensor => varTensor.arraySync()[0]);
draw();
await tf.nextFrame();
requestAnimationFrame(trainStep);
}
function trainApples() {
trainStep();
}
// Initialize and start the game
initGame();
trainApples();
</script>
</body>
</html>
Explanation:
-
HTML & Controls:
- The HTML includes a canvas for rendering and controls to adjust the number of dots and apples.
-
Initialization:
initGame() initializes the dots and apples with random positions and sets up TensorFlow variables for the apples.
-
Drawing:
draw() renders the dots and apples on the canvas.
-
Loss Function:
- The loss function for each apple has two components:
- Attraction: Minimizes the sum of the reciprocals of distances to the closest dots (encourages apples to be near dots).
- Repulsion: Maximizes the squared distance to other apples (encourages apples to spread out).
-
Training:
trainStep() performs gradient descent to update the positions of the apples. The positions are clamped to the [0, 1] range to keep them within the grid.
-
TensorFlow.js:
- TensorFlow.js is used to compute gradients and update positions efficiently.
How It Works:
- The apples compete to be closest to as many dots as possible while avoiding each other.
- Adjust the number of dots and apples using the controls and reset the game to see different behaviors.
This implementation should give you the desired competitive behavior between the apples!