diff --git a/mosfet/bot.py b/mosfet/bot.py index 70a26ab..c32e93d 100644 --- a/mosfet/bot.py +++ b/mosfet/bot.py @@ -24,6 +24,7 @@ from munch import Munch from mosfet import commands from mosfet import game +from mosfet.jobs import check_threats from mosfet import job from mosfet import path from mosfet import print_help @@ -39,6 +40,7 @@ for module in [ blocks, commands, game, + check_threats, items, job, mcdata, @@ -607,6 +609,7 @@ def refresh_runtime(global_state, reload_managers=False): """Rebind reloadable runtime adapters without touching the connection.""" g = global_state connection = g.get('connection') + previous_threat_monitor = g.get('threat_monitor') _remove_instance_listeners(connection, g.get('chat')) _remove_instance_listeners(connection, g.get('game')) @@ -643,6 +646,22 @@ def refresh_runtime(global_state, reload_managers=False): replacement_state = getattr(g.job, state_name, None) if replacement_state is not None: g.job.state = replacement_state + + from mosfet.jobs.check_threats import ThreatMonitor + threat_monitor = ThreatMonitor(g) + if previous_threat_monitor is not None: + monitor_state = getattr( + previous_threat_monitor.state, '__name__', 'watching') + for attribute in ( + 'next_scan_at', 'retry_at', 'safe_since', 'safety', + 'safe_sign', 'threats', 'resume_job_name', + 'job_suspended'): + if hasattr(previous_threat_monitor, attribute): + setattr(threat_monitor, attribute, + getattr(previous_threat_monitor, attribute)) + threat_monitor.state = getattr( + threat_monitor, monitor_state, threat_monitor.watching) + g.threat_monitor = threat_monitor g.commands = commands.Commands(g) if not reload_managers: g.mcdata = DataManager() diff --git a/mosfet/job.py b/mosfet/job.py index c8bcceb..5b5f7b8 100644 --- a/mosfet/job.py +++ b/mosfet/job.py @@ -17,7 +17,6 @@ from mosfet.info import mobs from mosfet.jobs import ( cache_items, - check_threats, clear_leaves, eat_food, fill_blocks, @@ -36,7 +35,6 @@ from mosfet.jobs import ( for module in [ cache_items, - check_threats, clear_leaves, eat_food, fill_blocks, @@ -71,7 +69,6 @@ class LegacyJobStates: self.grab_sapling_states = grab_sapling.GrabSaplingStates(self.g) self.grab_sand_states = grab_sand.GrabSandStates(self.g) self.fill_blocks_states = fill_blocks.FillBlocksStates(self.g) - self.check_threats_states = check_threats.CheckThreatsStates(self.g) self.gather_wart_states = gather_wart.GatherWartStates(self.g) self.gather_crop_states = gather_crop.GatherCropStates(self.g) self.eat_food_states = eat_food.EatFoodStates(self.g) @@ -105,7 +102,6 @@ class LegacyJobStates: def farm_sand(self): machines = [ self.grab_supplies_states, - self.check_threats_states, self.gather_sand_states, self.grab_sand_states, self.cache_items_states, @@ -216,7 +212,6 @@ class LegacyJobStates: def loiter(self): machines = [ - self.check_threats_states, self.sleep_with_bed_states, self.eat_food_states, ] @@ -285,8 +280,6 @@ class JobStates(LegacyJobStates): self.sleep_with_bed_states = sleep_with_bed.SleepWithBedStates( global_state) self.eat_food_states = eat_food.EatFoodStates(global_state) - self.check_threats_states = check_threats.CheckThreatsStates( - global_state) self.active_machine = None self.state = self.idle @@ -373,9 +366,6 @@ class JobStates(LegacyJobStates): self.sleep_with_bed_states.state = self.sleep_with_bed_states.idle self.sleep_with_bed_states.force_new_bed = False self.eat_food_states.state = self.eat_food_states.idle - self.check_threats_states.state = self.check_threats_states.idle - self.check_threats_states.safety = None - self.check_threats_states.external_safety = False self.gather_crop_states.active_section_anchor = None self.gather_crop_states.completed_crops = 0 self.active_machine = None diff --git a/mosfet/jobs/check_threats.py b/mosfet/jobs/check_threats.py index 3caeb28..cf5b6a0 100644 --- a/mosfet/jobs/check_threats.py +++ b/mosfet/jobs/check_threats.py @@ -1,19 +1,6 @@ -import re import time -import importlib -import random -from itertools import count -from math import floor - -from minecraft.networking.types import BlockFace - -from mosfet.protocol.managers import ChunkNotLoadedException from mosfet import utils -from mosfet import path -from mosfet.info import blocks -from mosfet.info import items -from mosfet.info import mcdata from mosfet.info import mobs class ThreatMonitor: @@ -59,32 +46,54 @@ class ThreatMonitor: print('[threat] queued job change until the area is safe', flush=True) self._stop_job() + def _nearby_hostiles(self, position, distance): + finder = getattr(self.g.world, 'find_monsters', None) + if callable(finder): + return finder(position, distance) + return self.g.world.find_threats(position, distance) + + @staticmethod + def _describe_threat(threat): + mob_name = mobs.MOB_NAMES.get( + threat.get('type'), 'unknown type {}'.format(threat.get('type'))) + return '{}#{} at ({:.1f}, {:.1f}, {:.1f})'.format( + mob_name, threat.get('entity_id', '?'), + threat.get('x', 0.0), threat.get('y', 0.0), + threat.get('z', 0.0)) + def _find_safety(self): world = self.g.world position = utils.pint(self.g.pos) self.safety = None self.g.path = [] - safety_blocks = world.find_blocks_indexed( - position, {blocks.EMERALD_BLOCK}, self.SAFETY_SEARCH_DISTANCE) - for block in safety_blocks: - spot = utils.padd(block, path.BLOCK_ABOVE) - if world.find_threats(spot, self.CLEAR_DISTANCE): - continue - navpath = world.path_to_place(position, spot) - if navpath is not None: - self.safety = spot - self.g.path = navpath - print('[threat] evacuating to safety marker', spot, flush=True) - return True + find_signs = getattr(world, 'find_safety_signs', None) + find_openings = getattr(world, 'find_safety_openings', None) + if callable(find_signs) and callable(find_openings): + signs = find_signs( + position, self.g.get('name', ''), self.SAFETY_SEARCH_DISTANCE) + for sign in signs: + for spot in find_openings(sign): + navpath = world.path_to_place(position, spot) + if navpath is None: + continue + self.safety = tuple(spot) + self.safe_sign = sign + self.g.path = navpath + print('[threat] evacuating to signed refuge', + self.safety, flush=True) + return True + # Preserve a conservative fallback when no addressed refuge sign is + # nearby or reachable. These fallback spots are not trusted shelters. for spot in world.find_bed_areas( position, self.CLEAR_DISTANCE * 2): - if world.find_threats(spot, self.CLEAR_DISTANCE): + if self._nearby_hostiles(spot, self.CLEAR_DISTANCE): continue navpath = world.path_to_place(position, spot) if navpath is not None: - self.safety = spot + self.safety = tuple(spot) + self.safe_sign = None self.g.path = navpath print('[threat] fleeing to clear area', spot, flush=True) return True @@ -94,18 +103,24 @@ class ThreatMonitor: return False def watching(self): + job = self.g.get('job') + if job is None or job.state == job.idle: + self.next_scan_at = 0.0 + return now = time.monotonic() if now < self.next_scan_at: return self.next_scan_at = now + self.CHECK_INTERVAL - threats = self.g.world.find_threats( + threats = self._nearby_hostiles( utils.pint(self.g.pos), self.THREAT_DISTANCE) if not threats: return self.threats = threats + descriptions = '; '.join(self._describe_threat(threat) + for threat in threats) print('[threat] detected {} nearby hostile(s); pausing job: {}'.format( - len(threats), threats), flush=True) + len(threats), descriptions), flush=True) self._suspend_job() self.g.look_at = None self.safe_since = None @@ -117,19 +132,10 @@ class ThreatMonitor: now = time.monotonic() if now >= self.next_scan_at: self.next_scan_at = now + self.CHECK_INTERVAL - position = utils.pint(self.g.pos) - threats = self.g.world.find_threats( - position, self.THREAT_DISTANCE) + threats = self._nearby_hostiles( + utils.pint(self.g.pos), self.THREAT_DISTANCE) if threats: self.threats = threats - if (self.safety is not None and - self.g.world.find_threats( - self.safety, self.CLEAR_DISTANCE)): - print('[threat] planned refuge is no longer clear; ' - 'choosing another', flush=True) - self.safety = None - self.g.path = [] - self._find_safety() if self.safety is not None and utils.pint(self.g.pos) == self.safety: self.g.path = [] @@ -140,8 +146,16 @@ class ThreatMonitor: flush=True) return - if not self.g.path and now >= self.retry_at: + if self.safety is None and now >= self.retry_at: self._find_safety() + elif (self.safety is not None and not self.g.path and + now >= self.retry_at): + navpath = self.g.world.path_to_place( + utils.pint(self.g.pos), self.safety) + if navpath is not None: + self.g.path = navpath + else: + self.retry_at = now + self.CHECK_INTERVAL def waiting(self): self._capture_job_change() @@ -149,16 +163,20 @@ class ThreatMonitor: if now < self.next_scan_at: return self.next_scan_at = now + self.CHECK_INTERVAL - threats = self.g.world.find_threats( - utils.pint(self.g.pos), self.CLEAR_DISTANCE) - if threats: - print('[threat] hostile still within safety radius; moving again', - flush=True) - self.threats = threats - self.safe_since = None - self.safety = None + + position = utils.pint(self.g.pos) + if position != self.safety: + # If knockback or a correction moved us off the refuge, return to + # the same sign instead of searching for another one. self.state = self.evacuating - self._find_safety() + self.retry_at = 0.0 + return + + # Signs explicitly designate trusted refuges. Keep monitoring nearby + # threats so work only resumes after the patrol has moved away, but + # never ray-test or blacklist the sign's refuge. + if self._nearby_hostiles(position, self.CLEAR_DISTANCE): + self.safe_since = None return if self.safe_since is None: @@ -178,6 +196,7 @@ class ThreatMonitor: self.resume_job_name = None self.job_suspended = False self.safety = None + self.safe_sign = None self.safe_since = None self.next_scan_at = time.monotonic() + self.CHECK_INTERVAL self.state = self.watching @@ -196,118 +215,9 @@ class ThreatMonitor: self.retry_at = 0.0 self.safe_since = None self.safety = None + self.safe_sign = None self.threats = [] self.resume_job_name = None self.job_suspended = False self.suspending_job = False - -class CheckThreatsStates: - THREAT_DISTANCE = 20 - CLEAR_DISTANCE = 30 - CHECK_INTERVAL = 2.0 - - def idle(self): - return None - - def init(self): - self.state = self.find_threats - print('Checking for threats') - - def find_threats(self): - w = self.g.world - p = utils.pint(self.g.pos) - - threats = w.find_threats(p, self.THREAT_DISTANCE) - - if threats: - print('Found', len(threats), 'threats, seeking safety:') - print(threats) - self.threats = threats - self.state = self.find_safety - else: - self.wait_time = self.CHECK_INTERVAL - self.state = self.wait - - def find_safety(self): - w = self.g.world - p = utils.pint(self.g.pos) - - safety_blocks = w.find_blocks_indexed( - p, [blocks.EMERALD_BLOCK], self.THREAT_DISTANCE * 4) - for block in safety_blocks: - spot = utils.padd(block, path.BLOCK_ABOVE) - if w.find_threats(spot, self.CLEAR_DISTANCE): - continue - navpath = w.path_to_place(p, spot) - if navpath is not None: - self.safety = spot - self.external_safety = True - self.g.path = navpath - self.state = self.going_to_safety - print('Going to emerald safety point', self.safety) - return - - # No configured emerald safe point was reachable. Retreat to a clear, - # supported location that the modern navigator can actually reach. - for spot in w.find_bed_areas(p, self.CLEAR_DISTANCE * 2): - if w.find_threats(spot, self.CLEAR_DISTANCE): - continue - navpath = w.path_to_place(p, spot) - if navpath is not None: - self.safety = spot - self.external_safety = False - self.g.path = navpath - self.state = self.going_to_safety - print('Fleeing to clear area', self.safety) - return - - print('No reachable safe area found') - self.wait_time = self.CHECK_INTERVAL - self.state = self.wait - - def going_to_safety(self): - if utils.pint(self.g.pos) == self.safety: - if self.external_safety: - print('At emerald safety point, waiting for server move') - self.state = self.wait_for_move - else: - print('At clear retreat spot') - self.wait_time = 3 - self.state = self.wait - - def wait_for_move(self): - # wait for the server to move the bot when it's safe - # ie. a piston + daylight sensor - if utils.pint(self.g.pos) != self.safety: - print('Moved, resuming job') - self.state = self.wait - self.wait_time = 3 - - def wait(self): - # wait to land, etc - if self.wait_time > 0: - self.wait_time -= utils.TICK - else: - self.state = self.cleanup - - def cleanup(self): - self.g.look_at = None - self.state = self.done - - def done(self): - # never gets ran, placeholder - return None - - def __init__(self, global_state): - self.g = global_state - self.state = self.idle - - self.safety = None - self.wait_time = 0 - self.threats = [] - self.external_safety = False - - def run(self): - self.state() - diff --git a/mosfet/world.py b/mosfet/world.py index 83b31e0..4e0c9f7 100644 --- a/mosfet/world.py +++ b/mosfet/world.py @@ -159,6 +159,64 @@ class World: center, directive['position'])) return result + def find_safety_signs(self, center, bot_name, distance=80): + """Find nearby signs addressed to this bot that mark safe refuges.""" + bot_name = str(bot_name).casefold() + group_name = (bot_name[:-1] if len(bot_name) > 1 and + bot_name[-1] in '123' else None) + addresses = {bot_name} + if group_name: + addresses.add(group_name) + + result = [] + for sign in self.find_signs(center, distance): + lines = [line.strip() for line in sign['lines'] if line.strip()] + if not lines: + continue + tokens = re.findall(r'[a-z0-9_]+', ' '.join(lines).casefold()) + if (len(tokens) < 2 or tokens[0] not in addresses or + not {'safety', 'refuge'}.intersection(tokens[1:])): + continue + state_id = self.block_at(*sign['position']) + result.append({ + 'position': tuple(sign['position']), + 'side': sign['side'], + 'lines': sign['lines'], + 'normal': self._sign_text_normal(sign, state_id), + }) + result.sort(key=lambda sign: utils.phyp(center, sign['position'])) + return result + + def find_safety_openings(self, sign, radius=3): + """Return standable positions near a trusted refuge sign, front first.""" + sign_pos = tuple(sign['position']) + normal_x, _, normal_z = sign['normal'] + if abs(normal_x) >= abs(normal_z): + front = (1 if normal_x >= 0 else -1, 0, 0) + else: + front = (0, 0, 1 if normal_z >= 0 else -1) + directions = ( + front, + (front[2], 0, -front[0]), + (-front[2], 0, front[0]), + (-front[0], 0, -front[2]), + ) + candidates = [] + for direction_rank, direction in enumerate(directions): + for distance in range(1, radius + 1): + for dy in (0, -1, 1): + if utils.hypot(distance, dy) > radius: + continue + offset = tuple(component * distance + for component in direction) + position = utils.padd( + sign_pos, (offset[0], dy, offset[2])) + if self._cache_opening_standable(position): + candidates.append(( + direction_rank, distance, abs(dy), position)) + candidates.sort() + return [candidate[3] for candidate in candidates] + def find_throw_openings(self, sign, center, radius=3): """Find standable, visible throw positions within radius of a sign.""" sign_pos = tuple(sign['position']) @@ -366,7 +424,6 @@ class World: support_machines = ( 'grab_supplies_states', 'sleep_with_bed_states', 'eat_food_states', 'cache_items_states', - 'check_threats_states', ) if any(machine is getattr(job, name, None) for name in support_machines): diff --git a/tests/test_safety_signs.py b/tests/test_safety_signs.py new file mode 100644 index 0000000..23e8ae9 --- /dev/null +++ b/tests/test_safety_signs.py @@ -0,0 +1,73 @@ +import unittest +from munch import Munch + +from mosfet.info import blocks +from mosfet.world import World + + +def wall_sign_state(facing): + data = blocks.MCD_BLOCKS['oak_wall_sign'] + return next( + state_id for state_id in range(data['minStateId'], data['maxStateId'] + 1) + if blocks.PROPS[state_id].get('facing') == facing and + blocks.PROPS[state_id].get('waterlogged') == 'false' + ) + + +class FakeChunks: + def __init__(self, block_entities=None, states=None): + self.block_entities = block_entities or {} + self.states = states or {} + + def get_block_at(self, *position): + return self.states.get(tuple(position), blocks.AIR) + + +class SafetySignTests(unittest.TestCase): + def test_safety_and_refuge_signs_follow_group_and_individual_addresses(self): + group_sign = (0, 64, 0) + individual_sign = (3, 64, 0) + world = World(Munch(chunks=FakeChunks( + block_entities={ + group_sign: {'data': {'front_text': {'messages': [ + 'mosfet', 'safety', '', '', + ]}}}, + individual_sign: {'data': {'back_text': {'messages': [ + 'mosfet2 refuge', '', '', '', + ]}}}, + }, + states={ + group_sign: wall_sign_state('north'), + individual_sign: wall_sign_state('east'), + }))) + + bot2 = world.find_safety_signs((0, 64, 0), 'mosfet2', 10) + self.assertEqual([sign['position'] for sign in bot2], [ + group_sign, individual_sign, + ]) + self.assertEqual(bot2[1]['normal'], (-1.0, 0.0, 0.0)) + self.assertEqual([sign['position'] for sign in world.find_safety_signs( + (0, 64, 0), 'mosfet1', 10)], [group_sign]) + self.assertEqual(world.find_safety_signs( + (0, 64, 0), 'mosfet4', 10), []) + + def test_safety_openings_try_text_facing_standable_positions_first(self): + sign_pos = (0, 64, 0) + front = (0, 64, -1) + side = (1, 64, 0) + states = { + sign_pos: wall_sign_state('north'), + (front[0], front[1] - 1, front[2]): blocks.STONE, + (side[0], side[1] - 1, side[2]): blocks.STONE, + } + world = World(Munch(chunks=FakeChunks(states=states))) + sign = {'position': sign_pos, 'normal': (0.0, 0.0, -1.0)} + + openings = world.find_safety_openings(sign) + + self.assertEqual(openings[0], front) + self.assertIn(side, openings) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_threat_detection.py b/tests/test_threat_detection.py index 49344f5..02a2267 100644 --- a/tests/test_threat_detection.py +++ b/tests/test_threat_detection.py @@ -6,7 +6,7 @@ from munch import Munch from mosfet.commands import Commands from mosfet.info import blocks, mobs from mosfet.job import JobStates -from mosfet.jobs.check_threats import CheckThreatsStates, ThreatMonitor +from mosfet.jobs.check_threats import ThreatMonitor from mosfet.world import World @@ -18,6 +18,22 @@ class FakeChunks: return blocks.STONE if (x, y, z) in self.solid else blocks.AIR +class FakeJob: + def idle(self): + pass + + def farm_wart(self): + pass + + def __init__(self): + self.state = self.farm_wart + self.stop_calls = 0 + + def stop(self): + self.stop_calls += 1 + self.state = self.idle + + class FakeChat: def __init__(self): self.handler = None @@ -50,38 +66,100 @@ class TestThreatDetection(unittest.TestCase): self.assertFalse(world.check_air_column((0, 64, 0), 5)) self.assertTrue(world.check_air_column((2, 64, 0), 5)) - def test_threat_state_falls_back_to_reachable_clear_area(self): + def test_waiting_monitor_sees_hostiles_even_when_surface_filter_hides_them(self): + refuge = (5, 64, 0) + pillager = Munch(entity_id=12, type=mobs.MOBS[ + 'minecraft:pillager']['protocol_id'], x=8.0, y=64.0, z=0.0) + + class ShelteredWorld: + @staticmethod + def find_monsters(_center, _distance): + return [pillager] + + @staticmethod + def find_threats(*_args): + return [] + + monitor = ThreatMonitor(Munch( + world=ShelteredWorld(), pos=refuge, job=None)) + monitor.safety = refuge + monitor.safe_sign = {'position': refuge} + monitor.state = monitor.waiting + + with patch('mosfet.jobs.check_threats.time.monotonic', + return_value=1.0): + monitor.tick() + + self.assertIs(monitor.state.__func__, monitor.waiting.__func__) + self.assertIsNone(monitor.safe_since) + self.assertEqual(monitor.safety, refuge) + + def test_threat_log_decodes_mob_type_and_position(self): + pillager_id = mobs.MOBS['minecraft:pillager']['protocol_id'] + description = ThreatMonitor._describe_threat(Munch( + entity_id=15, type=pillager_id, + x=-130.5, y=68.0, z=-241.5)) + + self.assertEqual(description, + 'pillager#15 at (-130.5, 68.0, -241.5)') + + def test_monitor_falls_back_to_reachable_clear_area_without_signs(self): + start = (0, 64, 0) spot = (8, 64, 0) + threat = Munch(entity_id=7) class SafeWorld: - def find_blocks_indexed(self, center, block_ids, distance=0): + @staticmethod + def find_safety_signs(*_args): return [] - def find_bed_areas(self, center, distance): + @staticmethod + def find_safety_openings(*_args): + return [] + + @staticmethod + def find_bed_areas(_center, _distance): return [spot] - def find_threats(self, center, distance): - return [] + @staticmethod + def find_threats(center, distance): + return [threat] if tuple(center) == start else [] - def path_to_place(self, start, target): - return [start, target] + @staticmethod + def path_to_place(origin, target): + return [origin, target] - g = Munch(world=SafeWorld(), pos=(0, 64, 0), path=[], look_at=None) - state = CheckThreatsStates(g) - state.state = state.find_safety - state.threats = [Munch(entity_id=7)] + g = Munch(world=SafeWorld(), pos=start, path=[], look_at=None, + job=FakeJob()) + monitor = ThreatMonitor(g) - state.find_safety() + with patch('mosfet.jobs.check_threats.time.monotonic', + return_value=0.0): + monitor.tick() - self.assertEqual(state.state, state.going_to_safety) - self.assertEqual(state.safety, spot) - self.assertFalse(state.external_safety) + self.assertEqual(monitor.state.__func__, monitor.evacuating.__func__) + self.assertEqual(monitor.safety, spot) self.assertEqual(g.path[-1], spot) - g.pos = spot - state.going_to_safety() - self.assertEqual(state.state, state.wait) - self.assertEqual(state.wait_time, 3) + def test_threat_monitor_does_not_scan_without_an_active_job(self): + class IdleJob: + def idle(self): + pass + + def __init__(self): + self.state = self.idle + + class UnusedWorld: + @staticmethod + def find_threats(*_args): + raise AssertionError('idle bot should not scan for threats') + + monitor = ThreatMonitor(Munch( + world=UnusedWorld(), pos=(0, 64, 0), job=IdleJob())) + + monitor.tick() + + self.assertIs(monitor.state.__func__, monitor.watching.__func__) def test_threat_monitor_waits_for_valid_spawn_position(self): class UnavailableWorld: @@ -95,6 +173,98 @@ class TestThreatDetection(unittest.TestCase): self.assertIs(monitor.state.__func__, monitor.watching.__func__) + def test_addressed_refuge_sign_is_trusted_and_has_no_line_of_sight_check(self): + start = (0, 64, 0) + refuge = (5, 64, 0) + threat = Munch(entity_id=9, x=3.5, y=64.0, z=0.5) + sign = {'position': (6, 64, 0), 'side': 'front'} + paths = [] + + class ShelterWorld: + @staticmethod + def find_threats(_center, _distance): + return [threat] + + @staticmethod + def find_safety_signs(center, bot_name, distance): + self.assertEqual(center, start) + self.assertEqual(bot_name, 'mosfet1') + self.assertEqual(distance, ThreatMonitor.SAFETY_SEARCH_DISTANCE) + return [sign] + + @staticmethod + def find_safety_openings(found_sign): + self.assertEqual(found_sign, sign) + return [refuge] + + @staticmethod + def path_to_place(origin, target): + paths.append((tuple(origin), tuple(target))) + return [origin, target] + + monitor = ThreatMonitor(Munch( + world=ShelterWorld(), name='mosfet1', pos=start, + path=[], look_at=None, job=FakeJob())) + with patch('mosfet.jobs.check_threats.time.monotonic', return_value=0.0): + monitor.tick() + self.assertEqual(monitor.safety, refuge) + self.assertIs(monitor.safe_sign, sign) + self.assertEqual(paths, [(start, refuge)]) + + # Even if the hostile remains nearby, it does not replace the trusted + # sign refuge merely due to distance or a line-of-sight calculation. + monitor.g.pos = refuge + with patch('mosfet.jobs.check_threats.time.monotonic', return_value=0.1): + monitor.tick() + self.assertIs(monitor.state.__func__, monitor.waiting.__func__) + with patch('mosfet.jobs.check_threats.time.monotonic', return_value=0.2): + monitor.tick() + self.assertEqual(monitor.safety, refuge) + self.assertEqual(paths, [(start, refuge)]) + + def test_damage_does_not_blacklist_a_trusted_sign_refuge(self): + start = (0, 64, 0) + refuge = (5, 64, 0) + now = [0.0] + sign = {'position': (6, 64, 0), 'side': 'front'} + + class FakeWorld: + @staticmethod + def find_threats(center, _distance): + return [Munch(entity_id=11)] if tuple(center) == start else [] + + @staticmethod + def find_safety_signs(*_args): + return [sign] + + @staticmethod + def find_safety_openings(_sign): + return [refuge] + + @staticmethod + def path_to_place(origin, target): + return [origin, target] + + g = Munch( + world=FakeWorld(), name='mosfet1', pos=start, path=[], + look_at=None, job=FakeJob(), health=20.0) + monitor = ThreatMonitor(g) + with patch('mosfet.jobs.check_threats.time.monotonic', + side_effect=lambda: now[0]): + monitor.tick() + g.pos = refuge + now[0] = 0.1 + monitor.tick() + self.assertIs(monitor.state.__func__, monitor.waiting.__func__) + + g.health = 14.0 + now[0] = 0.6 + monitor.tick() + + self.assertEqual(monitor.safety, refuge) + self.assertIs(monitor.state.__func__, monitor.waiting.__func__) + self.assertEqual(g.path, []) + def test_threat_monitor_polls_every_half_second(self): now = [0.0] scans = [] @@ -106,7 +276,7 @@ class TestThreatDetection(unittest.TestCase): return [] monitor = ThreatMonitor(Munch( - world=QuietWorld(), pos=(1, 64, 2), job=None)) + world=QuietWorld(), pos=(1, 64, 2), job=FakeJob())) with patch('mosfet.jobs.check_threats.time.monotonic', side_effect=lambda: now[0]): monitor.tick() @@ -122,8 +292,8 @@ class TestThreatDetection(unittest.TestCase): def test_monitor_evacuates_waits_for_clear_area_then_resumes_job(self): threat = Munch(entity_id=7) start = (0, 64, 0) - marker = (5, 63, 0) safe = (5, 64, 0) + sign = {'position': (5, 64, 1), 'side': 'front'} now = [0.0] class FakeWorld: @@ -134,8 +304,12 @@ class TestThreatDetection(unittest.TestCase): return [] @staticmethod - def find_blocks_indexed(_center, _block_ids, _distance): - return [marker] + def find_safety_signs(*_args): + return [sign] + + @staticmethod + def find_safety_openings(_sign): + return [safe] @staticmethod def path_to_place(origin, target):