-
Notifications
You must be signed in to change notification settings - Fork 2
/
TowersOfHanoi.js
71 lines (61 loc) · 1.93 KB
/
TowersOfHanoi.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
'use strict';
$(function(){
$('.header').load("../header.html");
var gameover = false;
var $stacks = $('[data-stack]');
var $blocks = $('[data-block]');
//since only last child of every stack is allowed to make the move, give them class movable
var $movableBlocks = $('[data-block]:last-child');
$movableBlocks.addClass("movable");
//any block is draggable, but they rever to original position unless condition is met
$blocks.draggable({
revert: true
});
//only when droppable is true, can a movable block be dropped
$stacks.droppable({
accept: ".movable",
drop: function(event, ui) {
if(!gameover){
if(goodToDrop($(this), ui.draggable)) {
ui.draggable.draggable('option', 'revert', false);
$(this).append(ui.draggable.detach());
ui.draggable.css({'top': 0, 'left': 0});
//reset things
$movableBlocks = $('[data-block]:last-child');
$('[data-block]').removeClass("movable");
$movableBlocks.addClass("movable");
$blocks.draggable({
revert: true
});
//checkForWin
checkForWin();
}
}
else {
resetGame();
}
}
});
function goodToDrop($stack, $block) {
var $last_block = $stack.children().last();
if( parseInt($block.attr("data-block"))<parseInt($last_block.attr("data-block")) || $stack.children().length===0) {
return true;
}
else {
return false;
}
}
function checkForWin() {
if($('[data-stack="3"]').children().length===4) {
$('#announce-game-won').html("You Won!");
gameover=true;
}
}
function resetGame() {
$('[data-stack="1"]').html('<div data-block="100"></div><div data-block="75"></div><div data-block="50"></div><div data-block="25"></div>');
$('[data-stack="2"]').empty();
$('[data-stack="3"]').empty();
$('#announce-game-won').empty();
gameover = false;
}
});