JSFiddle - React, Tailwind, and code Playground
HTML
<!-- Langton's ant -->
CSS
table {
border: 1px solid gray;
background-color: seashell;
}
td {
width: 5px;
height: 5px;
}
td.on {
background-color: midnightblue;
}
JavaScript
var max = 80;
var antPosX = antPosY = ~~(max / 2.5);
var antDir = "w";
var dirsOn = {
"n": "w",
"w": "s",
"s": "e",
"e": "n"
};
var dirsOff = {
"n": "e",
"e": "s",
"s": "w",
"w": "n"
};
function init() {
drawGrid();
startAnt();
}
function startAnt() {
walk();
}
function walk() {
repoint();
flip();
move();
setTimeout(walk, 1);
}
function flip() {
var td = getCurrent();
if (isOn(td)) {
td.setAttribute("class", "");
} else {
td.setAttribute("class", "on");
}
}
function repoint() {
var td = getCurrent();
var dir;
if (isOn(td)) {
dir = dirsOn[antDir];
} else {
dir = dirsOff[antDir];
}
antDir = dir;
}
function move() {
var td = getCurrent();
td.style.backgroundColor = "";
switch (antDir) {
case "n":
antPosY -=1;
break;
case "w":
antPosX -=1;
break;
case "e":
antPosX +=1;
break;
case "s":
antPosY +=1;
break;
}
var td = getCurrent();
td.style.backgroundColor = "crimson";
}
function isOn(td) {
return td.getAttribute("class") === "on";
}
function getCurrent() {
return document.getElementById("y"+antPosY+"x"+antPosX);
}
function drawGrid() {
var body = document.body;
var table = document.createElement("table");
table.setAttribute("cellspacing", 0);
table.setAttribute("cellpadding", 0);
table.style.width = (max * 5) + "px";
table.style.height = (max * 5) + "px";
for (var y = 0; y < max; y++) {
var tr = document.createElement("tr");
for (var x = 0; x < max; x++) {
var td = document.createElement("td");
td.setAttribute("id", "y"+y+"x"+x);
tr.appendChild(td);
}
table.appendChild(tr);
}
body.appendChild(table);
}
init();