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 from mosfet.jobs.work_boundary import WorkBoundaryReturnMixin class SleepWithBedStates(WorkBoundaryReturnMixin): BED_AIM_STABLE_DELAY = 0.5 def idle(self): return None def _is_thunderstorm(self): return self.g.get('weather') == 'thunderstorm' def init(self): self._capture_work_boundary() self.sleep_confirmed = False self.bed_aim_aligned_since = None self.my_bed = False self.area = None self.opening = None self.bed_head = None self.bed_facing = None self.bed_aim = None self.bed_click_options = [] self.bed_click_index = 0 self.opening_repath_at = 0.0 self.alignment_deadline = 0.0 self.bed_target_yaw = None self.beds = [] self.sleep_use_attempts = 0 self.waiting_for_night = False self.waiting_for_time_update = False current_time = self.g.get('time') if ((current_time is None or current_time < 12000) and not self._is_thunderstorm()): print('Aborting sleep, not night or thunderstorm') self.state = self.cleanup return if self.g.get('dimension') != 'overworld': print('Aborting sleep, not in overworld') self.state = self.cleanup return self.state = self.find_beds @staticmethod def _bed_facing(state_id): props = blocks.PROPS.get(state_id, {}) return { 'north': (0, 0, -1), 'south': (0, 0, 1), 'east': (1, 0, 0), 'west': (-1, 0, 0), }.get(props.get('facing')) def _bed_foot(self, position): w = self.g.world state_id = w.block_at(*position) props = blocks.PROPS.get(state_id, {}) if props.get('part') != 'head': return position facing = self._bed_facing(state_id) if facing is None: return position foot = utils.psub(position, facing) foot_state = w.block_at(*foot) if (foot_state in blocks.BED_IDS and blocks.PROPS.get(foot_state, {}).get('part') == 'foot'): return foot return position def _bed_head(self, foot): state_id = self.g.world.block_at(*foot) facing = self._bed_facing(state_id) return utils.padd(foot, facing) if facing is not None else foot def _bed_opening_standable(self, opening): world = self.g.world feet = world.block_at(*opening) above = world.block_at(*utils.padd(opening, path.BLOCK_ABOVE)) below = world.block_at(*utils.padd(opening, path.BLOCK_BELOW)) return ( feet in blocks.NON_SOLID_IDS and feet not in blocks.AVOID_IDS and above in blocks.NON_SOLID_IDS and above not in blocks.AVOID_IDS and below is not None and below not in blocks.NON_SOLID_IDS and below not in blocks.AVOID_IDS) def _bed_click_options(self, opening, bed, head): world = self.g.world eye = (opening[0] + 0.5, opening[1] + 1.62, opening[2] + 0.5) options = [] parts = list(dict.fromkeys((tuple(bed), tuple(head)))) line_of_sight = getattr(world, '_has_cache_line_of_sight', None) for part in parts: interaction = self.g.game.bed_interaction_point(part) if interaction is None: continue cursor, point = interaction if (callable(line_of_sight) and not line_of_sight(eye, point, tuple(part))): continue options.append({ 'block': tuple(part), 'cursor': cursor, 'point': point, 'distance': utils.phyp(eye, point), }) options.sort(key=lambda option: option['distance']) return options def _bed_approaches(self, position, bed): world = self.g.world head = self._bed_head(bed) parts = list(dict.fromkeys((tuple(bed), tuple(head)))) approaches = {} for part in parts: for direction in path.CHECK_DIRECTIONS: opening = tuple(utils.padd(part, direction)) if opening in parts or opening in approaches: continue if not self._bed_opening_standable(opening): continue options = self._bed_click_options(opening, bed, head) if not options: continue navpath = world.path_to_place(position, opening) if navpath is None: continue route = list(navpath) if route and tuple(route[0]) == tuple(position): route = route[1:] approaches[opening] = { 'path': route, 'options': options, } return sorted( ((len(info['path']), utils.phyp(position, opening), opening, info) for opening, info in approaches.items()), key=lambda candidate: (candidate[0], candidate[1], candidate[2])) def find_beds(self): print('Finding beds...') w = self.g.world p = utils.pint(self.g.pos) refuge_sign = getattr(self, 'refuge_sign', None) if refuge_sign is not None: # Refuge maintenance may use existing beds near the sign only; # never roam farther or place a bed while waiting for threats. center = tuple(refuge_sign['position']) indexed = w.find_blocks_indexed(center, blocks.BED_IDS, 5) nearby = list(w.find_blocks_3d( center, blocks.BED_IDS, distance=5, y_limit=5)) result = list(dict.fromkeys(nearby + indexed)) result = [bed for bed in result if utils.phyp(center, bed) <= 5] result.sort(key=lambda bed: utils.phyp(p, bed)) elif self.force_new_bed: result = [] print('Skipping existing beds; placing a new bed as requested') else: indexed = w.find_blocks_indexed(p, blocks.BED_IDS, 80) # Keep a tiny direct scan as a guard against stale/missing chunk # index entries, especially around respawn and chunk-cache changes. nearby = list(w.find_blocks_3d( p, blocks.BED_IDS, distance=8, y_limit=8)) result = list(dict.fromkeys(nearby + indexed)) result.sort(key=lambda bed: utils.phyp(p, bed)) if nearby and not indexed: print('Found beds by local scan; chunk index had none') result = list(dict.fromkeys(self._bed_foot(bed) for bed in result)) if refuge_sign is not None: center = tuple(refuge_sign['position']) result = [bed for bed in result if utils.phyp(center, bed) <= 5] self.beds = [] for bed in result: if refuge_sign is None and bed in self.bad_beds: continue if w.check_bed_occupied(bed): continue self.beds.append(bed) print('Found:', self.beds) self.state = self.choose_bed def choose_bed(self): print('Choosing a bed...') w = self.g.world p = utils.pint(self.g.pos) while self.beds: bed = self.beds.pop(0) print('Chose:', bed) approaches = self._bed_approaches(p, bed) if not approaches: if getattr(self, 'refuge_sign', None) is None: self.bad_beds.append(bed) print('No reachable, supported, visible bed opening; ' 'blacklisting') else: print('No reachable opening for refuge bed; skipping') continue _length, _distance, self.opening, approach = approaches[0] self.area = bed self.bed_head = self._bed_head(bed) self.bed_click_options = approach['options'] self.bed_click_index = 0 self.g.path = approach['path'] self.opening_deadline = time.monotonic() + max( 8.0, len(self.g.path) * 0.75) self.opening_repath_at = 0.0 self.g.look_at = None self.state = self.going_to_bed print('Going to supported bed opening:', self.opening, 'click target:', self.bed_click_options[0]['block']) return if getattr(self, 'refuge_sign', None) is not None: print('No existing bed within 5 blocks of refuge sign; not placing one') self.state = self.cleanup return print('No reachable beds; trying to place one') self.state = self.select_bed def _at_opening(self): return ( utils.pint(self.g.pos) == tuple(self.opening) and self._bed_opening_standable(self.opening) and self.g.get('on_ground', False) and abs(float(self.g.get('y_v', 0.0) or 0.0)) < 0.1) def going_to_bed(self): now = time.monotonic() if self._at_opening(): print('At grounded bed opening', self.opening) self.g.path = [] self.my_bed = False self.bed_click_index = 0 self.bed_aim_aligned_since = None self.alignment_deadline = now + 6.0 self.state = self.use_bed elif now >= self.opening_deadline: print('Could not reach grounded bed opening', self.opening, '; trying another bed') if getattr(self, 'refuge_sign', None) is None: self.bad_beds.append(self.area) self.g.path = [] self.g.look_at = None self.state = self.choose_bed elif not self.g.path and now >= self.opening_repath_at: position = utils.pint(self.g.pos) navpath = self.g.world.path_to_place(position, self.opening) if navpath: self.g.path = (list(navpath[1:]) if tuple(navpath[0]) == position else list(navpath)) self.opening_repath_at = now + 1.0 self.g.look_at = None def turn_to_bed(self): if not self._at_opening(): self.bed_aim_aligned_since = None self.g.look_at = None self.state = self.going_to_bed return if not self.bed_click_options: print('No visible bed surface from opening', self.opening) self.state = self.choose_bed return option = self.bed_click_options[self.bed_click_index] target_yaw, target_pitch = self.g.game.aim_at_point(option['point']) yaw_error = (target_yaw - float(self.g.get('yaw', 0.0)) + 180) % 360 - 180 pitch_error = target_pitch - float(self.g.get('pitch', 0.0)) if abs(yaw_error) <= 4.0 and abs(pitch_error) <= 3.0: now = time.monotonic() if self.bed_aim_aligned_since is None: self.bed_aim_aligned_since = now return if now - self.bed_aim_aligned_since < self.BED_AIM_STABLE_DELAY: return if not self.g.game.click_bed( option['block'], hand=self.g.get('holding_hand', 0), cursor=option['cursor']): print('Bed surface disappeared before click:', option['block']) self.state = self.choose_bed return self.sleep_use_attempts += 1 self.bed_aim_aligned_since = None self.sleep_deadline = now + 5.0 self.sleep_retry_at = now + 1.5 if self.sleep_use_attempts == 1 and not self.silent: self.g.chat.send('zzz') print('Clicked bed surface', option['block'], 'from grounded opening', self.opening, '(yaw error {:.1f}, pitch error {:.1f})'.format( yaw_error, pitch_error), flush=True) self.state = self.sleep_bed else: self.bed_aim_aligned_since = None if time.monotonic() >= self.alignment_deadline: if self.bed_click_index + 1 < len(self.bed_click_options): self.bed_click_index += 1 self.bed_aim_aligned_since = None self.alignment_deadline = time.monotonic() + 4.0 print('Could not aim at bed surface; trying alternate part', self.bed_click_options[self.bed_click_index]['block']) else: print('Could not align with bed; trying another opening') self.state = self.choose_bed def select_bed(self): if self.g.game.select_item(items.BED_IDS): self.state = self.find_bed_spot else: print('No bed, aborting.') self.state = self.cleanup def find_bed_spot(self): print('Finding a bed spot...') w = self.g.world p = utils.pint(self.g.pos) for layout in w.find_bed_areas(p, 100, include_layout=True): print('Found bed lane:', layout) if layout.foot in self.bad_areas: continue navpath = w.path_to_place(p, layout.opening) if navpath is not None: break else: # for print('Unable to find a reachable three-block bed lane') self.state = self.cleanup return self.area = layout.foot self.bed_head = layout.head self.opening = layout.opening self.bed_facing = layout.facing # Aim at the far end of the lane, not the adjacent foot tile. The # movement controller ignores yaw targets within 0.6 blocks, and the # foot tile can be that close when arrival stops near its edge. self.bed_aim = layout.head self.g.path = navpath self.opening_deadline = time.monotonic() + max( 8.0, len(navpath) * 0.75) self.g.look_at = None self.state = self.going_to_area def going_to_area(self): if utils.pint(self.g.pos) == self.opening: print('At bed lane end', self.opening) self.g.path = [] self.g.look_at = self.bed_aim self.bed_target_yaw = self._yaw_for_facing(self.bed_facing) self.g.yaw_target_override = self.bed_target_yaw self.alignment_deadline = time.monotonic() + 8.0 self.state = self.turn_to_bed_area elif time.monotonic() >= self.opening_deadline: print('Could not reach bed lane end', self.opening) self.bad_areas.append(self.area) self.g.look_at = None self.state = self.find_bed_spot else: self.g.look_at = None @staticmethod def _yaw_for_facing(facing): # Match the 26.3 movement adapter's Minecraft yaw convention. return { (0, 0, -1): 180.0, (0, 0, 1): 0.0, (1, 0, 0): -90.0, (-1, 0, 0): 90.0, }[tuple(facing)] def turn_to_bed_area(self): self.g.look_at = self.bed_aim target_yaw = self.bed_target_yaw self.g.yaw_target_override = target_yaw delta = (target_yaw - float(self.g.get('yaw', 0.0)) + 180) % 360 - 180 if abs(delta) <= 5.0: print('Aligned with bed lane; facing', self.bed_facing) self.state = self.place_bed elif time.monotonic() >= self.alignment_deadline: print('Could not align with bed lane; rejecting', self.area, '(yaw={}, target={})'.format(self.g.get('yaw'), target_yaw)) self.bad_areas.append(self.area) self.g.look_at = None self.g.yaw_target_override = None self.state = self.find_bed_spot def place_bed(self): support = utils.padd(self.area, path.BLOCK_BELOW) print('Placing bed at', self.area, 'on', support) self.g.game.place_block( support, BlockFace.TOP, hand=self.g.get('holding_hand', 0)) self.my_bed = True self.bed_place_deadline = time.monotonic() + 5.0 self.state = self.wait_use def wait_use(self): # Block updates can arrive after the use packet; poll authoritative # chunk state for several seconds instead of giving up after 0.5s. if self.g.world.block_at(*self.area) in blocks.BED_IDS: self.bed_head = self._bed_head(self.area) self.bed_click_options = self._bed_click_options( self.opening, self.area, self.bed_head) self.bed_click_index = 0 self.g.yaw_target_override = None if self.bed_click_options: self.state = self.use_bed else: print('Placed bed has no visible surface from opening', self.opening) self.state = self.cleanup elif time.monotonic() >= self.bed_place_deadline: print('Bed placement was not confirmed at', self.area) self.bad_areas.append(self.area) self.my_bed = False self.g.yaw_target_override = None self.state = self.cleanup def use_bed(self): w = self.g.world current_time = self.g.get('time') if current_time is None: if not getattr(self, 'waiting_for_time_update', False): print('Waiting for world time update before using bed') self.waiting_for_time_update = True return if (self.area is not None and w.block_at(*self.area) not in blocks.BED_IDS): print('Bed disappeared before use:', self.area) self.state = self.choose_bed return if self.area is not None and w.check_bed_occupied(self.area): print('Bed became occupied before use:', self.area) self.state = self.choose_bed return if (current_time < 12000 and not self._is_thunderstorm()): print('Daytime without a thunderstorm before bed use; ' 'resuming the job') self.state = self.cleanup return if current_time < 12550 and not self._is_thunderstorm(): if not getattr(self, 'waiting_for_night', False): print('Bed reached; waiting until sleep time (time={})'.format( current_time)) self.waiting_for_night = True return self.waiting_for_night = False self.waiting_for_time_update = False if not self._at_opening(): self.state = self.going_to_bed return print('Aiming at bed from grounded opening', self.opening) self.sleep_deadline = time.monotonic() + 12.0 self.sleep_use_attempts = 0 self.sleep_confirmed = False self.bed_click_index = 0 self.bed_aim_aligned_since = None self.alignment_deadline = time.monotonic() + 6.0 self.state = self.turn_to_bed def sleep_bed(self): w = self.g.world p = utils.pint(self.g.pos) current_time = self.g.get('time') threats = w.find_threats(p, 10) occupied = w.check_bed_occupied(self.area) if occupied: self.sleep_confirmed = True if threats: print('Waking up due to threats:') print(threats) if self.sleep_confirmed: self.g.game.leave_bed() self.state = self.cleanup elif self.sleep_confirmed and not occupied: print('Bed became unoccupied after sleep; resuming') self.state = self.break_bed if self.my_bed else self.cleanup elif current_time is not None and current_time < 12000: print('Woke up time') self.state = self.break_bed if self.my_bed else self.cleanup elif self.g.get('correction_count', 0) and self.sleep_confirmed: print('Woke up by movement') self.state = self.break_bed elif (not self.sleep_confirmed and self.sleep_use_attempts < 2 and self.sleep_use_attempts > 0 and time.monotonic() >= self.sleep_retry_at): print('Bed use not confirmed; realigning before retry') self.bed_aim_aligned_since = None if self.bed_click_index + 1 < len(self.bed_click_options): self.bed_click_index += 1 self.alignment_deadline = time.monotonic() + 5.0 self.state = self.turn_to_bed elif (not self.sleep_confirmed and self.sleep_use_attempts == 0 and time.monotonic() >= self.sleep_deadline): print('Could not aim/click bed while grounded; aborting') self.state = self.cleanup elif (not self.sleep_confirmed and time.monotonic() >= self.sleep_deadline): if getattr(self, 'refuge_sign', None) is None: print('Bed use was not confirmed; blacklisting', self.area) self.bad_beds.append(self.area) else: print('Bed use was not confirmed; will retry later', self.area) self.state = self.cleanup def break_bed(self): if self.my_bed: if self.g.game.break_block(self.area): self.state = self.collect_bed else: print('Could not break the placed bed at', self.area) self.my_bed = False self.state = self.cleanup else: self.state = self.cleanup def collect_bed(self): if not self.g.breaking: self.g.path = [utils.padd(self.area, utils.spiral(n)) for n in range(9)] self.wait_time = 2 self.collect_deadline = time.monotonic() + 8 self.state = self.wait def wait(self): # Finish the short pickup sweep, but don't let it block forever. if (self.g.path and time.monotonic() < self.collect_deadline): return if self.wait_time > 0: self.wait_time -= utils.TICK else: self.state = self.cleanup def cleanup(self): if (self.my_bed and self.area and self.g.world.block_at(*self.area) in blocks.BED_IDS): self.state = self.break_bed return if (getattr(self, 'refuge_sign', None) is None and self._maybe_return_to_work_boundary(self.cleanup)): return self.g.look_at = None self.g.path = [] self.g.yaw_target_override = None if self.sleep_confirmed and self.area is not None: self.g.post_sleep_cache_bed = tuple(self.area) self.my_bed = False self.force_new_bed = False self.state = self.done if (self.g.get('job') and getattr(self.g.job.state, '__name__', None) == 'sleep'): self.g.job.state = self.g.job.idle def done(self): # never gets ran, placeholder return None def __init__(self, global_state): self.g = global_state self.state = self.idle self.bed_aim_aligned_since = None self.silent = False self.my_bed = False self.beds = [] self.bad_beds = [] self.area = None self.opening = None self.bed_head = None self.bed_facing = None self.bed_aim = None self.bed_click_options = [] self.bed_click_index = 0 self.opening_repath_at = 0.0 self.alignment_deadline = 0.0 self.bed_target_yaw = None self.bad_areas = [] self.wait_time = 0 self.sleep_use_attempts = 0 self.sleep_retry_at = 0 self.force_new_bed = False self.sleep_confirmed = False self.work_policies = [] self.sleep_deadline = 0 self.refuge_sign = None def run(self): self._track_work_boundary_position() self.state()