monster_ai_system.rs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. extern crate specs;
  2. use specs::prelude::*;
  3. use super::{Viewshed, Monster, Map, Position, WantsToMelee, RunState, Confusion, particle_system::ParticleBuilder};
  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. WriteExpect<'a, ParticleBuilder>);
  20. fn run(&mut self, data : Self::SystemData) {
  21. let (mut map, player_pos, player_entity, runstate, entities, mut viewshed,
  22. monster, mut position, mut wants_to_melee, mut confused, mut particle_builder) = data;
  23. if *runstate != RunState::MonsterTurn { return; }
  24. for (entity, mut viewshed,_monster,mut pos) in (&entities, &mut viewshed, &monster, &mut position).join() {
  25. let mut can_act = true;
  26. let is_confused = confused.get_mut(entity);
  27. if let Some(i_am_confused) = is_confused {
  28. i_am_confused.turns -= 1;
  29. if i_am_confused.turns < 1 {
  30. confused.remove(entity);
  31. }
  32. can_act = false;
  33. particle_builder.request(pos.x, pos.y, rltk::RGB::named(rltk::MAGENTA),
  34. rltk::RGB::named(rltk::BLACK), rltk::to_cp437('?'), 200.0);
  35. }
  36. if can_act {
  37. let distance = rltk::DistanceAlg::Pythagoras.distance2d(Point::new(pos.x, pos.y), *player_pos);
  38. if distance < 1.5 {
  39. wants_to_melee.insert(entity, WantsToMelee{ target: *player_entity }).expect("Unable to insert attack");
  40. }
  41. else if viewshed.visible_tiles.contains(&*player_pos) {
  42. // Path to the player
  43. let path = rltk::a_star_search(
  44. map.xy_idx(pos.x, pos.y) as i32,
  45. map.xy_idx(player_pos.x, player_pos.y) as i32,
  46. &mut *map
  47. );
  48. if path.success && path.steps.len()>1 {
  49. let mut idx = map.xy_idx(pos.x, pos.y);
  50. map.blocked[idx] = false;
  51. pos.x = path.steps[1] % map.width;
  52. pos.y = path.steps[1] / map.width;
  53. idx = map.xy_idx(pos.x, pos.y);
  54. map.blocked[idx] = true;
  55. viewshed.dirty = true;
  56. }
  57. }
  58. }
  59. }
  60. }
  61. }