1
0
Fork 0
advent-of-code/viz2024-06-01.js

108 lines
2.6 KiB
JavaScript
Raw Normal View History

2024-12-06 15:08:04 +01:00
let inputData = ``;
let m = [];
let guard, UP, DOWN, LEFT, RIGHT;
let obstacles = new Set();
let visitedPos = new Set();
let cellSize = 800 / 130;
function setup() {
createCanvas(800, 800);
frameRate(120);
// Parse input data
m = inputData.split('\n').map(line => line.trim());
// Define directions
UP = { x: 0, y: -1 };
DOWN = { x: 0, y: 1 };
LEFT = { x: -1, y: 0 };
RIGHT = { x: 1, y: 0 };
// Initialize guard and obstacles
for (let y = 0; y < m.length; y++) {
for (let x = 0; x < m[y].length; x++) {
let cell = m[y][x];
if (["^", "v", "<", ">"].includes(cell)) {
guard = {
pos: { x, y },
direction:
cell === "^" ? UP :
cell === "v" ? DOWN :
cell === "<" ? LEFT :
RIGHT
};
}
if (cell === "#") {
obstacles.add(`${x},${y}`);
}
}
}
}
function draw() {
background(220);
moveGuard();
drawGrid();
}
function moveGuard() {
if (!visitedPos.has(`${guard.pos.x},${guard.pos.y}`)) {
visitedPos.add(`${guard.pos.x},${guard.pos.y}`);
}
let nextPos = {
x: guard.pos.x + guard.direction.x,
y: guard.pos.y + guard.direction.y
};
if (isObstacle(nextPos)) {
// Change direction if obstacle encountered
if (guard.direction === UP) guard.direction = RIGHT;
else if (guard.direction === RIGHT) guard.direction = DOWN;
else if (guard.direction === DOWN) guard.direction = LEFT;
else if (guard.direction === LEFT) guard.direction = UP;
} else {
// Move guard
guard.pos = nextPos;
}
}
function isObstacle(pos) {
return obstacles.has(`${pos.x},${pos.y}`) ||
pos.x < 0 || pos.x >= m[0].length ||
pos.y < 0 || pos.y >= m.length;
}
function drawGrid() {
// Draw visited positions
fill(255, 255, 0, 100); // Transparent yellow
visitedPos.forEach(pos => {
let [x, y] = pos.split(',').map(Number);
rect(x * cellSize, y * cellSize, cellSize, cellSize);
});
// Draw obstacles
fill(255, 0, 0, 100); // Transparent red
obstacles.forEach(pos => {
let [x, y] = pos.split(',').map(Number);
rect(x * cellSize, y * cellSize, cellSize, cellSize);
});
// Draw guard
fill(0, 0, 255); // Blue
rect(guard.pos.x * cellSize, guard.pos.y * cellSize, cellSize, cellSize);
// Draw guard direction
fill(0);
textAlign(CENTER, CENTER);
text(
guard.direction === UP ? "^" :
guard.direction === DOWN ? "v" :
guard.direction === LEFT ? "<" : ">",
guard.pos.x * cellSize + cellSize/2,
guard.pos.y * cellSize + cellSize/2
);
}