开发者

Problems writing script for blackjack game

I'm trying to write a script for a Black Jack game but have run into some problems. This is the code I've included in the head:

<script type="text/javascript">
var J = 10;
var Q = 10;
var K = 10;
var A = 11;
var deck = [1,2,3,4,5,6,7,8,9,10,J,Q,K,A];

function deal() {
var test = "hello";
var f_card = Math.floor(Math.random() * deck.length);
var s_card = Math.floor(Math.random() * deck.length);
var card1 = deck[f_card];
var card2 = deck[s_card];

if (card1 == J) {
    card1 = "Jack";
    }
else if (card1 == Q) {
    card1 = "Queen";
    }
else if (card1 == K) {
    card1 = "King"
    }
else if (card1 == A) {
    card1 = "Ace"
    }

if (card2 == J) {
    card2 = "Jack";
    }
else if (card2 == Q) {
 开发者_运维问答   card2 = "Queen";
    }
else if (card2 == K) {
    card2 = "King"
    }
else if (card2 == A) {
    card2 = "Ace"
    }

var bucket = card1 + ", " + card2;
var res = f_card + s_card
document.getElementById("result").innerHTML = bucket;
document.getElementById("test").innerHTML = f_card + ", " + s_card;
if (res == 22) {
    alert("Blackjack!")
    }
}
</script>

The body reads as follows:

<body>
<form>
    <input type="button" value ="Deal" onclick="deal()" /><br /><br />
</form>
<div id = "result">
</div><br />
<div id = "test">
</div>
</body>

I added the "test" div to see what was happening inside the deal, and it looks like "Jack" is being assigned to all array value above 9. How can I have the other if statements processed as well? Any help at all would be much appreciated.


Put your J,Q,K,A in quotes:

var deck = [1,2,3,4,5,6,7,8,9,10,'J','Q','K','A'];

if (card1 == 'J') {
    card1 = "Jack";
    }

etc..


if (card1 == J) {
    card1 = "Jack";
    }
else if (card1 == Q) {
    card1 = "Queen";
    }
else if (card1 == K) {
    card1 = "King"
    }

Lets say you have a card == 10 (Jack / Queen / King)

You test with ifs.

the first if is hit because 10 == J

Even if it is a Queen / King (which also == 10)

Because the Jack is hit in the if statement the other ifs dont get run


Instead of card1 and card2 in if else ladder use "original card ID", ie

switch (f_card){
  case 10: card1 = "Jack";
           break;
  case 11: card1 = "Queen";
           break;
  case 12: card1 = "King";
           break;
  case 13: card1 = "Ace";
           break;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜