players = {
    player1: {
        currentpos: 0,
        prevpos: 0,
        startpos: 0,
        balance: 1500
    },
    player2: {
        currentpos: 0,
        prevpos: 0,
        startpos: 0,
        balance: 1500
    }
};
positions = {
    position1: {
        title: "Cairo",
        type: "brown",
        owner: "unowned",
        purchaseprice: 60,
        rentprice: 2,
        forsale: "y"
    },
    position2: {
        title: "Schiphol Airport",
        type: "airport",
        owner: "unowned",
        purchaseprice: 200,
        rentprice: 25,
        forsale: "y"
    },
    position3: {
        title: "Vienna",
        type: "brown",
        owner: "unowned",
        purchaseprice: 60,
        rentprice: 4,
        forsale: "y"
    },
    position6: {
        title: "Brussels",
        type: "blue",
        owner: "unowned",
        purchaseprice: 100,
        rentprice: 6,
        forsale: "y"
    }
};


我想知道一个球员是否拥有一套。例如2个布朗做成一组。设置3个蓝调即可。
    一个玩家可以拥有1套以上。他可以拥有2个棕色和3个蓝色,因此可以拥有蓝色和棕色。
    拥有布景决定了玩家是否可以建立属性。在玩家购买职位的时刻,我只是将“所有者”值从“无人”更新为“玩家名”。
    我应该添加哪些属性以帮助确定玩家是否拥有一组。

最佳答案

如果您将自己的位置作为数组而不是普通对象,那将更加方便。我们将在内部使用map()对其进行隐蔽,因此可以使用诸如filter()every()之类的数组方法:

function doesOwnSet(player, type) {
    // we'll use "chaining" here, so every next method will be called upon
    // what previous method have returned

    // `return` statement will return the result of the very last method

    // first, lets take an array of `position` object keys
    // which are "position1", "position2" and so on
    return Object.keys(positions)

        // then, create an array of positions object
        // this will return Array
        .map(function (key) {
            return positions[key];
        })

        // then, pick up only positions with specified type (aka set)
        // this will return Array
        .filter(function (pos) {
            return pos.type === type;
        })

        // finally, check if specified player owns every position of the set
        // this will return Boolean
        .every(function (pos) {
            return pos.owner === player;
        });
}


您可以在if语句中使用此功能,如下所示:

if (doesOwnSet(players.player1, 'brown')) {
    // give some reward to player1
}

10-07 23:19