Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Langton's Ant</title>
- <style>
- canvas { border: 1px solid black; }
- </style>
- </head>
- <body>
- <canvas id="gridCanvas"></canvas>
- <script>
- const WW = 560, HH = 560;
- const GRID_SIZE = 10;
- const ROWS = HH / GRID_SIZE, COLS = WW / GRID_SIZE;
- const canvas = document.getElementById('gridCanvas');
- const ctx = canvas.getContext('2d');
- canvas.width = WW;
- canvas.height = HH;
- let grid = Array.from({ length: ROWS }, () => Array(COLS).fill(0));
- let ant_x = Math.floor(ROWS / 2), ant_y = Math.floor(COLS / 2);
- let ant_direction = 0; // 0: up, 1: right, 2: down, 3: left
- function draw() {
- grid[ant_x][ant_y] ^= 1;
- ctx.fillStyle = grid[ant_x][ant_y] ? "black" : "white";
- ctx.fillRect(ant_y * GRID_SIZE, ant_x * GRID_SIZE, GRID_SIZE, GRID_SIZE);
- ant_direction = grid[ant_x][ant_y] ? (ant_direction + 1) % 4 : (ant_direction + 3) % 4;
- if (ant_direction === 0) ant_x--;
- else if (ant_direction === 1) ant_y++;
- else if (ant_direction === 2) ant_x++;
- else if (ant_direction === 3) ant_y--;
- ant_x = (ant_x + ROWS) % ROWS;
- ant_y = (ant_y + COLS) % COLS;
- requestAnimationFrame(draw);
- }
- draw();
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement