View difference between Paste ID: EqKLt944 and vJnwkuaw
SHOW: | | - or go back to the newest paste.
1
function Card(suit, number) {
2
    var suit = suit;
3
    var number = number;
4
    
5
    this.getNumber = function() {
6
        return number;
7
    }
8
9
    this.getSuit = function() {
10
        return suit;
11
    }
12
    
13
    this.getValue = function() {
14
        if (number == 1) {
15
            return 11;
16
        } else if (number > 10) {
17
            return 10;
18
        } else {
19
            return number;
20
        }
21
    }
22
}
23
24
function Hand() {
25
    var hand = [deal(), deal()];
26
    
27
    this.getHand = function() {
28
        return hand;
29
    }
30
    
31
    this.hitMe = function() {
32
        hand.push(deal());
33
    }
34
    
35
    this.printHand = function() {
36
        var string = "";
37
        for (var i = 0; i < hand.length; i++) {
38
            string += hand[i].getNumber() + " of suit " + hand[i].getSuit();
39
            if (i < (hand.length - 1)) {
40
                string += ", ";
41
            }
42
        }
43
        return string;
44
    }
45
    
46
    this.score = function() {
47
        var aces = 0;
48
        var sum = 0;
49
        for (var i = 0; i < hand.length; i++) {
50
            sum += hand[i].getValue();
51
            if (hand[i].getValue() == 11) {
52
                aces++;
53
            }
54
        }
55
        while (aces > 0 && sum > 21) {
56
            aces--;
57
            sum -= 10;
58
        }
59
        return sum;
60
    }
61
}
62
63
function deal() {
64-
    var suit = Math.floor(Math.random ( ) * 4 + 1);
64+
    var suit = Math.floor(Math.random( ) * 4 + 1);
65-
    var number = Math.floor(Math.random ( ) * 13 + 1);
65+
    var number = Math.floor(Math.random( ) * 13 + 1);
66
    return new Card(suit, number);
67
}
68
69
function playAsDealer() {
70
    var hand = new Hand();
71-
    while (hand.getScore() < 17) {
71+
    while (hand.score() < 17) {
72
        hand.hitMe();
73
    }
74
    return hand;
75
}
76
77
function playAsUser() {
78
    var hand = new Hand();
79
    var decision = confirm("Your hand is "+ hand.printHand() + ": Hit OK to hit (take another card) or Cancel to stand");
80
    while(decision) {
81
        hand.hitMe();
82
        decision = confirm("Your hand is "+ hand.printHand() + ": Hit OK to hit (take another card) or Cancel to stand");
83
    }
84
    return hand;
85
}