I would like to know how to do so that the cards are returned IF THERE IS NO MATCH, the game draws cards random
once it is clicked. But I do not know why he tells me that mistake. The same if I do
cardsInPlay[0].setAttribute('src', 'images/back.png')
and
cardsInPlay[1].setAttribute('src', 'images/back.png')
does not work either. Also (in a primitive way) I tried to pass the this
as a parameter stored in a variable to be able to turn it over since it is the only way it works (BUT ONLY IT TURNS TO THE LAST LETTER TO WHICH I DO CLICK), I tried this since the envelope this
(the current element) is the only way to let me do setAttribute
, but I want both letters to turn over. I'm new to this, could someone help me? Thank you very much
//GLOBAL VARIABLES
var box = document.getElementById('box');
var cardElement;
var cardsInPlay= [];
var random;
//1. OBJETOS DE CARTAS EN ARRAY
var cards = [
{
rank: 'king',
pic: 'images/king-of-diamonds.png'
},
{
rank: 'king',
pic: 'images/king-of-hearts.png'
},
{
rank: 'queen',
pic: 'images/queen-of-diamonds.png'
},
{
rank: 'queen',
pic: 'images/queen-of-hearts.png'
}
];
//1. CREAR LA MESA
function createBoard(){
for (var i = 0; i < cards.length; i++) {
cardElement = document.createElement('img');
cardElement.setAttribute('src', 'images/back.png');
box.appendChild(cardElement);
cardElement.addEventListener('click', flipCardAndRandomize);
}
}
createBoard();
//2. DAR LA VUELTA A LAS CARTAS YA DE FORMA RANDOM
function flipCardAndRandomize(){
//Randomizar baraja =>
random = Math.floor(Math.random()*cards.length);
console.log(random);
this.setAttribute('src', cards[random].pic);
cardsInPlay.push(cards[random].rank);
var miThis = this;
match(miThis);
}
//3. VER SI HAY MATCH
function match(miThis){
if (cardsInPlay.length === 2) {
if (cardsInPlay[0] === cardsInPlay[1]) {
alert('MATCH');
} else {
alert('TRY AGAIN');
darVuelta(miThis);
// random.setAttribute('src', 'images/back.png'); //// QUIERO VOLTEAR DE NUEVO SI NO HAY MATCH
// random.setAttribute('src', 'images/back.png'); //// QUIERO VOLTEAR DE NUEVO SI NO HAY MATCH
}
}
function darVuelta(miThis){
miThis.setAttribute('src', 'images/back.png')
}
}
#box{
background-color: lightblue;
height: 250px;
width: 700px;
margin: 0 auto;
margin-top: 50px;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/style.css">
<meta charset="utf-8">
<title>CARDS</title>
</head>
<body>
<div id="box">
</div>
<script src="js/main.js" charset="utf-8"></script>
</body>
</html>