如何根据用户输入多次实例化一个类?

时间:2018-04-18 10:29:38

标签: javascript loops class instantiation

我试图创建一个棋盘游戏,并希望根据用户提供的多次实例化Human类。显然,我试图为每个对象分配一个不同的ID,并且以下循环不能用于实例化玩家的数量:

var question = prompt('how many players');
var numOfPlayers = parseInt(question);

class Human {
  constructor (id) {
    this.id = id;
    this.health = 100;
    this.hammer = false
    this.knife = false;
    this.sword = false;
    this.baseballbat = false;
    this.damage = 0;
    this.location = {
      x: Math.floor(Math.random() * 8),
      y: Math.floor(Math.random() * 8)
    }
  }

  moveTo(x, y){
    this.location.x += x;
    this.location.y += y;
  }
}

var i;
for (i = 0; i < numOfPlayers; i++) {
    const player = new Human(id = i);
}

2 个答案:

答案 0 :(得分:2)

首先,我希望我已经明白你要在这里实现的目标。 &#34; const播放器的范围&#34;在循环内是有限的。如果您希望能够在循环外访问它,则需要同样声明列表/数组。

代码可能会像这样:

var players = [];
for(let i = 0; i < numOfPlayers; i++) {
    players.push(new Human(i));
}

注意:如果您不想使用变量&#39; i&#39;在循环之外,你可以在里面声明它&#39; for&#39;使用&#39;让&#39;关键字可以在上面的代码中看到。

答案 1 :(得分:0)

class Human {
    constructor (id){
        this.id = id;
        this.health = 100;
        this.hammer = false
        this.knife = false;
        this.sword = false;
        this.baseballbat = false;
        this.damage = 0;
        this.location = {
            x:Math.floor(Math.random()*8),
            y:Math.floor(Math.random()*8)
        }

        console.log(`Human created with id of ${id}`); //Remove this just to show you that your class is being instantiated for each 'player'
    }

    moveTo(x,y){
        this.location.x += x;
        this.location.y += y;
    }
}

let numOfPlayers = prompt('How many players?');

const _init = () => {
    if(parseInt(numOfPlayers) > 0) {
        for (let i = 0; i < numOfPlayers; i++) {
            new Human(i)
        }
    }
}

_init();