我正在开发一款简单的纸牌游戏,现在我生成卡片然后在屏幕上显示它们。显示卡后,它将从数组中删除(array.shift())。代码工作正常但只有一半的数组。 总共有36张卡,我只能显示和转移18张卡。
如果我删除deckOfCards.shift();从drawCard功能,然后我可以显示所有36张卡。
我需要能够显示所有36张卡,并将它们全部从阵列中显示出来。 我无法看到问题所在,以及为什么array.shift()仅适用于数组的一半。非常感谢任何帮助!
这是我的HTML:
<p id="cardsLeft">here</p>
<div id="comp" class="area">Computer Cards Here</div>
<div id="play" class="area">Play Cards Here</div>
<div id="human" class="area">Human Cards Here</div>
<input type="button" onclick="drawCard(humanPlayer)" value="Human Card" id="humanCard" />
<input type="button" onclick="drawCard(compPlayer)" value="Computer Card" id="compPlayer" />
我在这里创建卡片
function Card(suit, value, rnum){
this.suit = suit;
this.value = value;
this.rnum = rnum;
};
//Create array to hold Cards
var deckOfCards = [];
//Generate cards and push them into array
for(suit = 0; suit < 4; suit++){
for (value = 6; value <=14; value++){
var rnum = Math.floor(Math.random()*36+1);
deckOfCards.push(new Card(suit,value,rnum));
};
};
//Sorting deck of cards by rnum to shuffle cards.
deckOfCards.sort(function (a, b) {
if (a.rnum > b.rnum) {
return 1;
}
if (a.rnum < b.rnum) {
return -1;
}
// a must be equal to b
return 0;
});
这里开始实际的功能,给我带来麻烦
function drawCard(player) {
var divPlayer = "";//creating div to find correct div in html
if (player === compPlayer){
divPlayer = "comp";
}else{
divPlayer = "human";
};
var ni = document.getElementById(divPlayer); //finds correct div based on passed parameter
var numi = document.getElementById('theValue'); //theValue is used to generate ids for divs
var num = (document.getElementById('theValue').value-1)+2; //counter to keep track of how many cards has been assigned
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my'+num+'Div';
newdiv.setAttribute('id',divIdName);
//Converting suite values into strings
var suit = '';
switch(deckOfCards[num].suit){
case 0: suit = "spades";
break;
case 1: suit = "diamonds" ;
break;
case 2: suit = "hearts";
break;
case 3: suit = "clubs";
break;
};
//assign corresponding image to newly created div
newdiv.innerHTML = '<img src="img/SVG/'+deckOfCards[num].value+'_of_'+suit+'.svg" class="card" alt="Card">';
ni.appendChild(newdiv);
问题在于:
deckOfCards.shift(); //removes only first 18 cards from array of 36 cards
document.getElementById('cardsLeft').innerHTML = deckOfCards.length; //counter of how many cards are left in the deck
}
答案 0 :(得分:1)
你的问题在于声明
switch(deckOfCards[num].suit){
如果您想使用unshift()
,num
应替换0
。
第二种解决方案是根本不打电话给.unshift()
。
<强>解释强>
Function Array.shift()删除数组中的第一个值。
假设我们有一系列索引:
var num = 0;
var cards = [1, 2, 3, 4, 5, 6, 7, 8, /*...*/ 36];
// cards[num] == 1
致电cards.unshift()
后,卡片的价值为:
cards == [2, 3, 4, 5, 6, 7, 8, /*...*/ 36]
但您的代码也会增加num
变量:
// num == 1
// cards[num] == 3
因此跳过了值2
。