forked from AlgorithmsMeetup/TowersOfHanoi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
actions.js
57 lines (47 loc) · 1.58 KB
/
actions.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
var config = require("./config");
var display = require("./display");
var top = function(stack) {
return stack[stack.length - 1];
};
var checkMove = function(from, to) {
if (from < 0 || from >= config.columns) {
return display.error(["Cannot move from tower", from, "to tower", to, "because tower", from, "it does not exist"].join(" "));
}
if (to < 0 || to >= config.columns) {
return display.error(["Cannot move from tower", from, "to tower", to, "because tower", to, "it does not exist"].join(" "));
}
if (towers[from].length === 0) {
return display.error(["Cannot move from tower", from, "to tower", to, "because tower", from, "is empty"].join(" "));
}
if (top(towers[from]) > top(towers[to])) {
return display.error(["Cannot move from tower", from, "to tower", to, "because piece", top(towers[from]), "is larger than piece", top(towers[to])].join(" "));
}
};
var towers = [];
var i;
for (i = 0; i < config.columns; i++) {
towers.push([]);
}
for (i = config.pieces; i--;) {
var col = config.random ? Math.floor(Math.random()*config.columns) : 0;
towers[col].push(i + 1);
}
display.init(towers);
var actions = {};
actions.getBoard = function() {
return towers.map(function(t) {
return t.slice();
});
};
actions.move = function(from, to) {
checkMove(from, to);
towers[to].push(towers[from].pop());
display.towers(towers);
};
actions.finish = function() {
if (top(towers).length !== config.pieces) {
return display.error("You haven't finished yet - not all pieces are in the final stack");
}
display.victory();
};
module.exports = actions;