-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
106 lines (88 loc) · 2.81 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
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
class Card {
_open = false
_success = false
constructor(container, number, action) {
this.card = document.createElement('div');
this.card.classList.add('card');
this.card.textContent = number;
this.number = number;
this.card.addEventListener('click', () => {
if(this.open == false && this.success == false) {
this.open = true;
action(this);
}
});
container.append(this.card);
}
set open(value) {
this._open = value;
value ? this.card.classList.add('open') : this.card.classList.remove('open');
}
get open() {
return this._open;
}
set success(value) {
this._success = value;
value ? this.card.classList.add('success') : this.card.classList.remove('success');
}
get success() {
return this._success;
}
}
function flip(card) {
console.log(card);
}
function newGame(container, cardsCount) {
cardsCount = cardsCount;
let cardsNumberArray = [];
let cardsArray = [];
let firstCard = null;
let secondCard = null;
for(let i = 1; i <= cardsCount / 2; i++) {
cardsNumberArray.push(i);
cardsNumberArray.push(i);
}
cardsNumberArray = cardsNumberArray.sort(() => Math.random() - 0.5);
for(const cardNumber of cardsNumberArray) {
cardsArray.push(new Card(container, cardNumber, flip));
}
function flip(card) {
if(firstCard !== null && secondCard !== null) {
if(firstCard.number != secondCard.number) {
firstCard.open = false;
secondCard.open = false;
firstCard = null;
secondCard = null;
}
}
if(firstCard == null) {
firstCard = card;
} else {
if (secondCard == null) {
secondCard = card;
}
}
if(firstCard !== null && secondCard !== null) {
if(firstCard.number == secondCard.number) {
firstCard.success = true;
secondCard.success = true;
firstCard = null;
secondCard = null;
}
}
if(document.querySelectorAll('.card.success').length == cardsNumberArray.length) {
setTimeout(function win() {
alert('You win!');
}, 500);
setTimeout(function clean() {
container.innerHTML = '';
let cardsNumberArray = [];
let cardsArray = [];
let firstCard = null;
let secondCard = null;
newGame(container, cardsCount);
}, 1000);
}
}
}
newGame(document.getElementById('game'), 10);