【发布时间】:2018-09-29 15:42:02
【问题描述】:
我有下面的代码,当两个类 (Player,Game) 被实例化时,特定数量的玩家被插入到 Player.gameBoard 数组中。仅当数组元素为 0 时,我才尝试将 Player 类添加到数组中。因此,如果将 Player 对象插入到 gameboard[0][0] 位置,则没有其他玩家可以覆盖他。目前,如果选择大量玩家(例如 20 个),其中一些会被覆盖,并且不会全部出现。所以我认为while循环有问题。
var question = prompt('how many players');
var numOfPlayers = parseInt(question);
class Game {
constructor(){
this.health = 100;
this.hammer = false
this.knife = false;
this.sword = false;
this.baseballbat = false;
this.damage = 0;
this.gameBoard = [
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
];
}
}
class Player {
constructor(id){
this.id=id;
this.location = {
x:Math.floor(Math.random()*8),
y:Math.floor(Math.random()*8)
};
}
}
var play = new Game();
let player =[];
for (i=0; i <numOfPlayers; i++ ){
player.push(new Player(i));
while (play.gameBoard[player[i].location.y][player[i].location.x]===0){
play.gameBoard[player[i].location.y][player[i].location.x] = player[i];
}
}
console.log(play);
【问题讨论】:
-
您的
while循环仅在空间为空时执行,但如果它不为空,则不会为玩家生成新坐标,因此它会被跳过/不会出现在网格。 -
玩家会得到一个随机的
x/y- 如果该空间被其他玩家占据,你想发生什么? -
重新运行 Math.floor(Math.random()*8) 以获取坐标
-
那么它不应该在
Player的构造函数中,而是在初始化循环中完成(并分配给播放器)
标签: javascript arrays object while-loop