JSFiddle - React, Tailwind, and code Playground

by replicateur

HTML

<canvas id="canvas"></canvas>
<div id="board">
  <button id="startAnimation">START</button>
  <button id="stopAnimation">STOP</button>
</div>
<div class="slidecontainer">
  <span>Delta</span>
  <input type="range" min="1" max="100" value="50" class="slider" id="myRange">
  <span id="demo"></span>
</div>
<div>
  <span id="counter"></span>
</div>

CSS

body {
  background: black;
  color: white;
}

canvas {
  margin: auto;
  background: white;
  border: 1px solid black;
}

JavaScript

var requestId;
var now = new Date();
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var ANTS_NUMBER = 5;
var OBSTACLES_NUMBER = 50;
var OBJECT_SIZE = 5;
var DELTA_FORCE_MOVE = 50;
var VISION_RADIUS = 20;
canvas.width = 166;
canvas.height = 144;

document.getElementById('startAnimation').onclick = startAnimation;
document.getElementById('stopAnimation').onclick = stopAnimation;

var bufferText = "";
var count = 0;
var ants = [];
var obstacles = [];
var velocityVector = [-1, 0, 1];
var counter = document.getElementById('counter');
var vX = 0;
var vY = 0;
var vCount = 0;

// Main animation loop
function clock() {  
    vCount = 0;
    vX = 0;
    vY = 0;
    counter.innerHTML = count;

    // Clear canvas before redrawing
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // Draw each obstacle
    obstacles.forEach(function(obstacle) {
        if (!obstacle.carry) {
            // Draw obstacle if it's not being carried by an ant
            ctx.fillStyle = obstacle.rgba;
            ctx.fillRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height);
            vX += obstacle.x;
            vY += obstacle.y;
            vCount++;
        }
    });
    
    if (vCount > 0) {
        // Draw the average position of all obstacles
        ctx.fillStyle = 'rgba(0, 255, 0, 1)';
        ctx.fillRect(Math.round(vX / vCount), Math.round(vY / vCount), 5, 5);
    }

    // Draw each ant and update its position
    ants.forEach(function(ant) {
        // Determine if any obstacles are within the ant's vision radius
        let visibleObstacle = getVisibleObstacle(ant, obstacles);
        if (visibleObstacle !== false && !ant.carry) {
            // Move towards the visible obstacle with smoother approach to avoid shaking
            let obstacle = obstacles[visibleObstacle];
            ant.velX = (obstacle.x - ant.x) / Math.max(1, Math.abs(obstacle.x - ant.x));
            ant.velY = (obstacle.y - ant.y) / Math.max(1,...