我正在使用 javascript/html5 编写纸牌游戏
我将游戏状态作为 ajax 请求。这是 JSON 数据,列出了玩家以及他们手中的牌
我正在尝试遍历每个玩家并将手牌数据设置如下
gameState.Players.forEach(function (player, i) {
var inx = i + 1;
var canvas = document.getElementById("player" + inx);
var ctx = canvas.getContext("2d");
var hand = Object.create(Hand);
hand.initialiseHand(player.Hand);
hand.setPosition(10, 10);
hand.draw(ctx);
});
页面上有六个画布。每个玩家一个
我正在使用 Object.create 创建一只手的新“实例”。然后调用 draw 方法,在画布上布置图像
然而,实际发生的是每个玩家数据只是被添加到同一个实例中
即每次我绕过forEach循环时,手对象只会被分配越来越多的卡片
我想为每个玩家提供一个单独的实例
那么我该如何实现呢?
我想循环数据并为循环的每次迭代创建一个新手
我猜手变量已被提升出循环,所以我每次都得到相同的变量?
这就是手的样子
var Hand = {
faceDownCards: [],
faceUpCards: [],
inHandCards: [],
initialiseHand: function (handData) {
handData.FaceDownCards.forEach(function (c, i) {
this.faceDownCards.push(Object.create(Card, pd({ rank: c.Rank, suit: c.Suit })));
}, this);
handData.FaceUpCards.forEach(function (c, i) {
this.faceUpCards.push(Object.create(Card, pd({ rank: c.Rank, suit: c.Suit })));
}, this);
handData.InHandCards.forEach(function (c, i) {
this.inHandCards.push(Object.create(Card, pd({ rank: c.Rank, suit: c.Suit })));
}, this);
},
draw: function (context) {
this.faceDownCards.forEach(function (c, i) {
c.draw(context);
});
this.faceUpCards.forEach(function (c, i) {
c.draw(context);
});
this.inHandCards.forEach(function (c, i) {
c.draw(context);
});
},
setPosition: function (x, y) {
this.x = x;
this.y = y;
this.faceDownCards.forEach(function (c, i) {
c.setPosition(x + i * 70, y);
});
this.faceUpCards.forEach(function (c, i) {
c.setPosition(x + i * 70, y + 60);
});
this.inHandCards.forEach(function (c, i) {
c.setPosition(x + i * 20, y + 80);
//c.rotation = 3;
});
}
};