开发者

Loading an Array with Stack of Cards

I want a way to load 52 cards in an Array without having to hard code it. I have an array suits which contains "H" , "C" , "S" , "D" prefixes for each suit. I need to have a single array cards[52] with values H1-H13,S1-S13 etc. The problem i am facing is i c开发者_运维问答an load cards[0] to cards[12] fairly easily, but how do i load the next card in cards[13] ?


You can do something like this:

var suits = new Array("H", "C", "S", "D");
var cards = new Array();
// changed 3 to 4 to display all four suits
var cnt = 0;
for(i=0; i<4; i++)
    for(j=1; j<=13; j++)
        cards[cnt++] = suits[i] + j;


Try:

var suits = ["H", "C", "S", "D"], cards = [], n = 0;
while(n < 4){
    for(i = 1; i < 13; i++)
        cards.push(suits[n] + i);
    n++;
}


You can either load all 52 cards into a single array, as you were thinking:

var suits = ['H', 'C', 'S', 'D'];
var cards = [];
var suitIndex = 0;

for(var i = 0 i < 52; i++) {
  cards.push(suits[suitIndex] + (i % 13));

  // if remainder after division by 13 is zero, 
  // you know you've hit a multiple of 13 and need to switch suits.
  if (i % 13 == 0 && suitIndex < suits.length) {
    suitIndex++;
  }
}

Or you can create 4 different card arrays and switch to a different array when you fill one.


Frankly there isn't any good reason to generate the deck dynamically when you can do it faster and in just a few lines by hand:

var cards = [
  "H1", "H2", "H3",  "H4",  "H5",  "H6", "H7",
  "H8", "H9", "H10", "H11", "H12", "H13",
  "C1", "C2", "C3",  "C4",  "C5",  "C6", "C7",
  "C8", "C9", "C10", "C11", "C12", "C13",
  "S1", "S2", "S3",  "S4",  "S5",  "S6", "S7",
  "S8", "S9", "S10", "S11", "S12", "S13",
  "D1", "D2", "D3",  "D4",  "D5",  "D6", "D7",
  "D8", "D9", "D10", "D11", "D12", "D13"
]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜