继承和多态

2022-05-11  本文已影响0人  大龙10

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

4.6 继承和多态的简介

1、继承和多态

2、贺卡粒子系统

class HappyConfetti {
}
class FunConfetti {
}
class WackyConfetti {
}
class ParticleSystem {
    ParticleSystem(int num) {
        particles = new ArrayList();
        for (int i = 0; i < num; i++) {
            float r = random(1);
            随机选择一种粒子
            if (r < 0.33) { particles.add(new HappyConfetti()); }
            else if (r < 0.67) { particles.add(new FunConfetti()); }
            else { particles.add(new WackyConfetti()); }
      }
}

3、两个问题

ArrayList<HappyConfetti> a1 = new ArrayList<HappyConfetti>();
ArrayList<FunConfetti> a2 = new ArrayList<FunConfetti>();
ArrayList<WackyConfetti> a3 = new ArrayList<WackyConfetti>();

4、碎裂

ParticleSystem ps;

void setup() {
  size(640,360);
  ps = new ParticleSystem(200,100,8);
}

void draw() {
  background(255);

  ps.display();
  ps.update();
}

void mousePressed() {
  ps.shatter(); 
}

Particle.pde

class Particle {
  PVector position;
  PVector velocity;
  PVector acceleration;
  float lifespan;
  
  float r;
  color c;
  
  Particle(float x, float y, float r_) {
    acceleration = new PVector(0,0.01);
    velocity = PVector.random2D();
    velocity.mult(0.5);
    position = new PVector(x,y);
    lifespan = 255.0;
    r = r_;
  }

  void run() {
    update();
    display();
  }

  // Method to update position
  void update() {
    velocity.add(acceleration);
    position.add(velocity);
    lifespan -= 2.0;
    c = color(random(255),random(255),random(255));
  }

  // Method to display
  void display() {
    stroke(0);
    fill(c);
    rectMode(CENTER);
    rect(position.x,position.y,r,r);
  }
  
  // Is the particle still useful?
  boolean isDead() {
    if (lifespan < 0.0) {
      return true;
    } else {
      return false;
    }
  }
}

ParticleSystem.pde

class ParticleSystem {
  ArrayList<Particle> particles;

  int rows = 20;
  int cols = 20;

  boolean intact = true;

  ParticleSystem(float x, float y, float r) {
    particles = new ArrayList<Particle>();

    for (int i = 0; i < rows*cols; i++) {
      addParticle(x + (i%cols)*r, y + (i/rows)*r, r);
    }
  }

  void addParticle(float x, float y, float r) {
    particles.add(new Particle(x, y, r));
  }

  void display() {
    for (Particle p : particles) {
      p.display();
    }
  }

  void shatter() {
    intact = false;
  }

  void update() {
    if (!intact) {
      for (Particle p : particles) {
        p.update();
      }
    }
  }
}

5、运行结果

上一篇下一篇

猜你喜欢

热点阅读