+
+pub trait AppState {
+ fn update(&mut self, dt: Nanoseconds);
+ fn render(&self, canvas: &mut Canvas<Window>);
+ fn leave(&self);
+ fn on_event(&mut self, event: Event);
+}
+
+type Bollar = Vec<Box<dyn Boll>>;
+
+pub struct ActiveState {
+ bolls: Bollar,
+ boll_size: u32,
+}
+
+impl ActiveState {
+ fn new() -> ActiveState {
+ ActiveState {
+ bolls: Bollar::new(),
+ boll_size: 1,
+ }
+ }
+
+ fn change_boll_count(&mut self, delta: i32) {
+ if delta > 0 {
+ for _i in 0..delta {
+ self.add_boll();
+ }
+ } else if delta < 0 {
+ for _i in 0..delta {
+ self.bolls.pop();
+ }
+ }
+ }
+
+ fn add_boll(&mut self) {
+ let mut rng = rand::thread_rng();
+ self.bolls.push(Box::new(SquareBoll {
+ pos: point!(rng.gen_range(0, SCREEN_WIDTH) as f64, rng.gen_range(0, SCREEN_HEIGHT) as f64),
+ vel: point!(rng.gen_range(-2.0, 2.0), rng.gen_range(-2.0, 2.0)),
+ }));
+ }
+}
+
+impl AppState for ActiveState {
+ fn update(&mut self, dt: Nanoseconds) {
+ for mut b in &mut self.bolls {
+ b.update();
+ }
+
+ match dt {
+ ns if ns < (NS_PER_FRAME - 90_0000) as u64 => { self.change_boll_count(100) }
+ ns if ns > (NS_PER_FRAME + 90_0000) as u64 => { self.change_boll_count(-100) }
+ _ => {}
+ }
+ }
+
+ fn render(&self, canvas: &mut Canvas<Window>) {
+ for mut b in &self.bolls {
+ b.draw(canvas, self.boll_size);
+ }
+ }
+
+ fn leave(&self) {
+ println!("number of bolls: {}", self.bolls.len());
+ }
+
+ fn on_event(&mut self, event: Event) {
+ match event {
+ Event::KeyDown { keycode: Some(Keycode::KpPlus), .. } => { self.boll_size = std::cmp::min(self.boll_size + 1, 32) }
+ Event::KeyDown { keycode: Some(Keycode::KpMinus), .. } => { self.boll_size = std::cmp::max(self.boll_size - 1, 1) }
+ Event::MouseMotion { x, y, .. } => {
+ self.bolls.push(Box::new(CircleBoll::new(
+ point!(x as f64, y as f64),
+ point!(0.0, 0.0),
+ )))
+ }
+ _ => {}
+ }
+ }
+}