使用JS BlackJack应用程序并遇到一些问题。我有mar deck(卡阵),我的面卡有定义的值。我为每个玩家随机选择卡片,它会添加并显示卡片值,但我希望能够为每个卡片显示卡片img。所以,我无法区分黑/白脸卡。
var j = 10;
var q = 10;
var k = 10;
var cards = [2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, j, j, j, j, q, q, q, q, k, k, k, k, a, a, a, a];
function processIt() {
//player's hand
var player = document.getElementById("player");
var card1 = (Math.floor(Math.random() * cards.length));
var card2 = (Math.floor(Math.random() * cards.length));
totalPlayer = cards[card1] + cards[card2];
cardDisplayP = cards[card1] + " " + cards[card2];
player.innerHTML = cardDisplayP + "<br />" + "Total: " + totalPlayer;
所以,有什么办法可以调用var而不是数组中的值吗? 即我想要:
show var.cards[46] = k;
cards[46] = 10;
答案 0 :(得分:1)
您应该创建构造函数或对象以包含有关卡的数据,而不是依赖于数组中的位置。以下是构造函数的示例:
var Suit = {
Hearts: 0,
Diamonds: 1,
Clubs: 2,
Spades: 3,
'0': '♥',
'1': '♦',
'2': '♣',
'3': '♠'
};
if(Object.freeze) {
Object.freeze(Suit);
}
function Card(suit, value) {
this.suit = suit;
this.value = value;
}
Card.faceValue = function(value) {
if(value > 1 && value < 11) {
return value.toString();
} else if(value === 1) {
return 'A';
} else {
return ['J', 'Q', 'K'][value % 10 - 1];
}
};
Card.prototype.toString = function() {
return Card.faceValue(this.value) + Suit[this.suit];
};
function Deck() {
for(var value = 1; value <= 13; value++) {
for(var suit = 0; suit < 4; suit++) {
this.push(new Card(suit, value));
}
}
}
Deck.prototype = [];
Deck.prototype.constructor = Deck;
Deck.prototype.shuffle = function() {
this.sort(function() {
return Math.random() - 0.5;
});
};
var d = new Deck();
d.shuffle();
document.write(d);
Deck
继承自数组,因此您只需使用.pop()
即可获得顶级卡片。