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 个蓝色,因此有蓝色套装和棕色套装。 拥有一套决定了玩家是否可以 build 属性(property)。当玩家购买位置时,我只需将“所有者”值从“无主”更新为“玩家名”。 我应该添加哪些属性来帮助确定玩家是否拥有一套。
最佳答案
如果您将位置作为数组而不是普通对象,会更方便。我们将使用 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
}
关于javascript - 垄断检查玩家是否拥有一套,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20848475/