monster_ai_system.rs 2.0 KB

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