melee_combat_system.rs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. extern crate specs;
  2. use specs::prelude::*;
  3. use super::{CombatStats, WantsToMelee, Name, SufferDamage, gamelog::GameLog, MeleePowerBonus, DefenseBonus, Equipped};
  4. pub struct MeleeCombatSystem {}
  5. impl<'a> System<'a> for MeleeCombatSystem {
  6. #[allow(clippy::type_complexity)]
  7. type SystemData = ( Entities<'a>,
  8. WriteExpect<'a, GameLog>,
  9. WriteStorage<'a, WantsToMelee>,
  10. ReadStorage<'a, Name>,
  11. ReadStorage<'a, CombatStats>,
  12. WriteStorage<'a, SufferDamage>,
  13. ReadStorage<'a, MeleePowerBonus>,
  14. ReadStorage<'a, DefenseBonus>,
  15. ReadStorage<'a, Equipped>
  16. );
  17. fn run(&mut self, data : Self::SystemData) {
  18. let (entities, mut log, mut wants_melee, names, combat_stats, mut inflict_damage, melee_power_bonuses, defense_bonuses, equipped) = data;
  19. for (entity, wants_melee, name, stats) in (&entities, &wants_melee, &names, &combat_stats).join() {
  20. if stats.hp > 0 {
  21. let mut offensive_bonus = 0;
  22. for (_item_entity, power_bonus, equipped_by) in (&entities, &melee_power_bonuses, &equipped).join() {
  23. if equipped_by.owner == entity {
  24. offensive_bonus += power_bonus.power;
  25. }
  26. }
  27. let target_stats = combat_stats.get(wants_melee.target).unwrap();
  28. if target_stats.hp > 0 {
  29. let target_name = names.get(wants_melee.target).unwrap();
  30. let mut defensive_bonus = 0;
  31. for (_item_entity, defense_bonus, equipped_by) in (&entities, &defense_bonuses, &equipped).join() {
  32. if equipped_by.owner == wants_melee.target {
  33. defensive_bonus += defense_bonus.defense;
  34. }
  35. }
  36. let damage = i32::max(0, (stats.power + offensive_bonus) - (target_stats.defense + defensive_bonus));
  37. if damage == 0 {
  38. log.entries.insert(0, format!("{} is unable to hurt {}", &name.name, &target_name.name));
  39. } else {
  40. log.entries.insert(0, format!("{} hits {}, for {} hp.", &name.name, &target_name.name, damage));
  41. inflict_damage.insert(wants_melee.target, SufferDamage{ amount: damage }).expect("Unable to do damage");
  42. }
  43. }
  44. }
  45. }
  46. wants_melee.clear();
  47. }
  48. }