Last active
September 27, 2015 21:28
-
-
Save kevincolten/f1af35ad0ab0fb62c89a to your computer and use it in GitHub Desktop.
Towers of Hanoi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var prompt = require('prompt'); | |
prompt.start(); | |
var stacks = { | |
a: [4, 3, 2, 1], | |
b: [], | |
c: [] | |
}; | |
function printStacks() { | |
console.log("a: " + stacks.a); | |
console.log("b: " + stacks.b); | |
console.log("c: " + stacks.c); | |
} | |
function movePiece(start, finish) { | |
// "push" on the finish stack the block that is popped off the startig stack | |
stacks[finish].push(stacks[start].pop()); | |
} | |
function isLegal(start, finish) { | |
// get the last indicies of your start and finish stacks | |
var start_last_block_idx = stacks[start].length - 1 | |
var finish_last_block_idx = stacks[finish].length - 1 | |
// this will give us the block at the end of the start stack | |
var movingBlock = stacks[start][start_last_block_idx]; | |
// if the finish stack is empty, this will be undefined, otherwise it will | |
// give us the block at the last index of the finish stack | |
var comparingBlock = stacks[finish][finish_last_block_idx]; | |
// compare the blocks | |
if (movingBlock < comparingBlock || !comparingBlock) { | |
// if the moving block is less than the block it's going to stack on | |
// or if the finish stack is empty (hence the comparing block would be undefined) | |
// remember '!' in front of a value will give the opposite "truthiness" value | |
return true; | |
} | |
// otherwise return false. It is not a legal move | |
console.log ("Not a Legal Move"); | |
return false; | |
} | |
function gameOver() { | |
if (stacks['b'].length === 4 || stacks['c'].length === 4) { | |
console.log('You Won!!!') | |
return true; | |
} | |
return false; | |
} | |
function getPrompt() { | |
printStacks(); | |
prompt.get(['start', 'finish'], function (error, result) { | |
if (isLegal(result['start'], result['finish'])) { | |
movePiece(result['start'], result['finish']); | |
} | |
if (!gameOver()) { | |
getPrompt(); | |
} | |
}); | |
} | |
getPrompt(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment