PixiJS: игра «жизнь» продолжение
В ходе наблюдения за жителями, заметил, что не очень хорошо смотрится рождение нового жителя, а именно он «рождается» в случайном месте карты. Не порядок. Пусть он рождается рядом с «мамой». Для этого изменим код генерации «нового жителя», чтобы можно было за ранее передавать координаты рождения жителя:
function GenerateNewCitizen(x,y){
resident=new People(randomIntFromInterval(0,1),1,randomIntFromInterval(1,100),professions.get(1));
graphics = new PIXI.Graphics();
graphics.beginFill(professions.get(1).color);
graphics.lineStyle(2, professions.get(1).color, 1);
graphics.beginFill(professions.get(1).color, 1);
graphics.drawCircle(0,0, 1);
graphics.position.set(x, y);
graphics.direction=randomIntFromInterval(0,360);
graphics.endFill();
graphics.resident=resident;
residents.push(graphics);
app.stage.addChild(residents[residents.length-1]);
}
И соотвественно «рождение» жителя:
// проверим, есть ли совпадение точек?
// если возраст от 18..50
// если полы противоположные
// то считаем что это "лябовь" и размножаемся
for (let j = 0; j < residents.length; j++) {
if (Math.round(residents[i].position.y)==Math.round(residents[j].position.y) &&
Math.round(residents[i].position.x)==Math.round(residents[j].position.x) && i!=j){
if (residents[i].resident.age>=18 && residents[i].resident.age<=50){
if (residents[j].resident.age>=18 && residents[j].resident.age<=50){
if (residents[j].resident.gender==0 && residents[i].resident.gender==1){
console.log("-это лябофь!");
x=residents[j].position.x+1;
y=residents[j].position.y+1;
GenerateNewCitizen(x,y);
}
}
}
};
};
И картинка стала выглядеть уже интереснее: жители стали «кучковаться», что логично — в тех местах где жителей больше они и рождаться стали чаще

Второй момент. Нужно как-то выделить возраст жителей. Может быть сделать более «старших» чуть толще?
if (residents[i].resident.age>0 && residents[i].resident.age<18){
residents[i].scale._x=1;
residents[i].scale._y=1;
};
if (residents[i].resident.age>18 && residents[i].resident.age<50){
residents[i].scale._x=1.5;
residents[i].scale._y=1.5;
};
if (residents[i].resident.age>50){
residents[i].scale._x=1.8;
residents[i].scale._y=1.8;
};

Еще нашел ошибку, оказывается не все жители умирали по достижении 120 лет. Поправил:
// прибавляем всем жителям по году жизни..
for (let i = 0; i < residents.length; i++) {
residents[i].resident.age++;
if (residents[i].resident.age>120){
residents.pop(residents[i]); // в 120 лет жизненный путь завершается..
};
};
После этого жители стали стремительно вымирать после примерно 30-50 прошедших «лет» и на «планете» остались одни трупы:

Гнетущее впечатление, планета заваленная трупами.. Всё таки сделаю чтоб они убирались при смерти, пришлось серьёзно переписать логику, избавившись от «теневого» массива
// перебираю каждого человека и двигаем его
for (let i = 0; i < app.stage.children.length; i++) {
if (app.stage.children[i].resident!==undefined){
// регулируем размер жителей
if (app.stage.children[i].resident.age>0 && app.stage.children[i].resident.age<18){
app.stage.children[i].scale._x=1;
app.stage.children[i].scale._y=1;
};
if (app.stage.children[i].resident.age>18 && app.stage.children[i].resident.age<50){
app.stage.children[i].scale._x=1.5;
app.stage.children[i].scale._y=1.5;
};
if (app.stage.children[i].resident.age>50){
app.stage.children[i].scale._x=1.8;
app.stage.children[i].scale._y=1.8;
};
//двигаем жителя (кудато идёт)
step=false;
while (step==false){
pre_y=app.stage.children[i].position.y+Math.sin(app.stage.children[i].direction);
pre_x=app.stage.children[i].position.x+Math.cos(app.stage.children[i].direction);
if ((pre_x>=0)&& (pre_x<=screen_width) && (pre_y>=0) && (pre_y<=screen_height)) {
step=true;
} else {
app.stage.children[i].direction=randomIntFromInterval(0,360);
};
};
app.stage.children[i].position.y=app.stage.children[i].position.y+Math.sin(app.stage.children[i].direction);
app.stage.children[i].position.x=app.stage.children[i].position.x+Math.cos(app.stage.children[i].direction);
// размножаемся
// проверим, есть ли совпадение точек?
// если возраст от 18..50
// если полы противоположные
// то считаем что это "лябовь" и размножаемся
for (let j = 0; j < app.stage.children.length; j++) {
if (app.stage.children[j].resident!==undefined){
if (Math.round(app.stage.children[i].position.y)==Math.round(app.stage.children[j].position.y) &&
Math.round(app.stage.children[i].position.x)==Math.round(app.stage.children[j].position.x) && i!=j){
if (app.stage.children[i].resident.age>=18 && app.stage.children[i].resident.age<=50){
if (app.stage.children[j].resident.age>=18 && app.stage.children[j].resident.age<=50){
if (app.stage.children[j].resident.gender==0 && app.stage.children[i].resident.gender==1){
console.log("-это лябофь!");
x=app.stage.children[j].position.x+1;
y=app.stage.children[j].position.y+1;
GenerateNewCitizen(x,y);
}
}
}
};
}
};
};
}
Осталось придумать что-то, что бы позволило не вымирать населению? Может быть повысить «рождаемость»? Пусть иногда рождаются двойни-тройни?
console.log("-это лябофь!");
for (let z = 0; z < randomIntFromInterval(0,3); z++) {
x=app.stage.children[j].position.x+1;
y=app.stage.children[j].position.y+1;
GenerateNewCitizen(x,y);
};
Не помогло. Нужно разрешить рожать от 16 лет до 55. Плюс не нравится мне, что умирают жители строго по дистежении 120 лет. А если сделать что умирать будут чем больше лет начиная от 70, тем чаще?
// прибавляем всем жителям по году жизни..
for (let i = 0; i < app.stage.children.length; i++) {
if (app.stage.children[i].resident!==undefined){
app.stage.children[i].resident.age++;
if (app.stage.children[i].resident.age>60){
if (randomIntFromInterval(121,app.stage.children[i].resident.age)==120){
console.log("- умер "+i+" по достижению "+app.stage.children[i].resident.age+" лет");
app.stage.removeChild(app.stage.children[i]);
};
};
}
};
Уже выглядит красивее, но всё равно жители вымирают..

Нужно попробовать сделать так, чтобы рожали чаще. Если ранее дети рождались, если жители оказались в одной и той же точке, то теперь сделаем, что дети будут рождаться, даже если родители оказались просто рядом..
function DiffuzeCompare(x,y,x1,y1){
res=false;
if (Math.abs(x-x1)<=2&&Math.abs(y-y1)<=2){
res=true;
}
return res;
};
if (DiffuzeCompare(app.stage.children[i].position.x,app.stage.children[i].position.y,app.stage.children[j].position.x,app.stage.children[j].position.y)==true) {
if (app.stage.children[i].resident.age>=16 && app.stage.children[i].resident.age<=55){
if (app.stage.children[j].resident.age>=16 && app.stage.children[j].resident.age<=55){
if (app.stage.children[j].resident.gender==0 && app.stage.children[i].resident.gender==1){
console.log("-это лябофь!");
for (let z = 0; z < randomIntFromInterval(0,3); z++) {
x=app.stage.children[j].position.x+1;
y=app.stage.children[j].position.y+1;
GenerateNewCitizen(x,y);
};
}
}
}
};
Вот теперь население стабильно стало расти. Теперь сделаем так, чтоб дети рождались только в роддоме:
if (buldings[bb].bulding_type.name=="Роддом"){
x=randomIntFromInterval(buldings[bb].xx,buldings[bb].xx+buldings[bb].ww);
y=randomIntFromInterval(buldings[bb].yy,buldings[bb].yy+buldings[bb].hh);
GenerateNewCitizen(x,y);
}
}
В итоге получили: