Advertisement
here2share

Langton's Ant

May 3rd, 2025
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 1.53 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>Langton's Ant</title>
  7.     <style>
  8.         canvas { border: 1px solid black; }
  9.     </style>
  10. </head>
  11. <body>
  12.     <canvas id="gridCanvas"></canvas>
  13.     <script>
  14.         const WW = 560, HH = 560;
  15.         const GRID_SIZE = 10;
  16.         const ROWS = HH / GRID_SIZE, COLS = WW / GRID_SIZE;
  17.         const canvas = document.getElementById('gridCanvas');
  18.         const ctx = canvas.getContext('2d');
  19.         canvas.width = WW;
  20.         canvas.height = HH;
  21.  
  22.         let grid = Array.from({ length: ROWS }, () => Array(COLS).fill(0));
  23.         let ant_x = Math.floor(ROWS / 2), ant_y = Math.floor(COLS / 2);
  24.         let ant_direction = 0; // 0: up, 1: right, 2: down, 3: left
  25.  
  26.         function draw() {
  27.             grid[ant_x][ant_y] ^= 1;
  28.             ctx.fillStyle = grid[ant_x][ant_y] ? "black" : "white";
  29.             ctx.fillRect(ant_y * GRID_SIZE, ant_x * GRID_SIZE, GRID_SIZE, GRID_SIZE);
  30.  
  31.             ant_direction = grid[ant_x][ant_y] ? (ant_direction + 1) % 4 : (ant_direction + 3) % 4;
  32.  
  33.             if (ant_direction === 0) ant_x--;
  34.             else if (ant_direction === 1) ant_y++;
  35.             else if (ant_direction === 2) ant_x++;
  36.             else if (ant_direction === 3) ant_y--;
  37.  
  38.             ant_x = (ant_x + ROWS) % ROWS;
  39.             ant_y = (ant_y + COLS) % COLS;
  40.  
  41.             requestAnimationFrame(draw);
  42.         }
  43.  
  44.         draw();
  45.     </script>
  46. </body>
  47. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement