JSFiddle - React, Tailwind, and code Playground

by replicateur

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Random Agent in a Square World</title>
    <style>
        body { text-align: center; }
        canvas { border: 1px solid black; }
    </style>
</head>
<body>
    <canvas id="world" width="500" height="500"></canvas>
    <script>
        const canvas = document.getElementById("world");
        const ctx = canvas.getContext("2d");

        // Create 100 agents with random initial positions, sizes, and directions
        let agents = [];
        for (let i = 0; i < 10; i++) {
            let radius = Math.random() * 4 + 1; // Random radius between 1 and 5
            let speed = 6 - radius; // Speed inversely proportional to size
            agents.push({
                id: i,
                x: Math.random() * canvas.width,
                y: Math.random() * canvas.height,
                radius: radius,
                speed: speed,
                dx: (Math.random() * 2 - 1) * speed, // Random direction scaled by speed
                dy: (Math.random() * 2 - 1) * speed  // Random direction scaled by speed
            });
        }

        function updateAgents() {
            // Update each agent's position with smooth movements (Brownian motion)
            agents.forEach(agent => {
                // Smoothly adjust direction
                agent.dx += (Math.random() * 2 - 1) * 0.05; // Smaller random change for smoother movement
                agent.dy += (Math.random() * 2 - 1) * 0.05; // Smaller random change for smoother movement

                // Limit the maximum speed to maintain smoothness
                const maxSpeed = agent.speed;
                agent.dx = Math.max(Math.min(agent.dx, maxSpeed), -maxSpeed);
                agent.dy = Math.max(Math.min(agent.dy, maxSpeed), -maxSpeed);

                agent.x += agent.dx;
                agent.y += agent.dy;

                // Ensure agents...