0

I draw pairs of cards from a deck of 9 then store the higher valued card and discard the other. When only 1 card remains it is automatically picked as one half of the next pair and I randomly pick the second from a newly refilled deck. This all works fine. However, the second time through, the deck is even (ending with 0 cards) so I should just reset the deck without autopicking the first card but for some reason when I try the array remains empty despite me duplicating the same line I use to refill the deck the first time. I know the code block is running because I've put a flag variable there that is being triggered. Any ideas?

//Global Vars
var deckRefill = [1,1,1,1,1,1,4,4,4];
var deck = [1,1,1,1,1,1,4,4,4];
var playHistory = [];
var discardPile = [];
var cardsPlayed = -1; //So first card played is index 0 in playHistory array
var refillFlag = 0; //Shows refill was triggered

function simGame(turns) {

var i;

for (i = 0; i < turns; i++) {

playCard();

}

//return refillFlag;
//return playHistory;
return deck.length;

}


function playCard() {

if (deck.length == 0) {



}

if (deck.length > 1) {

var draw1 =0;
var draw2 =0;

draw1 = deck.splice(Math.floor(Math.random()*deck.length), 1);
draw2 = deck.splice(Math.floor(Math.random()*deck.length), 1);

   if (draw1 > draw2) {

   playHistory.push(draw1);
   
   } else {
   
   playHistory.push(draw2);
   
   }
} else if (deck.length == 1) {

      var draw1 = deck[0];
      var draw2 =0;
      deck = deckRefill;
      
      draw2 = deck.splice(Math.floor(Math.random()*deck.length), 1);
      
      if (draw1 > draw2) {
  
     playHistory.push(draw1); 
     
     } else {
     
     playHistory.push(draw2);
     
     }
   } else {
   
   deck = deckRefill;
   refillFlag = 1;
   
   }

cardsPlayed = cardsPlayed+1;
return playHistory[cardsPlayed];


}
nll_ptr
  • 864
  • 8
  • 11
bulkhed
  • 21
  • 2
  • `deck = deckRefill;` doesn't make a copy of the array, the two variables now refer to the same array, and you're taking cards out of `deckRefill`. – Barmar Jan 24 '20 at 17:28
  • 2
    Use `deck = deckRefill.slice()` to make a copy. – Barmar Jan 24 '20 at 17:29

0 Answers0