-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathview.js
117 lines (95 loc) · 2.92 KB
/
view.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
var canvas = new fabric.Canvas('c');
var OFFSET = 4;
var img = {};
var interval;
var img_names = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"];
var field_diff = function (field_one, field_two) {
var diff = [];
if (field_one.length != field_two.length)
return;
for (var i = 0; i < field_one.length; i++) {
if (field_one[i] != field_two[i]) {
diff.push(i);
}
}
return diff;
};
var swap_img = function (from, to, timeout) {
var from_left = from.getLeft();
var from_top = from.getTop();
var to_left = to.getLeft();
var to_top = to.getTop();
from.animate('left', to_left, {
duration: timeout * 0.8,
onChange: canvas.renderAll.bind(canvas)
});
from.animate('top', to_top, {
duration: timeout * 0.8,
onChange: canvas.renderAll.bind(canvas)
});
to.animate('left', from_left, {
duration: timeout * 0.8,
onChange: canvas.renderAll.bind(canvas)
});
to.animate('top', from_top, {
duration: timeout * 0.8,
onChange: canvas.renderAll.bind(canvas)
});
};
var pause = function () {
clearInterval(interval);
interval = 0;
};
var new_field = function () {
var start_state = shuffle(15);
for (var i = 0; i < start_state.length; i++) {
var ind = start_state[i];
img[ind].left = (i % OFFSET) * 100;
img[ind].top = ~~(i / OFFSET) * 100;
canvas.add(img[ind]);
}
return start_state;
};
async.map(img_names, function (name, callback) {
fabric.Image.fromURL('img/' + name + '.png', function (oImg) {
callback(null, {name: name, img: oImg});
});
}, function (error, results) {
if (error)
console.log(error);
results.forEach(function (element) {
img[element.name] = element.img;
});
var field = new_field();
var start_bt = document.getElementById('start');
var pause_bt = document.getElementById('pause');
var restart_bt = document.getElementById('restart');
var j = 1;
var moves;
start_bt.onclick = function () {
if (j == 1) {
moves = start(field);
}
var current = moves[j - 1].state;
var timeout = 100;
interval = setInterval(function () {
var next = moves[j].state;
var change = field_diff(current, next);
var img1 = current[change[0]];
var img2 = current[change[1]];
swap_img(img[img1], img[img2], timeout);
current = next;
j++;
if (j == moves.length)
clearInterval(interval);
}, timeout);
};
pause_bt.onclick = function () {
pause();
};
restart_bt.onclick = function () {
pause();
field = new_field();
j = 1;
}
});