-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
76 lines (72 loc) · 2.2 KB
/
main.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
let table = document.querySelector(".table");
let stepsNumber = document.querySelector(".steps-number");
function shuffle(array) {
array.sort(() => Math.random() - 0.5);
}
let initialNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
shuffle(numbers);
let emptyIndex = numbers.findIndex((item) => {
return item === 9;
});
//alert(emptyIndex);
const reset = function () {
for (let i = 0; i < 3; i++) {
first = 3 * i;
second = 3 * i + 1;
third = 3 * i + 2;
table.innerHTML += `<tr class="row"><td class=${
first === emptyIndex ? "white" : "col"
}>${numbers[first]}</td><td class=${
second === emptyIndex ? "white" : "col"
}>${numbers[second]}</td><td class=${
third === emptyIndex ? "white" : "col"
}>${numbers[third]}</td></tr>`;
}
};
reset();
table.addEventListener("click", (event) => {
let target = Number(event.target.innerText);
let index = numbers.findIndex((item) => item === target);
if (checkAdjusency(index, emptyIndex)) {
switch (emptyIndex) {
case index - 1:
event.target.style = "transform:translateX(-200px);";
break;
case index + 1:
event.target.style = "transform:translateX(200px);";
break;
case index + 3:
event.target.style = "transform:translateY(200px);";
break;
case index - 3:
event.target.style = "transform:translateY(-200px);";
break;
}
let temp;
temp = numbers[index];
numbers[index] = numbers[emptyIndex];
numbers[emptyIndex] = temp;
emptyIndex = index;
setTimeout(() => {
stepsNumber.innerHTML = Number(stepsNumber.innerText) + 1;
table.innerHTML = "";
reset();
if (JSON.stringify(numbers) === JSON.stringify(initialNumbers)) {
alert("You Won!");
location.reload();
}
}, 1000);
}
});
let checkAdjusency = function (currentIndex, emptyIndex) {
let list = [0, 1, 2, 3, 4, 5, 6, 7, 8].filter(
(item) =>
item + 3 === emptyIndex ||
item - 3 === emptyIndex ||
(item - 1 === emptyIndex && ![0, 3, 6].includes(item)) ||
(item + 1 === emptyIndex && ![2, 5, 8].includes(item))
);
//alert(list);
return list.includes(currentIndex);
};