1

我正在使用 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;
        });
    }
};
4

1 回答 1

1

您的手变量没有被提升到循环之外。Javascript 变量具有函数作用域,您已经在 forEach 循环中方便地使用了函数。


是什么Hand?通常的约定是大写的名称代表构造函数,但是 Players 和 Object.create 让它看起来Hand只是一个对象?

如果Hand已经是一个对象(而不是您滥用的构造函数),我最好的选择是 initializeHand/setPosition 正在设置封闭变量,而不是通过this. (当然,这只是不看Hand代码的胡乱猜测)


查看您的Hand代码后,我现在认为问题在于双手正在共享faceDownCards等数组。基本原型应仅用于共享特征,并且应在初始化时设置数组和其他 instance-olny 状态:

举个具体的例子,改变

handData.FaceDownCards.forEach(function (c, i) {
    this.faceDownCards.push(Object.create(Card, pd({ rank: c.Rank, suit: c.Suit })));
}, this);

 this.faceDownCards = handData.FaceDownCards.map(function (c, i) {
     return Object.create(Card, pd({ rank: c.Rank, suit: c.Suit }));
 });

ps.:所有的 Object.create 都不是完全地道的 Javascript。但是,我想你应该对你在做什么有一个想法,对吧?

于 2011-09-11T17:47:57.073 回答