gpt4 book ai didi

javascript - 如何将对象添加到数组中但仅当数组的当前元素为 0 时?

转载 作者:行者123 更新时间:2023-11-30 11:20:47 26 4
gpt4 key购买 nike

我有下面的代码,当两个类 (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);

最佳答案

与其在每个玩家创建时随机分配一个 x/y,不如创建一个包含所有可能位置的列表,并为每个新玩家随机选择一个玩家实例。你有一个 8x8 的网格。所以有 64 个可能的位置

如果对于每个玩家,您:

  • 随机选择一个位置
  • 删除该位置

你永远不会有重叠。

var positions = [];
for(var x=0;x<8;x++){
for(var y=0;y<8;y++){
positions.push({x,y});
}
}

// pick 5 random positions for demo

for(var i=0;i<5;i++){
var rnd = Math.floor(Math.random()*positions.length);
console.log("random position chosen:", positions[rnd]);
//remove this so its not picked again
positions.splice(rnd,1);
}

应用于您的代码如下所示:

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, location){
this.id=id;
this.location = location;
}
}

var positions = [];
for(var x=0;x<8;x++){
for(var y=0;y<8;y++){
positions.push({x,y});
}
}

var play = new Game();
let player =[];
for (i=0; i <numOfPlayers; i++ ){
var rndPos = Math.floor(Math.random()*positions.length);
player.push(new Player(i, positions[rndPos]));
positions.splice(rndPos,1);
play.gameBoard[player[i].location.y][player[i].location.x] = player[i];
}

console.log(play);

如果有意义的话,您甚至可以考虑将 availablePositions 数组作为您的 Game 的属性。

关于javascript - 如何将对象添加到数组中但仅当数组的当前元素为 0 时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49915944/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com