我正在尝试制作一个非常简单的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.");
提前感谢您对此的任何帮助!
答案 0 :(得分:0)
.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);