Skip to content

Commit db473e9

Browse files
Merge pull request steam-bell-92#1562 from mayurigade-hub/fix/tower-of-hanoi-invalid-moves
fix: prevent invalid moves in Tower of Hanoi
2 parents 830af42 + 033d53b commit db473e9

1 file changed

Lines changed: 16 additions & 4 deletions

File tree

web-app/js/projects/tower-of-hanoi.js

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -207,9 +207,19 @@ function initTowerOfHanoi() {
207207
}
208208
}
209209

210-
function executeMove(from, to, saveHistory = true) {
211-
if (towers[from].length === 0) return;
212-
const disk = towers[from].pop();
210+
function executeMove(from, to, saveHistory = true, showWarning = false) {
211+
if (towers[from].length === 0) return false;
212+
const disk = towers[from][towers[from].length - 1];
213+
const targetTopDisk = towers[to][towers[to].length - 1];
214+
215+
if (targetTopDisk !== undefined && disk > targetTopDisk) {
216+
if (showWarning) {
217+
alert("Invalid move: you cannot place a larger disk on a smaller disk.");
218+
}
219+
return false;
220+
}
221+
222+
towers[from].pop();
213223
towers[to].push(disk);
214224

215225
if (saveHistory) {
@@ -225,6 +235,8 @@ function initTowerOfHanoi() {
225235
if (towers[2].length === diskCount && !isAnimating) {
226236
setTimeout(() => alert("🎉 Puzzle Solved!"), 100);
227237
}
238+
239+
return true;
228240
}
229241

230242
async function autoMove(from, to) {
@@ -311,7 +323,7 @@ function initTowerOfHanoi() {
311323
drawTowers();
312324
} else {
313325
moveQueue = []; // Clear auto queue on manual intervention
314-
executeMove(selectedTower, clickedTower);
326+
executeMove(selectedTower, clickedTower, true, true);
315327
selectedTower = null;
316328
drawTowers();
317329
}

0 commit comments

Comments
 (0)