js css html

进化的生态系统

2022-08-22  本文已影响0人  大龙10

书名:代码本色:用编程模拟自然系统
作者:Daniel Shiffman
译者:周晗彬
ISBN:978-7-115-36947-5
第9章目录

9.13 生态系统模拟

首先,我们要建立基因型和表现型。

1、基因型和表现型

class DNA {
    float[] genes;
    DNA() { 我们只需要一个变量,但这里却使用了数组,这是出于对后续扩展的考虑
    genes = new float[1];
    for (int i = 0; i < genes.length; i++) {
        genes[i] = random(0,1);
    }
}
class Bloop {
    PVector location;
    float health;
    DNA dna; bloop对象有DNA
    float r;
    float maxspeed;
    Bloop(DNA dna_) {
        location = new PVector(width/2,height/2);
        health = 200;
        dna = dna_;
        maxspeed = map(dna.genes[0], 0, 1, 15, 0); 将DNA中的基因映射为最大速度和半径
        r = map(dna.genes[0], 0, 1, 0, 50);
    }

2、选择和繁殖

Bloop reproduce() { 该函数返回子代bloop对象
    if (random(1) < 0.01) { 有1%的概率执行其中的代码,也就是有1%的繁殖机会
    // 创建新的bloop对象
    }
}
Bloop reproduce() {
    if (random(1) < 0.0005) {
        DNA childDNA = dna.copy(); 创建DNA的副本
        childDNA.mutate(0.01); 1%的突变率
        return new Bloop(location, childDNA); 在相同的位置,用新的DNA创建新的bloop对象
    } else {
        return null; 如果不繁殖新的bloop对象,就返回NULL
    }
}
class DNA {
    DNA copy() { copy()函数代替了之前的crossover()函数
        float[] newgenes = new float[genes.length]; 用相同的长度创建新数组,复制内容
        arraycopy(genes,newgenes);
        return new DNA(newgenes);
    }

3、示例

示例代码9-5 进化的生态系统(程序略)

上一篇 下一篇

猜你喜欢

热点阅读