asteroids-genetic/src/world.rs

72 lines
2.2 KiB
Rust
Raw Normal View History

2022-10-08 19:47:47 +00:00
use crate::{
asteroids::{Asteroid, AsteroidSize},
player::Player,
};
2022-10-08 15:27:05 +00:00
use macroquad::{prelude::*, rand::gen_range};
#[derive(Default)]
pub struct World {
player: Player,
asteroids: Vec<Asteroid>,
}
impl World {
pub fn new() -> Self {
Self {
player: Player::new(),
..Default::default()
}
}
pub fn update(&mut self) {
self.player.update();
2022-10-08 20:17:06 +00:00
let mut to_add: Vec<Asteroid> = Vec::new();
2022-10-08 15:27:05 +00:00
for asteroid in &mut self.asteroids {
asteroid.update();
2022-10-08 20:17:06 +00:00
if self.player.check_bullet_collisions(asteroid) {
match asteroid.size {
AsteroidSize::Large => {
let rand = vec2(gen_range(-50., 50.), gen_range(-50., 50.));
to_add.push(Asteroid::new_from(
asteroid.pos,
asteroid.vel + rand,
AsteroidSize::Medium,
));
to_add.push(Asteroid::new_from(
asteroid.pos,
asteroid.vel - rand,
AsteroidSize::Medium,
));
}
AsteroidSize::Medium => {
let rand = vec2(gen_range(-30., 30.), gen_range(-30., 30.));
to_add.push(Asteroid::new_from(
asteroid.pos,
asteroid.vel + rand,
AsteroidSize::Small,
));
to_add.push(Asteroid::new_from(
asteroid.pos,
asteroid.vel - rand,
AsteroidSize::Small,
));
}
_ => {}
}
}
2022-10-08 15:27:05 +00:00
}
2022-10-08 20:17:06 +00:00
self.asteroids.append(&mut to_add);
2022-10-08 19:47:47 +00:00
self.asteroids.retain(|asteroid| asteroid.alive);
2022-10-08 15:27:05 +00:00
if self.asteroids.len() < 5 {
2022-10-08 19:47:47 +00:00
self.asteroids.push(Asteroid::new(AsteroidSize::Large));
2022-10-08 15:27:05 +00:00
}
}
pub fn draw(&self) {
self.player.draw();
for asteroid in &self.asteroids {
asteroid.draw();
}
}
}