我正在构建一个进化模拟应用程序,如果某个有机体的健康状况超过75%,它就会繁殖,然后将健康状况减去一半。为此,我创建了该对象所属类的新实例,然后将该对象推入存储其他生物的数组。由于我不知道的原因,这使p5.js崩溃。
我试图减少有机体的数量(3),并根据班级的情况来写。
var organisms = []; // array where organisms instances go
function reproduce(){
for (let i = 0; i < organisms.length; i++){
if(organisms[i].life > 0.75){
// create a genetically similar size
let size = organisms[i].size + (random() > 0.5 ? 1 : -1 * random() * 2);
// declare instance
let org = new Organism(width, height, size)
organisms.push(org);
// prevent infinite reproduction
organisms[i].life -= 0.5;
}
}
}
我希望这只会创建新的类实例,但是会使p5.js崩溃。
答案 0 :(得分:2)
遍历数组并创建新的生物,然后在循环之后将新创建的生物的数组添加到原始数组中。
这是一个可运行的代码段,它创建了一个最小的示例。问题中对方法random
的调用已替换为对Math.random()
的调用,并且声明了width
和height
以消除对p5.js的需求。
var organisms = []; // array where organisms instances go
var width = 100;
var height = 100;
function Organism(w, h, s){
this.width = w;
this.height = h;
this.size = s;
this.life = .76;
}
organisms.push(new Organism(1,1,1));
console.log("Organisms length before reproduce: " + organisms.length);
reproduce();
console.log("Oganisms length after reproduce: "+organisms.length);
function reproduce(){
var organismsToAdd = [];
for (let i = 0; i < organisms.length; i++){
if(organisms[i].life > 0.75){
// create a genetically similar size
let size = organisms[i].size + (Math.random() > 0.5 ? 1 : -1 * Math.random() * 2);
// declare instance
let org = new Organism(width, height, size)
organismsToAdd.push(org);
// prevent infinite reproduction
organisms[i].life -= 0.5;
}
}
//organisms = organisms.concat(organismsToAdd);
// or
organisms.push.apply(organisms, organismsToAdd)
}
这是带有p5.js的可运行代码段
var organisms = []; // array where organisms instances go
function setup(){
createCanvas(100,100);
organisms.push(new Organism(1,1,1));
noLoop();
}
function draw(){
console.log("Organisms length before reproduce: " + organisms.length);
reproduce();
console.log("Organisms length after reproduce: " + organisms.length);
}
function reproduce(){
var organismsToAdd = [];
for (let i = 0; i < organisms.length; i++){
if(organisms[i].life > 0.75){
// create a genetically similar size
let size = organisms[i].size + (random() > 0.5 ? 1 : -1 * random() * 2);
// declare instance
let org = new Organism(width, height, size)
organismsToAdd.push(org);
// prevent infinite reproduction
organisms[i].life -= 0.5;
}
}
// organisms = organisms.concat(organismsToAdd);
organisms.push.apply(organisms, organismsToAdd)
}
function Organism(w, h, s){
this.width = w;
this.height = h;
this.size = s;
this.life = .76;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.min.js"></script>
答案 1 :(得分:0)
您创建的循环条件可能永远不会结束。
for (let i = 0; i < organisms.length; i++){
在第一次迭代中,假设生物具有5个元素。如果满足下一行的if
条件,则将另一个元素添加到organisms
数组中。下一次迭代将更改organisms
中的下一个元素,但是由于数组每次都增加一个,因此您将永远无法到达数组的末尾!