Port sand gathering to 26.3

This commit is contained in:
Tanner committed 2026-11-16 22:55:06 +00:00
1 parent f28269f71c
commit 3e8b95c895
9 files changed
+413 -147

No files matched your search

+28 -11
View File
@@ -6,8 +6,9 @@ versions are not supported.
The original bot included wood/sand/crop farming, villager trading, eating, The original bot included wood/sand/crop farming, villager trading, eating,
sleeping, and threat avoidance. On the current 26.3 runtime, path following, sleeping, and threat avoidance. On the current 26.3 runtime, path following,
crop harvest/replant, tree harvesting/log farming, and loiter/threat avoidance crop harvest/replant, tree harvesting/log farming, sand gathering/farming, and
are migrated; other legacy jobs remain unavailable until ported to protocol 777. loiter/threat avoidance are migrated; other legacy jobs remain unavailable
until ported to protocol 777.
## Requirements and setup ## Requirements and setup
@@ -53,9 +54,10 @@ sign-directed item-specific and general chest caching (`1cache`, also run by
crop farming at the inventory threshold), bed sleeping (`1sleep`, or `1sleep new` to place a bed; crop farming at the inventory threshold), bed sleeping (`1sleep`, or `1sleep new` to place a bed;
also run by crop farming at night), food use (`1eat`, also run as needed by also run by crop farming at night), food use (`1eat`, also run as needed by
crop farming), the crop harvest/replant loop (`1farm crops`), tree/log farming crop farming), the crop harvest/replant loop (`1farm crops`), tree/log farming
(`1farm logs`, with `1farm wood` as an alias), and death-screen respawning (`1farm logs`, with `1farm wood` as an alias), sand gathering/farming
(`1respawn`). Other inventory/window actions and resource-farming/trading jobs (`1gather sand`, `1farm sand`), and death-screen respawning (`1respawn`).
remain disabled until their 26.3 packets are migrated. Other inventory/window actions and resource-farming/trading jobs remain disabled
until their 26.3 packets are migrated.
The default server is `127.0.0.1`; set `SERVER` explicitly only when you The default server is `127.0.0.1`; set `SERVER` explicitly only when you
intentionally want another server. intentionally want another server.
@@ -74,6 +76,21 @@ the bot's full name (for example, `mosfet1`) or its group name (for example,
`mosfet`, which addresses bots ending in `1`, `2`, or `3`). A colon after the `mosfet`, which addresses bots ending in `1`, `2`, or `3`). A colon after the
address is optional. address is optional.
### Sand origin
Address a sign with `sand origin` to choose the search center for `1gather sand`
or `1farm sand`:
```
mosfet sand origin
```
The bot uses the nearest matching loaded sign within 200 blocks. A full bot
name such as `mosfet1` can be used instead of the group name. Sand is harvested
in safe 3x3x1 sections, clearing one section before moving to the next. If no
matching sign is found, the job keeps its previous loaded origin, or uses the
bot's current block position when no loaded origin is set.
### Cache labels ### Cache labels
Put one or more item-category labels on a sign next to a chest. A standing Put one or more item-category labels on a sign next to a chest. A standing
@@ -205,11 +222,11 @@ and all bots will run the command.
The current 26.3 command path handles public chat and direct messages, replying The current 26.3 command path handles public chat and direct messages, replying
in the same channel. Verified commands are `!ping`, `!pos`, `!dist`, `!loaded`, in the same channel. Verified commands are `!ping`, `!pos`, `!dist`, `!loaded`,
`!info x y z`, `!inv` (basic slot/count data), `1cache`, `1drain`, `1eat`, `!info x y z`, `!inv` (basic slot/count data), `1cache`, `1drain`, `1eat`,
`1respawn`, `1sleep`, `1loiter`, addressed path movement such as `1goto x y z`, and `1respawn`, `1sleep`, `1loiter`, addressed path movement such as `1goto x y z`,
`1farm crops`, and `1farm logs` (also available as `1farm wood`). The command `1farm crops`, `1farm logs` (also available as `1farm wood`), `1gather sand`,
catalog below is retained from the legacy bot; other inventory actions, and `1farm sand`. The command catalog below is retained from the legacy bot;
arbitrary block interaction, and the other farming/trading commands are not yet other inventory actions, arbitrary block interaction, and the other
available on 26.3. Common item farming/trading commands are not yet available on 26.3. Common item
components (names, damage, enchantments, book components (names, damage, enchantments, book
contents, and shulker contents) are decoded; unrecognized component types are contents, and shulker contents) are decoded; unrecognized component types are
marked partial rather than silently discarded. marked partial rather than silently discarded.
@@ -282,7 +299,7 @@ These will only run for the bot they are addressed to. Replace `1` with the last
`1farm logs` (or `1farm wood`) - farms trees and caches their logs `1farm logs` (or `1farm wood`) - farms trees and caches their logs
`1farm sand` - farms sand from a certain area `1farm sand` - gathers sand, first obtaining a shovel from a supply chest
`1farm wart` - farms netherwart from a certain area `1farm wart` - farms netherwart from a certain area
+1
View File
@@ -509,6 +509,7 @@ def start_automation(global_state, initialize=True):
old_stop.set() old_stop.set()
if old_worker is not None and old_worker is not threading.current_thread(): if old_worker is not None and old_worker is not threading.current_thread():
old_worker.join(timeout=1.0) old_worker.join(timeout=1.0)
g.movement_error = None
stop_event = threading.Event() stop_event = threading.Event()
g.movement_stop_event = stop_event g.movement_stop_event = stop_event
+19 -8
View File
@@ -29,6 +29,18 @@ class Commands:
else: else:
self.g.chat.send(reply) self.g.chat.send(reply)
def _prepare_sand_origin(self):
position = utils.pint(self.g.pos)
origins = self.g.world.find_sand_origins(position, self.g.name)
self.g.sand_origin_from_sign = bool(origins)
if origins:
self.g.sand_origin = origins[0]['position']
print('Using sand origin sign at', self.g.sand_origin)
elif (not self.g.sand_origin or
self.g.chunks.get_block_at(*self.g.sand_origin) is None):
self.g.sand_origin = position
print('Using current position as sand origin', position)
def handle_chat(self, message): def handle_chat(self, message):
source, sender, text = message[:3] source, sender, text = message[:3]
reply_target = message[3] if len(message) > 3 else sender reply_target = message[3] if len(message) > 3 else sender
@@ -70,11 +82,12 @@ class Commands:
'trade', 'gapple', 'fill', 'trade', 'gapple', 'fill',
'break', 'open', 'click', 'use', 'interact', 'break', 'open', 'click', 'use', 'interact',
} }
if ((command == 'gather' and data.lower().strip() != 'wood') or if ((command == 'gather' and
data.lower().strip() not in ('wood', 'sand')) or
command in unsupported or command in unsupported or
(command == 'farm' and (command == 'farm' and
not farm_target.startswith('crop') and not farm_target.startswith('crop') and
farm_target not in ('wood', 'logs', 'wart'))): farm_target not in ('wood', 'logs', 'wart', 'sand'))):
reply = 'not migrated to Minecraft 26.3 yet' reply = 'not migrated to Minecraft 26.3 yet'
print('Reply:', reply) print('Reply:', reply)
self._send_reply(reply, private, reply_target) self._send_reply(reply, private, reply_target)
@@ -462,9 +475,8 @@ class Commands:
if data == 'wood': if data == 'wood':
self.g.job.state = self.g.job.gather_wood self.g.job.state = self.g.job.gather_wood
reply = 'ok' reply = 'ok'
elif data == 'sand': elif data.lower().strip() == 'sand':
if not self.g.sand_origin or not self.g.chunks.check_loaded(self.g.sand_origin): self._prepare_sand_origin()
self.g.sand_origin = utils.pint(self.g.pos)
self.g.job.state = self.g.job.gather_sand self.g.job.state = self.g.job.gather_sand
reply = 'ok' reply = 'ok'
@@ -484,9 +496,8 @@ class Commands:
if farm_target in ('wood', 'logs'): if farm_target in ('wood', 'logs'):
self.g.job.state = self.g.job.farm_wood self.g.job.state = self.g.job.farm_wood
reply = 'ok' reply = 'ok'
elif data == 'sand': elif farm_target == 'sand':
if not self.g.sand_origin or not self.g.chunks.check_loaded(self.g.sand_origin): self._prepare_sand_origin()
self.g.sand_origin = utils.pint(self.g.pos)
self.g.job.state = self.g.job.farm_sand self.g.job.state = self.g.job.farm_sand
reply = 'ok' reply = 'ok'
elif farm_target == 'wart': elif farm_target == 'wart':
+4
View File
@@ -271,6 +271,8 @@ class JobStates(LegacyJobStates):
self.gather_wood_states = gather_wood.GatherWoodStates(global_state) self.gather_wood_states = gather_wood.GatherWoodStates(global_state)
self.gather_crop_states = gather_crop.GatherCropStates(global_state) self.gather_crop_states = gather_crop.GatherCropStates(global_state)
self.gather_wart_states = gather_wart.GatherWartStates(global_state) self.gather_wart_states = gather_wart.GatherWartStates(global_state)
self.gather_sand_states = gather_sand.GatherSandStates(global_state)
self.grab_sand_states = grab_sand.GrabSandStates(global_state)
self.grab_supplies_states = grab_supplies.GrabSuppliesStates( self.grab_supplies_states = grab_supplies.GrabSuppliesStates(
global_state) global_state)
self.clear_leaves_states = clear_leaves.ClearLeavesStates(global_state) self.clear_leaves_states = clear_leaves.ClearLeavesStates(global_state)
@@ -358,6 +360,8 @@ class JobStates(LegacyJobStates):
self.g.game.leave_bed() self.g.game.leave_bed()
self.gather_wood_states.state = self.gather_wood_states.idle self.gather_wood_states.state = self.gather_wood_states.idle
self.gather_crop_states.state = self.gather_crop_states.idle self.gather_crop_states.state = self.gather_crop_states.idle
self.gather_sand_states.state = self.gather_sand_states.idle
self.grab_sand_states.state = self.grab_sand_states.idle
self.grab_supplies_states.state = self.grab_supplies_states.idle self.grab_supplies_states.state = self.grab_supplies_states.idle
self.clear_leaves_states.state = self.clear_leaves_states.idle self.clear_leaves_states.state = self.clear_leaves_states.idle
self.plant_tree_states.state = self.plant_tree_states.idle self.plant_tree_states.state = self.plant_tree_states.idle
+204 -76
View File
@@ -1,132 +1,260 @@
import re """Gather naturally generated sand using the protocol-777 world APIs."""
import time 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 utils
from mosfet import path
from mosfet.info import blocks from mosfet.info import blocks
from mosfet.info import items from mosfet.info import items
from mosfet.info import mcdata
from mosfet.info import mobs
class GatherSandStates: class GatherSandStates:
def bair(self, p): SEARCH_DISTANCE = 200
return self.g.chunks.get_block_at(*p) in blocks.NON_SOLID_IDS BREAK_CONFIRM_TIMEOUT = 15.0
BREAK_REACH = 4.5
NAVIGATION_STALL_TIMEOUT = 20.0
NAVIGATION_PROGRESS_EPSILON = 0.15
def bsand(self, p): def _path_head_distance(self):
return self.g.chunks.get_block_at(*p) == blocks.SAND if not self.g.path:
return None
waypoint = self.g.path[0]
return utils.hypot(
self.g.pos.x - (waypoint[0] + 0.5),
self.g.pos.z - (waypoint[2] + 0.5))
def _begin_navigation(self):
self.navigation_path_head = (
tuple(self.g.path[0]) if self.g.path else None)
self.navigation_best_distance = self._path_head_distance()
self.navigation_last_progress_at = time.monotonic()
def _clear_navigation(self):
self.navigation_path_head = None
self.navigation_best_distance = None
self.navigation_last_progress_at = None
def _navigation_stalled(self):
now = time.monotonic()
path_head = tuple(self.g.path[0]) if self.g.path else None
distance = self._path_head_distance()
if path_head != self.navigation_path_head:
self.navigation_path_head = path_head
self.navigation_best_distance = distance
self.navigation_last_progress_at = now
elif (distance is not None and
(self.navigation_best_distance is None or
distance <= self.navigation_best_distance -
self.NAVIGATION_PROGRESS_EPSILON)):
self.navigation_best_distance = distance
self.navigation_last_progress_at = now
return (self.navigation_last_progress_at is not None and
now - self.navigation_last_progress_at >=
self.NAVIGATION_STALL_TIMEOUT)
def idle(self): def idle(self):
return None return None
def init(self): def init(self):
if not self.g.sand_origin or not self.g.chunks.check_loaded(self.g.sand_origin): if (not self.g.get('sand_origin_from_sign') and
(not self.g.sand_origin or
self.g.chunks.get_block_at(*self.g.sand_origin) is None)):
self.g.sand_origin = utils.pint(self.g.pos) self.g.sand_origin = utils.pint(self.g.pos)
self.state = self.select_shovel self.state = self.select_shovel
def select_shovel(self): def select_shovel(self):
self.g.game.select_item(items.SHOVEL_IDS) if not self.g.game.select_item(items.SHOVEL_IDS):
print('No shovel found; gathering sand without one')
self.state = self.find_new_slice self.state = self.find_new_slice
def _sand_is_safe(self, position):
world = self.g.world
if world.block_at(*position) != blocks.SAND:
return False
below = world.block_at(*utils.padd(position, (0, -1, 0)))
below_two = world.block_at(*utils.padd(position, (0, -2, 0)))
above = world.block_at(*utils.padd(position, (0, 1, 0)))
if (below is None or below_two is None or above is None or
below in blocks.NON_SOLID_IDS or
below_two in blocks.NON_SOLID_IDS or
above not in blocks.NON_SOLID_IDS):
return False
return world.sand_adjacent_safe(position)
def find_new_slice(self): def find_new_slice(self):
print('Finding new slice...') print('Finding a new 3x3x1 sand slice...')
w = self.g.world started = time.monotonic()
origin = self.g.sand_origin self.prev_layer, sand_slice = self.g.world.find_sand_slice(
self.g.sand_origin, self.SEARCH_DISTANCE, 10,
print('using origin', self.g.sand_origin) self.bad_slices, self.prev_layer)
start = time.time() if sand_slice is None:
self.prev_layer, s = w.find_sand_slice(self.g.sand_origin, 200, 10, self.bad_slices, self.prev_layer) print('No safe sand slices remain')
print('Found slice:', s, 'in', time.time() - start, 'seconds')
if s:
self.slice = s
self.bad_slices.append(s)
self.state = self.find_new_sand
else:
print('No slices remaining.')
self.state = self.cleanup self.state = self.cleanup
def find_new_sand(self):
print('Finding new sand...')
w = self.g.world
p = utils.pint(self.g.pos)
head = utils.padd(p, path.BLOCK_ABOVE)
for sand in w.find_sand(self.slice, 2, p):
if (sand not in self.bad_sand and
w.work_position_allowed(sand)):
print('Found sand:', sand)
break
else: # for
print('No in-bounds sand left in this slice; trying another.')
self.state = self.find_new_slice
return return
self.sand = sand self.sand_slice = tuple(sand_slice)
self.bad_slices.append(self.sand_slice)
self.bad_sand.clear()
print('Selected sand slice {} (search {:.3f}s)'.format(
self.sand_slice, time.monotonic() - started))
self.state = self.find_new_sand
if utils.phyp(head, self.sand) < blocks.BREAK_DISTANCE: def find_new_sand(self):
self.state = self.dig_sand world = self.g.world
else: center = utils.pint(self.g.pos)
for sand in world.find_sand(self.sand_slice, 2, center):
if (sand not in self.bad_sand and
world.work_position_allowed(sand)):
self.sand = tuple(sand)
self.tried_openings = set()
self.state = self.nav_to_sand self.state = self.nav_to_sand
return
print('No more eligible sand in slice', self.sand_slice)
self.state = self.find_new_slice
def _sand_openings(self):
world = self.g.world
openings = []
for direction in ((0, 0, -1), (0, 0, 1),
(-1, 0, 0), (1, 0, 0)):
for height in (1, 0):
opening = (self.sand[0] + direction[0],
self.sand[1] + height,
self.sand[2] + direction[2])
if opening in self.tried_openings:
continue
if not world.work_position_allowed(opening):
continue
feet = world.block_at(*opening)
head = world.block_at(*utils.padd(opening, (0, 1, 0)))
floor = world.block_at(*utils.padd(opening, (0, -1, 0)))
if (feet not in blocks.NON_SOLID_IDS or
head not in blocks.NON_SOLID_IDS or floor is None or
floor in blocks.NON_SOLID_IDS):
continue
openings.append(opening)
return openings
def nav_to_sand(self): def nav_to_sand(self):
w = self.g.world world = self.g.world
p = utils.pint(self.g.pos) if not self._sand_is_safe(self.sand):
c = self.g.chunks self.state = self.find_new_sand
return
navpath = w.path_to_place_faked(p, self.sand)
print('navpath:', navpath)
position = utils.pint(self.g.pos)
routes = []
for opening in self._sand_openings():
navpath = ([opening] if position == opening else
world.path_to_place(position, opening))
if navpath: if navpath:
self.g.path = navpath[:-1] routes.append((len(navpath), opening, navpath))
if routes:
_, self.opening, navpath = min(routes)
self.g.path = navpath
self.g.look_at = self.sand
self._begin_navigation()
print('Going to sand', self.sand, 'via', self.opening)
self.state = self.going_to_sand self.state = self.going_to_sand
else: else:
print('Cant get to that sand') print('Cannot path to sand; skipping', self.sand)
time.sleep(0.1) self.bad_sand.add(self.sand)
self.bad_sand.append(self.sand)
self.state = self.find_new_sand self.state = self.find_new_sand
def going_to_sand(self): def going_to_sand(self):
if not len(self.g.path): if self.g.world.block_at(*self.sand) != blocks.SAND:
self.g.look_at = self.sand self.g.path = []
self._clear_navigation()
self.state = self.find_new_sand
elif utils.pint(self.g.pos) == self.opening:
self.g.path = []
self._clear_navigation()
self.state = self.dig_sand self.state = self.dig_sand
elif self._navigation_stalled():
print('Navigation stalled to sand {}; trying another opening'.format(
self.sand))
self.g.path = []
self.g.look_at = None
self._clear_navigation()
self.tried_openings.add(self.opening)
self.state = self.nav_to_sand
def _set_break_deadline(self):
game_deadline = getattr(self.g.game, 'break_deadline', None)
self.break_deadline = (
game_deadline + 5.0 if game_deadline is not None else
time.monotonic() + self.BREAK_CONFIRM_TIMEOUT)
def dig_sand(self): def dig_sand(self):
if not self.g.breaking: if self.g.world.block_at(*self.sand) != blocks.SAND:
if self.bsand(self.sand): self.g.look_at = None
self.state = self.find_new_sand
return
position = self.g.pos
eye = (position.x, position.y + 1.62, position.z)
hit_point = tuple(value + 0.5 for value in self.sand)
if (utils.phyp(eye, hit_point) > self.BREAK_REACH or
not self.g.world._has_cache_line_of_sight(
eye, hit_point, self.sand)):
self.tried_openings.add(self.opening)
self.state = self.nav_to_sand
return
breaking = self.g.get('breaking')
if breaking:
if tuple(breaking) == self.sand:
self._set_break_deadline()
self.state = self.wait_break
return
self.g.look_at = self.sand self.g.look_at = self.sand
self.g.game.break_block(self.sand) if self.g.game.break_block(self.sand):
print('digging sand') self._set_break_deadline()
self.state = self.wait_break
else: else:
print('Break request rejected; skipping', self.sand)
self.bad_sand.add(self.sand)
self.state = self.find_new_sand
def wait_break(self):
if self.break_deadline is None:
self._set_break_deadline()
if self.g.world.block_at(*self.sand) != blocks.SAND:
print('Sand break confirmed at', self.sand)
self.g.look_at = None
self.state = self.find_new_sand
elif time.monotonic() > self.break_deadline:
print('Sand did not break; skipping', self.sand)
if self.g.get('breaking') == self.sand:
self.g.game.cancel_break()
self.g.look_at = None
self.bad_sand.add(self.sand)
self.state = self.find_new_sand self.state = self.find_new_sand
def cleanup(self): def cleanup(self):
self.g.path = []
self.g.look_at = None self.g.look_at = None
self._clear_navigation()
self.state = self.done self.state = self.done
def done(self): def done(self):
# never gets ran, placeholder
return None return None
def __init__(self, global_state): def __init__(self, global_state):
self.g = global_state self.g = global_state
self.state = self.idle self.state = self.idle
self.sand = None
self.slice = None self.sand_slice = None
self.bad_slices = [] self.bad_slices = []
self.prev_layer = 0 self.prev_layer = 0
self.sand = None self.bad_sand = set()
self.bad_sand = [] self.tried_openings = set()
self.wait_time = 0 self.opening = None
self.break_deadline = None
self.navigation_path_head = None
self.navigation_best_distance = None
self.navigation_last_progress_at = None
def run(self): def run(self):
self.state() self.state()
+78 -46
View File
@@ -1,89 +1,121 @@
import re """Pick up dropped sand using 26.3 entity and navigation state."""
import time 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 utils
from mosfet import path from mosfet import path
from mosfet.info import blocks from mosfet.info import blocks
from mosfet.info import items from mosfet.info import items
from mosfet.info import mcdata
from mosfet.info import mobs
class GrabSandStates: class GrabSandStates:
PICKUP_DISTANCE = 1.5
PICKUP_TIMEOUT = 5.0
def idle(self): def idle(self):
return None return None
def init(self): def init(self):
self.eid_blacklist.clear()
self.state = self.find_sand
print('Looking for dropped sand')
def _object(self, entity_id):
obj = self.g.get('objects', {}).get(entity_id)
if obj is None or obj.get('item_id') != items.SAND_ID:
return None
return obj
def _skip_target(self):
if self.entity_id is not None:
self.eid_blacklist.add(self.entity_id)
self.g.path = []
self.g.look_at = None
self.state = self.find_sand self.state = self.find_sand
print('Trying to grab sand')
def find_sand(self): def find_sand(self):
w = self.g.world world = self.g.world
p = utils.pint(self.g.pos) position = utils.pint(self.g.pos)
candidates = [
(entity_id, obj) for entity_id, obj in
self.g.get('objects', {}).items()
if obj.get('item_id') == items.SAND_ID and
entity_id not in self.eid_blacklist
]
candidates.sort(key=lambda pair: utils.phyp(
position, (pair[1].x, pair[1].y, pair[1].z)))
sand = w.find_objects([items.SAND_ID]) for entity_id, obj in candidates:
item_position = (obj.x, obj.y, obj.z)
if utils.phyp(position, item_position) > 6:
continue
item_block = utils.pint(item_position)
support = world.block_at(*utils.padd(item_block, path.BLOCK_BELOW))
if support is None or support in blocks.NON_SOLID_IDS:
continue
if not sand: self.entity_id = entity_id
print('No sand objects found, aborting') self.sand = item_block
self.state = self.cleanup if utils.phyp(tuple(self.g.pos), item_position) <= self.PICKUP_DISTANCE:
self.pickup_deadline = time.monotonic() + self.PICKUP_TIMEOUT
self.state = self.wait_for_pickup
return return
sand.sort(key=lambda s: utils.phyp(p, (s.x, s.y, s.z))) navpath = world.path_to_place(position, item_block)
if not navpath:
for s in sand: self.eid_blacklist.add(entity_id)
s_pos = utils.pint((s.x, s.y, s.z))
check = utils.padd(s_pos, path.BLOCK_BELOW)
if utils.phyp(p, s_pos) > 6:
continue
# skip if the sand is floating
if self.g.chunks.get_block_at(*check) in {0}:
continue
if s.entity_id in self.eid_blacklist:
continue continue
self.eid_blacklist.append(s.entity_id) self.entity_id = entity_id
self.sand = item_block
navpath = w.path_to_place(p, s_pos)
if navpath:
self.g.path = navpath self.g.path = navpath
self.g.look_at = item_block
print('Going to dropped sand', self.sand)
self.state = self.going_to_sand self.state = self.going_to_sand
self.sand = s_pos
print('Going to sand', self.sand)
return return
else:
print('Cant get to sand', self.sand)
time.sleep(0.1)
print('Cant get to any more sand, aborting') print('No reachable dropped sand nearby')
self.state = self.cleanup self.state = self.cleanup
def going_to_sand(self): def going_to_sand(self):
if utils.pint(self.g.pos) == self.sand: obj = self._object(self.entity_id)
self.state = self.cleanup if obj is None:
self.g.path = []
self.state = self.find_sand
return
item_position = (obj.x, obj.y, obj.z)
distance = utils.phyp(tuple(self.g.pos), item_position)
if distance <= self.PICKUP_DISTANCE:
self.g.path = []
self.pickup_deadline = time.monotonic() + self.PICKUP_TIMEOUT
self.state = self.wait_for_pickup
elif not self.g.path:
self._skip_target()
def wait_for_pickup(self):
if self._object(self.entity_id) is None:
print('Picked up dropped sand')
self.g.look_at = None
self.state = self.find_sand
elif time.monotonic() > self.pickup_deadline:
print('Could not pick up dropped sand; skipping', self.sand)
self._skip_target()
def cleanup(self): def cleanup(self):
self.g.path = []
self.g.look_at = None self.g.look_at = None
self.state = self.done self.state = self.done
def done(self): def done(self):
# never gets ran, placeholder
return None return None
def __init__(self, global_state): def __init__(self, global_state):
self.g = global_state self.g = global_state
self.state = self.idle self.state = self.idle
self.sand = None self.sand = None
self.eid_blacklist = [] self.entity_id = None
self.eid_blacklist = set()
self.pickup_deadline = None
def run(self): def run(self):
self.state() self.state()
+33 -6
View File
@@ -160,6 +160,31 @@ class World:
center, directive['position'])) center, directive['position']))
return result return result
def find_sand_origins(self, center, bot_name, distance=200):
"""Find signs addressed to this bot that designate a sand origin."""
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):
text = ' '.join(
line for line in sign['lines'] if line.strip()).casefold()
tokens = re.findall(r'[a-z0-9_]+', text)
if (len(tokens) < 3 or tokens[0] not in addresses or
tokens[1:3] != ['sand', 'origin']):
continue
result.append({
'position': tuple(sign['position']),
'side': sign['side'],
'lines': sign['lines'],
})
result.sort(key=lambda sign: utils.phyp(center, sign['position']))
return result
def find_safety_signs(self, center, bot_name, distance=80): def find_safety_signs(self, center, bot_name, distance=80):
"""Find nearby signs addressed to this bot that mark safe refuges.""" """Find nearby signs addressed to this bot that mark safe refuges."""
bot_name = str(bot_name).casefold() bot_name = str(bot_name).casefold()
@@ -790,7 +815,7 @@ class World:
return safe_sand return safe_sand
def check_sand_slice(self, center): def check_sand_slice(self, center):
# checks if a 5x5x1 slice has sand in it # Check whether a 3x3x1 sand section contains a safe block.
for i in range(9): for i in range(9):
s = utils.padd(center, utils.spiral(i)) s = utils.padd(center, utils.spiral(i))
if self.block_at(*s) != blocks.SAND: if self.block_at(*s) != blocks.SAND:
@@ -810,11 +835,13 @@ class World:
return False return False
def find_sand_slice(self, center, distance, y_limit=0, bad_slices=[], prev_layer=0): def find_sand_slice(self, center, distance, y_limit=0,
# returns the centre coord of the next 5x5x1 slice that still has bad_slices=None, prev_layer=0):
# diggable sand in it. lower slices are only valid if there's an # Return the centre of the next 3x3x1 section with diggable sand.
# adjacent slice farther at the same level. this should ensure an # Lower slices are only valid if there's an adjacent slice farther at
# upside down pyramid gets excavated so the edges are still climbable # the same level. This keeps the excavation edges climbable.
if bad_slices is None:
bad_slices = ()
for v in count(prev_layer): for v in count(prev_layer):
peak = utils.padd(center, (0, 10-v, 0)) peak = utils.padd(center, (0, 10-v, 0))
+21
View File
@@ -6,6 +6,27 @@ from mosfet.world import World
class IndexedSearchTests(unittest.TestCase): class IndexedSearchTests(unittest.TestCase):
def test_sand_search_targets_safe_blocks_in_3x3_slice_only(self):
sand_position = (1, 64, 1)
class SandChunks:
def get_block_at(self, x, y, z):
position = (x, y, z)
if position == sand_position:
return blocks.SAND
if y < sand_position[1]:
return blocks.STONE
return blocks.AIR
world = World(Munch(chunks=SandChunks()))
self.assertTrue(world.check_sand_slice((0, 64, 0)))
self.assertEqual(
world.find_sand((0, 64, 0), 2, (0, 64, 0)),
[sand_position])
sand_position = (2, 64, 0)
self.assertFalse(world.check_sand_slice((0, 64, 0)))
def test_index_deduplication_is_linear_and_sort_is_optional(self): def test_index_deduplication_is_linear_and_sort_is_optional(self):
far = (10, 64, 0) far = (10, 64, 0)
near = (1, 64, 0) near = (1, 64, 0)
+25
View File
@@ -107,6 +107,31 @@ class SignReadingTests(unittest.TestCase):
individual_world.sign_policies('mosfet2')], ['circle']) individual_world.sign_policies('mosfet2')], ['circle'])
self.assertEqual(individual_world.sign_policies('mosfet1'), []) self.assertEqual(individual_world.sign_policies('mosfet1'), [])
def test_sand_origin_signs_match_bot_and_numbered_group_addresses(self):
chunks = Munch(block_entities={
(1, 64, 0): {'data': {'front_text': {'messages': [
'mosfet', 'sand origin', '', '',
]}}},
(3, 64, 0): {'data': {'back_text': {'messages': [
'mosfet1 sand', 'origin', '', '',
]}}},
(2, 64, 0): {'data': {'front_text': {'messages': [
'mosfet2 sand origin', '', '', '',
]}}},
})
world = World(Munch(chunks=chunks))
origins = world.find_sand_origins((0, 64, 0), 'mosfet1')
self.assertEqual([origin['position'] for origin in origins], [
(1, 64, 0), (3, 64, 0),
])
self.assertEqual(
[origin['position'] for origin in
world.find_sand_origins((0, 64, 0), 'mosfet2')],
[(1, 64, 0), (2, 64, 0)],
)
def test_sign_policies_read_any_distance_within_loaded_signs(self): def test_sign_policies_read_any_distance_within_loaded_signs(self):
position = (100, 64, 0) position = (100, 64, 0)
chunks = Munch(block_entities={position: { chunks = Munch(block_entities={position: {