monster_ai_system.rs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. extern crate specs;
  2. use specs::prelude::*;
  3. use super::{Viewshed, Monster, Map, Position, WantsToMelee, RunState, Confusion};
  4. extern crate rltk;
  5. use rltk::{Point};
  6. pub struct MonsterAI {}
  7. impl<'a> System<'a> for MonsterAI {
  8. #[allow(clippy::type_complexity)]
  9. type SystemData = ( WriteExpect<'a, Map>,
  10. ReadExpect<'a, Point>,
  11. ReadExpect<'a, Entity>,
  12. ReadExpect<'a, RunState>,
  13. Entities<'a>,
  14. WriteStorage<'a, Viewshed>,
  15. ReadStorage<'a, Monster>,
  16. WriteStorage<'a, Position>,
  17. WriteStorage<'a, WantsToMelee>,
  18. WriteStorage<'a, Confusion>);
  19. fn run(&mut self, data : Self::SystemData) {
  20. let (mut map, player_pos, player_entity, runstate, entities, mut viewshed, monster, mut position, mut wants_to_melee, mut confused) = data;
  21. if *runstate != RunState::MonsterTurn { return; }
  22. for (entity, mut viewshed,_monster,mut pos) in (&entities, &mut viewshed, &monster, &mut position).join() {
  23. let mut can_act = true;
  24. let is_confused = confused.get_mut(entity);
  25. if let Some(i_am_confused) = is_confused {
  26. i_am_confused.turns -= 1;
  27. if i_am_confused.turns < 1 {
  28. confused.remove(entity);
  29. }
  30. can_act = false;
  31. }
  32. if can_act {
  33. let distance = rltk::DistanceAlg::Pythagoras.distance2d(Point::new(pos.x, pos.y), *player_pos);
  34. if distance < 1.5 {
  35. wants_to_melee.insert(entity, WantsToMelee{ target: *player_entity }).expect("Unable to insert attack");
  36. }
  37. else if viewshed.visible_tiles.contains(&*player_pos) {
  38. // Path to the player
  39. let path = rltk::a_star_search(
  40. map.xy_idx(pos.x, pos.y) as i32,
  41. map.xy_idx(player_pos.x, player_pos.y) as i32,
  42. &mut *map
  43. );
  44. if path.success && path.steps.len()>1 {
  45. let mut idx = map.xy_idx(pos.x, pos.y);
  46. map.blocked[idx] = false;
  47. pos.x = path.steps[1] % map.width;
  48. pos.y = path.steps[1] / map.width;
  49. idx = map.xy_idx(pos.x, pos.y);
  50. map.blocked[idx] = true;
  51. viewshed.dirty = true;
  52. }
  53. }
  54. }
  55. }
  56. }
  57. }