22.10.12 μμ μκ° μ€ κ³΅λΆν λ΄μ©λ€μ μ 리νμμ΅λλ€ π
νΌλλ°±μ μΈμ λ νμμ λλ€! π
// λ³κ²½ μ
<div class="cards" data-id="1">?</div>
// λ³κ²½ μ΄ν
<div class="cards" data-id="1">
<div class="card-inner">
<div class="card-front">?</div>
<div class="card-back"></div>
</div>
</div>
.card-inner {
position: relative;
width: 100%;
height: 100%;
text-align: center;
transition: transform 0.5s;
transform-style: preserve-3d;
}
.cards.opened .card-inner {
transform: rotateY(180deg);
}
.card-front,
.card-back {
...
backface-visibility: hidden;
}
...
.card-back {
...
transform: rotateY(180deg);
}
π‘ μΆκ° μ§μ
- transform-style
μμμ μμμ΄ 3D 곡κ°μ λ°°μΉνλλ‘ νλ μμ±
- backface-visibility
μμμ λ·μͺ½μμ μλ©΄μ΄ λ³΄μ΄κ² ν μ§ λ§ μ§ κ²°μ νλ μμ±
- κΈ°λ³Έκ° : visible
- μμ : No
- μ λλ©μ΄μ
: NO
ν΄λ¦νμ λ, λ€μ§μ μ μλλ‘ κ΅¬ν
opened
classλ₯Ό ν κΈμμΌμ£Όμμ΅λλ€.μΉ΄λ 2μ₯μ΄ 1μμΌλ‘ μΌμΉνλμ§ μ¬λΆ νμΈ λ‘μ§ κ΅¬ν
μΉ΄λ λ€μ§μμ λ, μΌμΉνμ§ μλ μΉ΄λλ₯Ό λ€μ λ€μ§μ λ, setTimeoutμ μκ°μ΄ λλμ§ μμμ λ, λ€λ₯Έ μΉ΄λλ₯Ό λλ₯΄λ©΄ μΉ΄λκ° μΌμΉνμ§ μλλΌλ 2κ° μ΄μμ΄ μ΄λ¦¬λ λ¬Έμ κ° λ°μν¨.
// μ΄μ
let openCard = [];
const completedCard = [];
document.querySelector('.card-container').addEventListener('click', e => {
if (
!e.target.closest('.cards') ||
e.target.closest('.cards').classList.contains('opened')
)
return;
e.target.closest('.cards').classList.toggle('opened');
openCard.push(e.target.nextElementSibling);
if (openCard.length === 2) {
if (openCard[0].textContent === openCard[1].textContent) {
console.log('HOLYMOLY');
completedCard.push(openCard[0]);
completedCard.push(openCard[1]);
openCard = [];
} else {
console.log('TRY AGAIN');
setTimeout(() => {
openCard[0].closest('.cards').classList.remove('opened');
openCard[1].closest('.cards').classList.remove('opened');
openCard = [];
}, 500);
}
}
});
// μ΄ν
...
document.querySelector('.card-container').addEventListener('click', e => {
if (
!e.target.closest('.cards') ||
e.target.closest('.cards').classList.contains('opened') ||
openCard.length === 2
)
return;
e.target.closest('.cards').classList.toggle('opened');
...
});
μ΄μ μ μΉ΄λκ° 2κ° μ΄μ ν΄λ¦λμμ λ, setTimeoutμ μκ°μ΄ λλκΈ° μ μ λ€λ₯Έ μΉ΄λλ₯Ό ν΄λ¦νλ©΄, λ°°μ΄μ΄ μ΄κΈ°νλκΈ° μ μ openCard λ°°μ΄μ λ€λ₯Έ μμκ° μΆκ°λκΈ° λλ¬Έμ μκΈ°λ λ¬Έμ μ.
κ·Έλμ, μ μ΄μ openCard λ°°μ΄μ κΈΈμ΄λ₯Ό 2κ° λμ΄κ°μ§ μλλ‘, λ°°μ΄μ κΈΈμ΄κ° 2μΌ λ, early return μμΌμ£Όμ΄μ ν΄κ²°νμμ.
λλ€μΌλ‘ μ΄λ―Έμ§ / κΈμ λΏλ €μ£ΌκΈ°
π νΌμ μμ΄μΈ μ ν(Fisher-Yates Shuffle) μκ³ λ¦¬μ¦ μ΄μ©
function shuffle(array) { const copyArray = [...array]; for (let index = copyArray.length - 1; index > 0; index--) { const randomPosition = Math.floor(Math.random() * (index + 1)); [copyArray[index], copyArray[randomPosition]] = [copyArray[randomPosition], copyArray[index]]; } return copyArray; }