LangtonAntp5js/sketch.js
2025-04-16 16:40:50 +02:00

75 lines
1.7 KiB
JavaScript

const sketch = function (p) {
const gridSize = [200, 200]; // min ~31, smaller is faster
const cellSize = 4; // Smaller is also faster
let agent = { x: cellSize * 30, y: cellSize * 30, angle: 0 };
let cols, rows;
let grid = [];
let cActive, cInactive;
p.setup = function () {
const sketch = p.createCanvas(
gridSize[0] * cellSize,
gridSize[1] * cellSize
);
sketch.parent("sketch");
cols = p.width / cellSize;
rows = p.height / cellSize;
for (let i = 0; i < cols; i++) {
grid[i] = [];
for (let j = 0; j < rows; j++) {
grid[i][j] = 0;
}
}
cActive = p.color(255, 105, 180, 255);
cInactive = p.color(0, 0, 0, 255);
p.background(0);
p.frameRate(1000);
};
p.draw = function () {
// console.log(p.frameRate());
p.noStroke();
const col = agent.x / cellSize;
const row = agent.y / cellSize;
if (grid[col][row] === 1) {
agent.angle += 90;
grid[col][row] = 0;
p.fill(cInactive);
} else {
agent.angle -= 90;
grid[col][row] = 1;
p.fill(cActive);
}
agent.angle = (agent.angle + 360) % 360;
p.rect(agent.x, agent.y, cellSize, cellSize);
switch (agent.angle) {
case 0:
agent.y -= cellSize;
break;
case 90:
agent.x += cellSize;
break;
case 180:
agent.y += cellSize;
break;
case 270:
agent.x -= cellSize;
break;
}
if (agent.x < 0) agent.x = p.width - cellSize;
if (agent.x >= p.width) agent.x = 0;
if (agent.y < 0) agent.y = p.height - cellSize;
if (agent.y >= p.height) agent.y = 0;
};
};
p5Sketch = new p5(sketch);