【发布时间】:2014-06-19 03:19:57
【问题描述】:
我正在尝试制作一个非常简单的 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 用于查找复杂对象,您应该提供您的实现。在这里查看讨论stackoverflow.com/questions?page=2&sort=newest
-
很抱歉,但我不确定我是否理解您所说的实现的意思,这是对 javascript 类的介绍,这是迄今为止我必须展示的唯一代码。跨度>
标签: javascript if-statement indexof