简单纸牌游戏javascript中的indexOf问题

issue with indexOf in simple card game javascript

本文关键字:indexOf 问题 中的 javascript 纸牌游戏 简单      更新时间:2023-09-26

我想做一个非常简单的javascript卡牌游戏,但我有一个小问题,我似乎无法弄清楚。基本上,下面的代码应该是建立一副牌…这个问题在下面的代码中进行了注释,我有一个脚本,应该随机分配花色和值给卡,并将它们推入甲板数组。在if语句中的indexOf方法应该检查是否随机的卡已经被推到游戏甲板上,以防止重复的卡,但我似乎仍然得到重复。希望有人能给我指出正确的方向:

//selecting the cards types for the deck.
var cards = []; 
var numberedCards = [2, 3, 4, 5, 6, 7, 8, 9, 10];
var faceCards = ["Jack", "Queen", "King", "Ace"];
var suit = ["of hearts", "of diamonds", "of clubs", "of spades"];
while (!(cardOptions == "a" || cardOptions == "b" || cardOptions == "c")) {
    var cardOptions = prompt("What cards do you need? 'nType 'a', 'b', 'c'.'na. All cards 'nb. Face cards only 'nc. Numbered cards only");
    switch (cardOptions) {
        case "a":
            cards = numberedCards.concat(faceCards);
            break;
        case "b":
            cards = faceCards; 
            break;
        case "c":
            cards = numberedCards;
            break;
        default:
            alert("You have to choose one an option");
    }
    console.log("You have chosen cards " + cards + ". Let's add the suits to make your deck.");
}
//the following code is supposed to:
///Randomly assign suits to the cards and push the cards into array playingDeck.  
//"indexOf" is suppose to tell me if the randomCard is already in the playingDeck, but 
//I'm still getting duplicate cards.
var playingDeck = [];
do {
    var randomNumberCard = cards[Math.floor(Math.random()*cards.length)];
    var randomSuitCard = suit[Math.floor(Math.random()*suit.length)];
    var randomCard = [[randomNumberCard],[randomSuitCard]];
    if(playingDeck.indexOf(randomCard) === -1) {
        playingDeck.push(randomCard);
        continue;
    }
    else {
        continue;
    }
} while (playingDeck.length <= cards.length*suit.length - 1);
console.log(playingDeck);
console.log("ok, you now have " + playingDeck.length + " to play with.");

提前感谢任何帮助与此!

.indexOf()检查数组是否为字符串-在这种情况下,您正在尝试匹配数组对象(而不是字符串)。

你可以使用jQuery的$.inArray()方法,或者像这样迭代你的牌组:

var found = false;
for ( var card in playingDeck ) {
   if (card[0] == randomCard[0] && card[1] == randomCard[1] ) {
    found == true;
   }
}
if ( !found ) playingDeck.push(randomCard);