soy nuevo en esto, quiero saber como puedo hacer para si no hay match, vaciar el array para que vuelva a chequear? Si hay match se quedan mostradas las dos, si no lo hay se devuelven, eso pasa solo una vez, no consigo que el juego tenga sentido
var box = document.getElementsByClassName('box')[0];
var all = [
{
pic: 'a.png',
name: 'circle'
},
{
pic: 'a.png',
name: 'circle'
},
{
pic: 'b.png',
name: 'square'
},
{
pic: 'b.png',
name: 'square'
},
{
pic: 'c.png',
name: 'star'
},
{
pic: 'c.png',
name: 'star'
},
{
pic: 'd.png',
name: 'moon'
},
{
pic: 'd.png',
name: 'moon'
},
{
pic: 'e.png',
name: 'heart'
},
{
pic: 'e.png',
name: 'heart'
},
{
pic: 'f.png',
name: 'star'
},
{
pic: 'f.png',
name: 'star'
}
];
var cardNodes =[];
var cardsInPlay =[];
let cardElement, cardId, random = all[Math.floor(Math.random()*all.length)];
// console.log(random[1]);
function createBoard(){
for (var i = 0; i < all.length - 1; i++) {
cardElement = document.createElement('img');
cardElement.setAttribute('src', 'images/back.png');
cardElement.setAttribute('data-id', i);
cardElement.style.width = '190px';
cardElement.style.height = '190px';
cardElement.style.margin = '20px';
box.appendChild(cardElement);
cardNodes.push(cardElement);
cardElement.onclick = backFlip;
}
}
createBoard();
function backFlip(){
cardId = this.getAttribute('data-id');
this.setAttribute('src', `images/${all[cardId].pic}`);
cardsInPlay.push(all[cardId].name);
// console.log(cardId, cardsInPlay);
// console.log(cardNodes);
checkForMatch();
}
function checkForMatch(){
if (cardsInPlay.length === 2) {
if (cardsInPlay[0] !== cardsInPlay[1]) {
setTimeout(function(){
cardNodes.map(x=>x.setAttribute('src', 'images/back.png'))
},1000);
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MEMORY GAME</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>MEMORY GAME</h1>
<p>This is a game in which you have to remember the position of the cards to match, you have a timer</p>
<div class="box">
</div>
<script src="app.js" charset="utf-8"></script>
</body>
</html>