1 use specs::prelude::*;
2 use super::{Viewshed, Monster, Map, Position, WantsToMelee, RunState};
3 use rltk::{Point};
4
5 pub struct MonsterAI {}
6
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
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) = 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 distance = rltk::DistanceAlg::Pythagoras.distance2d(Point::new(pos.x, pos.y), *player_pos);
24 if distance < 1.5 {
25 wants_to_melee.insert(entity, WantsToMelee{ target: *player_entity }).expect("Unable to insert attack");
26 }
27 else if viewshed.visible_tiles.contains(&*player_pos) {
28 // Path to the player
29 let path = rltk::a_star_search(
30 map.xy_idx(pos.x, pos.y),
31 map.xy_idx(player_pos.x, player_pos.y),
32 &mut *map
33 );
34 if path.success && path.steps.len()>1 {
35 let mut idx = map.xy_idx(pos.x, pos.y);
36 map.blocked[idx] = false;
37 pos.x = path.steps[1] as i32 % map.width;
38 pos.y = path.steps[1] as i32 / map.width;
39 idx = map.xy_idx(pos.x, pos.y);
40 map.blocked[idx] = true;
41 viewshed.dirty = true;
42 }
43 }
44 }
45 }
46 }