From b98ea15acbebe8815f9316b5a8ef3393fdd1c3e6 Mon Sep 17 00:00:00 2001 From: troido Date: Tue, 3 Mar 2020 16:28:19 +0100 Subject: monsters tend to stay around their home --- src/systems/controlai.rs | 39 +++++++++++++++++++++++---------------- 1 file changed, 23 insertions(+), 16 deletions(-) (limited to 'src/systems/controlai.rs') diff --git a/src/systems/controlai.rs b/src/systems/controlai.rs index 9d49b41..debe716 100644 --- a/src/systems/controlai.rs +++ b/src/systems/controlai.rs @@ -12,7 +12,8 @@ use specs::{ use crate::{ components::{Controller, ControlCooldown, Fighter, MonsterAI, Home, Health, Position}, - controls::{Control, Direction::{North, South, East, West}} + controls::{Control, Direction::{self, North, South, East, West}}, + Pos }; @@ -50,15 +51,7 @@ impl <'a> System<'a> for ControlAI { if closest_distance <= fighter.range { controllers.insert(entity, Controller{control: Control::AttackTarget(target)}).unwrap(); } else { - let p = position.pos; - let t = closest_position.unwrap().pos; - let mut directions = Vec::new(); - if t.x > p.x {directions.push(East);} - else if t.x < p.x {directions.push(West);} - if t.y > p.y {directions.push(South);} - else if t.y < p.y {directions.push(North);} - if !directions.is_empty() { - let direction = directions[rand::thread_rng().gen_range(0, directions.len())]; + if let Some(direction) = step_to(position.pos, closest_position.unwrap().pos){ controllers.insert(entity, Controller{control: Control::Move(direction)}).unwrap(); } } @@ -66,16 +59,30 @@ impl <'a> System<'a> for ControlAI { } } if rand::thread_rng().gen_range(0.0, 1.0) < ai.move_chance { + if let Some(home) = homes.get(entity) { + if rand::thread_rng().gen_range(0.0, 1.0) < ai.homesickness * (position.pos.distance_to(home.home) as f64) { + let direction = step_to(position.pos, home.home).unwrap(); + controllers.insert(entity, Controller{control: Control::Move(direction)}).unwrap(); + return; + } + } let direction = [North, South, East, West][rand::thread_rng().gen_range(0, 4)]; controllers.insert(entity, Controller{control: Control::Move(direction)}).unwrap(); -// home = roomData.getComponent(obj, Home) -// if home is not None and home.home.inRoom() and random.random() < (ai.homesickness * pathfinding.distanceBetween(obj, home.home)): -// direction = pathfinding.stepTo(obj, home.home) -// else: -// direction = random.choice(["north", "south", "east", "west"]) -// movable.direction = direction } } } } +fn step_to(p: Pos, t: Pos) -> Option { + let mut directions = Vec::new(); + if t.x > p.x {directions.push(East);} + else if t.x < p.x {directions.push(West);} + if t.y > p.y {directions.push(South);} + else if t.y < p.y {directions.push(North);} + if directions.is_empty() { + None + } else { + Some(directions[rand::thread_rng().gen_range(0, directions.len())]) + } +} + -- cgit