简体   繁体   中英

How to check if cards in hand match cards on table?

There are 8 cards on the table, with four faces visible and four hidden. Click on a card to turn it and if there's a pip-match or suit-match, show sparks around the associated cards.

Problem is, I'm either doing something wrong logic-wise, or .concat() is not working. Because some sparks show and some do not.

The whole game could probably be refactored into proper objects but that is beyond my current level (I've been learning JS for a month now). Framework used is RightJS. Posted the whole function for clarity's sake and a bit of context.

function pick(card) {
    var matches = [],
        pip = [],
        suit = [];

    //Check for matches
    ['card1', 'card2', 'card3', 'card4'].each(function (el) {
        if (hand[el].charAt(0) == 'j') {
            matches.push(card);
            matches.push(el);
        } //Joker
        else if (hand[card].charAt(1) == hand[el].charAt(1) || hand[card].charAt(0) == 'j') {
            matches.push(card);
            pip.push(el);
        } //Pip match
        else if (hand[card].charAt(0) == hand[el].charAt(0) || hand[card].charAt(0) == 'j') {
            matches.push(card);
            suit.push(el);
        } //Suit match
    });
    if (pip.length > suit.length) {
        matches.concat(pip);
    } else {
        matches.concat(suit);
    }

    //Hide old bling
    $$('.bling').each(function (el) {
        el.hide();
    });

    //Show bling
    if (matches.length > 0) {
        matches.each(function (el) {
            $(el).firstChild.show();
        });
    }

    //Show the card from hand
    $(card).setClass(hand[card]);
    turned++;

    // New turn if all have been clicked
    if (turned == 4) {
        turned = 0;
        newturn();
    }
}

The trick is to build your deck of cards first, and then remove cards from the deck as you hand them out. 😊

Below is one way of doing it with classes , Array.splice() and 52 cards. You draw a card with Deck.drawCard().

Here is a demo.

class Card {
  constructor(suit, value) {
    this.suit = suit;
    this.value = value;
  }
}

class Deck {
  constructor() {
    const suits = ["H", "D", "S", "C"];
    const values = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"];
    this.cards = [];
    suits.forEach(suit =>
      values.forEach(value => {
        const newCard = new Card(suit, value);
        this.cards.push(newCard);
      })
    );
  }
  drawCard() {
    if (!this.cards.length) return false;
    const cardIndex = Math.floor(Math.random() * this.cards.length);
    return this.cards.splice(cardIndex, 1)[0];
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM