73 lines
1.4 KiB
JavaScript
73 lines
1.4 KiB
JavaScript
const DISK_WIDTH = 30;
|
|
const DISK_HEIGHT = 20;
|
|
const DELAY_MS = 500;
|
|
const NUMBER_OF_DISKS = 3;
|
|
|
|
let pole1, pole2, pole3;
|
|
let A = generateDisks(NUMBER_OF_DISKS); // bottom up, from large to small, like [4,3,2,1]
|
|
let B = [];
|
|
let C = [];
|
|
|
|
// Solving the Tower of Hanoi
|
|
async function solveTower(n, from, to, helper) {
|
|
// todo
|
|
}
|
|
|
|
async function move(from, to) {
|
|
to.push(from.pop());
|
|
await sleep(DELAY_MS);
|
|
}
|
|
|
|
// Main program
|
|
|
|
function setup() {
|
|
createCanvas(innerWidth, 600); // full width
|
|
pole1 = (1 * width) / 5;
|
|
pole2 = width / 2;
|
|
pole3 = (4 * width) / 5;
|
|
}
|
|
|
|
function draw() {
|
|
background(200);
|
|
|
|
// draw three poles
|
|
stroke(0);
|
|
strokeWeight(5);
|
|
line(pole1, height, pole1, height / 3);
|
|
line(pole2, height, pole2, height / 3);
|
|
line(pole3, height, pole3, height / 3);
|
|
|
|
fill(255, 0, 0);
|
|
drawDisks(pole1, A);
|
|
drawDisks(pole2, B);
|
|
drawDisks(pole3, C);
|
|
}
|
|
|
|
function drawDisks(poleLocation, disks) {
|
|
let y = height - DISK_HEIGHT / 2;
|
|
|
|
rectMode(CENTER);
|
|
stroke(0);
|
|
strokeWeight(2);
|
|
for (let disk of disks) {
|
|
rect(poleLocation, y, DISK_WIDTH * disk, DISK_HEIGHT);
|
|
y -= DISK_HEIGHT;
|
|
}
|
|
}
|
|
|
|
function mousePressed() {
|
|
solveTower(A.length, A, B, C);
|
|
}
|
|
|
|
// Helpers
|
|
|
|
function generateDisks(n) {
|
|
return Array(n)
|
|
.fill()
|
|
.map((_, i) => n - i);
|
|
}
|
|
|
|
function sleep(milliseconds) {
|
|
return new Promise((resolve) => setTimeout(resolve, milliseconds));
|
|
}
|