In my card game the player can play once from their hand at the start of their turn. They can play a card on its own or paired with another card of the same suit. I currently have this loop for selecting and playing the cards:
export function selectionLoop() {
let selectedCardImg = elements.selectedCard;
for (var i = 0; i < selectedCardImg.length; i++) {
//add event listener to each card
selectedCardImg[i].addEventListener("click", function () {
//test for the class selected
if (this.classList.contains("selected")) {
//if the img does have the selected class and is clicked, remove the class and remove the corresponding DOMTokenList from the selectedCards array
this.classList.remove("selected");
selectedCardsImg.shift(this.classList);
selectedCards.shift();
//if the img doesn't have the selected class AND the selectedCardsImg array contains no cards, add the selected class to the img and push the DOMTokenList into the selectedCardsImg array
} else if (!this.classList.contains("selected") && selectedCardsImg.length < 1) {
this.classList.add("selected");
selectedCardsImg.push(this.classList);
//gets the corresponding card object from its classname in DOMTokenlist and pushes it into selectedCards array
pushIntoSelected();
//renders the cards in the selectedCards array to the slot the player has clicked on
UIC.renderCardInSlot();
console.log(selectedCards);
//if the img doesn't have the selected class AND the selectedCardsImg array contains 1 card, adds the selected class to the img and pushes the DOMTokenList into SelectedCardsImg
} else if (!this.classList.contains("selected") && selectedCardsImg.length == 1) {
this.classList.add("selected");
selectedCardsImg.push(this.classList);
emptySelected();
// removes the corresponding card object from playerHand array and pushes into the selectedCards array
pushIntoSelected();
//if the suits of both cards match
if (selectedCards[0].suit === selectedCards[1].suit) {
console.log(`suits match`);
console.log(selectedCards);
} else {
//if the suits don't match
alert("suits must match");
//remove the cards from the selectedCards array
emptySelected();
//remove the card imgs from the selectedCardsImg array
selectedCardsImg.splice(0, 2);
//remove the selected class from the selected cards
document.getElementsByClassName("selected")[0].classList.remove("selected");
console.log(selectedCards);
}
}
})
}
}
If the player chooses to play 2 cards, it works. However if the player chooses to play 1 card, they can still select more cards. How can I stop the player being able to select cards after playing one?
Aucun commentaire:
Enregistrer un commentaire