src/damage_system.rs
1	use specs::prelude::*;
2 use super::{CombatStats, SufferDamage, Player, GameLog, Name, RunState, Position, Map};
3
4 pub struct DamageSystem {}
5
6 impl<'a> System<'a> for DamageSystem {
7 type SystemData = ( WriteStorage<'a, CombatStats>,
8 WriteStorage<'a, SufferDamage>,
9 ReadStorage<'a, Position>,
10 WriteExpect<'a, Map>,
11 Entities<'a> );
12
13 fn run(&mut self, data : Self::SystemData) {
14 let (mut stats, mut damage, positions, mut map, entities) = data;
15
16 for (entity, mut stats, damage) in (&entities, &mut stats, &damage).join() {
17 stats.hp -= damage.amount.iter().sum::<i32>();
18 let pos = positions.get(entity);
19 if let Some(pos) = pos {
20 let idx = map.xy_idx(pos.x, pos.y);
21 map.bloodstains.insert(idx);
22 }
23 }
24
25 damage.clear();
26 }
27 }
28
29 pub fn delete_the_dead(ecs : &mut World) {
30 let mut dead : Vec<Entity> = Vec::new();
31 // Using a scope to make the borrow checker happy
32 {
33 let combat_stats = ecs.read_storage::<CombatStats>();
34 let players = ecs.read_storage::<Player>();
35 let entities = ecs.entities();
36 let names = ecs.read_storage::<Name>();
37 let mut log = ecs.write_resource::<GameLog>();
38
39 for (entity, stats) in (&entities, &combat_stats).join() {
40 if stats.hp < 1 {
41 let player = players.get(entity);
42 match player {
43 None => {
44 let victim_name = names.get(entity);
45 if let Some(victim_name) = victim_name {
46 log.entries.push(format!("{} is dead", &victim_name.name));
47 }
48 dead.push(entity);
49 },
50 Some(_) => {
51 let mut runstate = ecs.write_resource::<RunState>();
52 *runstate = RunState::GameOver;
53 }
54 }
55 }
56 }
57 }
58
59 for victim in dead {
60 ecs.delete_entity(victim).expect("Unable to delete");
61 }
62 }