class Grid {
constructor() {
this.head = { x: 0, y: 0 };
this.tail = { x: 0, y: 0 };
this.grid = new Map();
this.grid.set("0:0", 1);
}
move(dir) {
this.moveTail();
this.recordTailPosition();
switch (dir) {
case "R":
this.head.x++;
break;
case "U":
this.head.y++;
break;
case "L":
this.head.x--;
break;
case "D":
this.head.y--;
break;
}
}
moveTail() {
if (this.head.x === this.tail.x && this.head.y === this.tail.y) return;
if (this.head.x > this.tail.x) {
this.tail.x++;
if (this.head.y > this.tail.y) {
this.tail.y++;
} else if (this.head.y < this.tail.y) {
this.tail.x++;
}
} else if (this.head.x < this.tail.x) {
this.tail.x--;
if (this.head.y > this.tail.y) {
this.tail.y++;
} else if (this.head.y < this.tail.y) {
this.tail.x++;
}
} else if (this.head.y > this.tail.y) {
this.tail.y++;
} else if (this.head.y < this.tail.y) {
this.tail.y--;
}
}
key(x, y) {
return `${x}:${y}`;
}
recordTailPosition() {
const gridKey = this.key(this.tail.x, this.tail.y);
const val = this.grid.get(gridKey);
this.grid.set(gridKey, val ? val + 1 : 1);
}
gridSize() {
return [...this.grid.keys()].reduce(
([maxX, maxY], key) => {
const [x, y] = key.split(":").map((n) => parseInt(n));
return [Math.max(x, maxX), Math.max(y, maxY)];
},
[0, 0]
);
}
render() {
const [maxX, maxY] = this.gridSize();
return { head: this.head, tail: this.tail, maxX };
let output = "";
for (let i = maxY; i >= 0; i--) {
for (let j = 0; j <= maxX; j++) {
if (this.head.x === j && this.head.y === i) {
output += "H";
} else if (this.tail.x === j && this.tail.y === i) {
output += "T";
} else if (i === 0 && j === 0) {
output += "s";
} else {
output += ".";
}
output += " ";
}
output += "\n";
}
return html`<pre>${output}</pre>`;
}
}