交互式选择

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

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

9.12 交互式选择

1、评分系统

class DNA {
    float[] genes;
    int len = 20; 为了画出这张脸,我们需要20个基因
    DNA() {
        genes = new float[len];
        for (int i = 0; i < genes.length; i++) {
                genes[i] = random(0,1); 每个基因都是介于0~1的随机浮点数
        }
    }
}
class Face {
    DNA dna;
    float fitness;
void display() {
    float r = map(dna.genes[0],0,1,0,70); 用map()函数将基因转化为绘制参数
    color c = color(dna.genes[1],dna.genes[2],dna.genes[3]);
    float eye_y = map(dna.genes[4],0,1,0,5);
    float eye_x = map(dna.genes[5],0,1,0,10);
    float eye_size = map(dna.genes[5],0,1,0,10);
    color eyecolor = color(dna.genes[4],dna.genes[5],dna.genes[6]);
    color mouthColor = color(dna.genes[7],dna.genes[8],dna.genes[9]);
    float mouth_y = map(dna.genes[5],0,1,0,25);
    float mouth_x = map(dna.genes[5],0,1,-25,25);
    float mouthw = map(dna.genes[5],0,1,0,50);
    float mouthh = map(dna.genes[5],0,1,0,10);
}

2、示例代码9-4 交互式选择

Population population;
Button button;
void setup() {
        size(780,200);
        float mutationRate = 0.05;
        population = new Population(mutationRate,10);
        button = new Button(15,150,160,20, "evolve new generation");
}

void draw() {
    population.display();
    population.rollover(mouseX,mouseY); 将鼠标位置传入population对象的rollover()函数,以
    button.display();
}
void mousePressed() {
    if (button.clicked(mouseX,mouseY)) { 一旦按钮被按下,就通过选择和繁殖创建下一代
        population.selection();
        population.reproduction();
  }
}
上一篇 下一篇

猜你喜欢

热点阅读