垄断检查玩家是否拥有一套

2024-01-26

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() and 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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

垄断检查玩家是否拥有一套 的相关文章

随机推荐