开发者

accessing local variables within another function

Here is the code I have written:

function p_deal(id) {
    var card1_val = Math.floor(Math.random() * deck.length);
    var card2_val = Math.floor(Math.random() * deck.length);
        var card1 = deck[card1_val];
        var card2 = deck[card2_v开发者_StackOverflowal];
    var hand = card1 + ", " + card2;
var res = card1_val + card2_val;

document.getElementById(id).innerHTML = hand;

and

function hit(id) {
    if (bucket == 0) {
        bucket = " ";
    }

    var card3_val = Math.floor(Math.random() * deck.length);
    var nhand = deck[card3_val];
    bucket = bucket + " " + nhand + ", ";
    bucket_val = bucket_val + card1_val + card2_val + card3_val;

    if (bucket_val >= 22) {
        var r = confirm("Bust! By " + nhand);
        if (r == true) {
            refresh();
        }
        else {
            refresh();
        }
    }

    document.getElementById(id).innerHTML = bucket;

    light = light + 1;

    if (light == 5) {
        alert("Five Card Blackjack! You Win!");
        refresh();
    }
}

The card_val variables within bucket val are from the p_deal(id) function. In order for the program to work, the card_val values must be the same each time both functions are called but they need to be regenerated each time the function is called (so multiple players can have different hands). However, as local variables I find it difficult to use them in another function. What can i do here?


Looks like you want an object:

function Hand(id) {
    this.elem = document.getElementById(id);
    this.bucket = "";
    this.bucketVal = 0;
    this.deal = function() {
        this.card1 = Math.floor(Math.random() * deck.length);
        this.card2 = Math.floor(Math.random() * deck.length);
        this.elem.innerHTML = deck[this.card1] + ', ' + this.card2;
    }
    this.hit = function() {

        var newCard = Math.floor(Math.random() * deck.length);
        this.bucket += " " + deck[nhand] + ", ";
        this.bucketVal += this.card1 + this.card2 + newCard;

        if (this.bucketVal >= 22) {
            var r = confirm("Bust! By " + nhand);

            refresh();
        }

        this.elem.innerHTML = this.bucket;

        light = light + 1;

        if (light == 5) {
            alert("Five Card Blackjack! You Win!");
            refresh();
        }
    }
}

var player1Hand = new Hand('player1Id');
player1Hand.deal();
player1Hand.hit();


easy way: make them global or pass them between the functions

harder but more advisable way: use objects instead and make those variable attributes of the object.


Make them global variables rather than local variables.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜