I'm developing a simple card game, for now i generate cards and then display them on the screen. Once the card is displayed, it is removed from the array (array.shift()). The code works fine but only for half of the array. In total there are 36 cards, i can display and shift only 18 cards.
If I remove deckOfCards.shift(); from drawCard function, then I can display all 36 cards.
I need to be able to display all 36 cards and remove them all from the array as they appear on screen. I can't see where lies the problem and why array.shift() works only for half of the array. Any help is greatly appreciated!
Here is my 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" />
Here i create cards
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;
});
And here starts the actual function which gives me trouble
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);
And here is the problem:
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
}