roguelike-game/src/damage_system.rs

68 lines
2.0 KiB
Rust
Raw Normal View History

2021-11-16 10:28:05 -05:00
use crate::components::{CombatStats, Name, Player, SufferDamage};
use crate::{game_log::GameLog, Map, Position, RunState};
2021-10-29 15:15:22 -04:00
use specs::prelude::*;
pub struct DamageSystem {}
impl<'a> System<'a> for DamageSystem {
type SystemData = (
WriteStorage<'a, CombatStats>,
WriteStorage<'a, SufferDamage>,
2021-11-16 10:28:05 -05:00
ReadStorage<'a, Position>,
WriteExpect<'a, Map>,
Entities<'a>,
2021-10-29 15:15:22 -04:00
);
fn run(&mut self, data: Self::SystemData) {
2021-11-16 10:28:05 -05:00
let (mut stats, mut damage, positions, mut map, entities) = data;
2021-10-29 15:15:22 -04:00
2021-11-16 10:28:05 -05:00
for (entity, mut stats, damage) in (&entities, &mut stats, &damage).join() {
2021-10-29 15:15:22 -04:00
stats.hp -= damage.amount.iter().sum::<i32>();
2021-11-16 10:28:05 -05:00
if let Some(pos) = positions.get(entity) {
let idx = map.xy_idx(pos.x, pos.y);
map.bloodstains.insert(idx);
}
2021-10-29 15:15:22 -04:00
}
damage.clear();
}
}
pub fn delete_the_dead(ecs: &mut World) {
let mut dead: Vec<Entity> = Vec::new();
// Scope for the sake of the borrow checker
{
let combat_stats = ecs.read_storage::<CombatStats>();
let players = ecs.read_storage::<Player>();
let names = ecs.read_storage::<Name>();
2021-10-29 15:15:22 -04:00
let entities = ecs.entities();
let mut log = ecs.write_resource::<GameLog>();
2021-10-29 15:15:22 -04:00
for (entity, stats) in (&entities, &combat_stats).join() {
if stats.hp < 1 {
let player = players.get(entity);
match player {
None => {
if let Some(victim_name) = names.get(entity) {
log.append(format!("{} is dead", &victim_name.name));
}
dead.push(entity)
}
2021-11-15 13:27:40 -05:00
Some(_) => {
let mut runstate = ecs.write_resource::<RunState>();
*runstate = RunState::GameOver;
}
2021-10-29 15:15:22 -04:00
}
}
}
}
for victim in dead {
ecs.delete_entity(victim)
.expect("Unable to delete the dead");
}
}