use ::rltk::RandomNumberGenerator; use ::specs::prelude::*; use crate::components::{ Equipped, InBackpack, LootTable, Name, Player, Pools, Position, SufferDamage, }; use crate::game_log::GameLog; use crate::raws::{get_item_drop, spawn_named_item, SpawnType, RAWS}; use crate::{Map, RunState}; pub struct DamageSystem {} impl<'a> System<'a> for DamageSystem { type SystemData = ( WriteStorage<'a, Pools>, WriteStorage<'a, SufferDamage>, ReadStorage<'a, Position>, WriteExpect<'a, Map>, Entities<'a>, ); fn run(&mut self, data: Self::SystemData) { let (mut stats, mut damage, positions, mut map, entities) = data; for (entity, mut stats, damage) in (&entities, &mut stats, &damage).join() { stats.hit_points.current -= damage.amount.iter().sum::(); if let Some(pos) = positions.get(entity) { let idx = map.xy_idx(pos.x, pos.y); map.bloodstains.insert(idx); } } damage.clear(); } } pub fn delete_the_dead(ecs: &mut World) { let mut dead: Vec = Vec::new(); // Scope for the sake of the borrow checker { let combat_stats = ecs.read_storage::(); let players = ecs.read_storage::(); let names = ecs.read_storage::(); let entities = ecs.entities(); let mut log = ecs.write_resource::(); for (entity, stats) in (&entities, &combat_stats).join() { if stats.hit_points.current < 1 { match players.get(entity) { None => { if let Some(victim_name) = names.get(entity) { log.append(format!("{} is dead", &victim_name.name)); } dead.push(entity) } Some(_) => { let mut runstate = ecs.write_resource::(); *runstate = RunState::GameOver; } } } } } // Drop everything held by dead people let mut to_spawn: Vec<(String, Position)> = Vec::new(); { // To avoid hold of borrowed entires, use a scope let mut to_drop: Vec<(Entity, Position)> = Vec::new(); let entities = ecs.entities(); let mut equipped = ecs.write_storage::(); let mut carried = ecs.write_storage::(); let mut positions = ecs.write_storage::(); let loot_tables = ecs.read_storage::(); let mut rng = ecs.write_resource::(); for victim in dead.iter() { let pos = positions.get(*victim); for (entity, equipped) in (&entities, &equipped).join() { if equipped.owner == *victim { // Drop their stuff if let Some(pos) = pos { to_drop.push((entity, *pos)); } } } for (entity, backpack) in (&entities, &carried).join() { if backpack.owner == *victim { // Drop their stuff if let Some(pos) = pos { to_drop.push((entity, *pos)); } } } if let Some(table) = loot_tables.get(*victim) { let drop_finder = get_item_drop(&crate::raws::RAWS.lock().unwrap(), &mut rng, &table.table); if let Some(tag) = drop_finder { if let Some(pos) = pos { to_spawn.push((tag, *pos)); } } } } for drop in to_drop.iter() { equipped.remove(drop.0); carried.remove(drop.0); positions .insert(drop.0, drop.1) .expect("Unable to insert position"); } } { for drop in to_spawn.iter() { spawn_named_item( &RAWS.lock().unwrap(), ecs, &drop.0, SpawnType::AtPosition { x: drop.1.x, y: drop.1.y, }, ); } } for victim in dead { ecs.delete_entity(victim) .expect("Unable to delete the dead"); } }