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);
});
ページには 6 つのキャンバスがあります。各プレイヤーに 1 つ
Object.create を使用して、手の新しい「インスタンス」を作成しています。次に draw メソッドを呼び出し、キャンバス上に画像を配置します。
ただし、実際には、各プレイヤーのデータが同じインスタンスに追加されるだけです。
つまり、forEach ループを一周するたびに、hand オブジェクトに割り当てられるカードが増えていきます。
プレイヤーごとに個別のインスタンスを用意したい
では、どうすればこれを達成できますか?
データをループして、ループの反復ごとに新しい手を作成したい
ハンド変数がループから引き上げられたので、毎回同じものを取得していると思いますか?
これが手の外観です
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;
});
}
};