Throw designated items at signs during caching

This commit is contained in:
Tanner committed 2026-11-10 15:11:27 +00:00
1 parent 46b0657bcf
commit ce3be28d0c
4 files changed
+469 -2

No files matched your search

+126 -1
View File
@@ -70,6 +70,119 @@ class CacheItemsStates:
return True
return False
def _find_throw_signs(self):
world = self.g.get('world')
finder = getattr(world, 'find_throw_signs', None)
position = self.g.get('pos')
if not callable(finder) or position is None or position is False:
return []
return finder(utils.pint(position), self.g.get('name', ''), 80)
def _throwable_slots(self, item_ids, excluded=()):
item_ids = set(item_ids)
excluded = set(excluded)
slots = [(slot, item) for slot, item in self.g.get('inv', {}).items()
if 9 <= slot <= 45 and slot not in excluded and
item.present and item.item_id in item_ids]
slots.sort(key=lambda pair: (-pair[1].item_count, pair[0]))
return slots
@staticmethod
def _throw_sign_key(sign):
return (tuple(sign['position']), sign.get('side'),
sign.get('item_name'))
def choose_throw_sign(self):
print('Checking item-throw signs...')
world = self.g.get('world')
center = utils.pint(self.g.pos)
for sign in self.throw_signs:
key = self._throw_sign_key(sign)
if key in self.checked_throw_signs:
continue
self.checked_throw_signs.add(key)
if not self._throwable_slots(sign['item_ids']):
continue
finder = getattr(world, 'find_throw_openings', None)
if not callable(finder):
continue
for opening in finder(sign, center, 3):
opening_position = tuple(opening['position'])
navpath = world.path_to_place(center, opening_position)
if not navpath:
continue
self.throw_sign = sign
self.throw_failed_slots = set()
self.pending_throw = None
self.opening = opening_position
self.g.path = navpath
self.g.look_at = None
print('Going to throw', sign['item_name'], 'at sign',
sign['position'], 'from', opening_position)
self.state = self.going_to_throw_sign
return
print('No reachable throw opening for sign', sign['position'])
self.throw_sign = None
self.state = self.choose_trapped_chest
def going_to_throw_sign(self):
if utils.pint(self.g.pos) == self.opening:
self.g.look_at = self.throw_sign['position']
self.wait_time = 0.5
self.state = self.turn_to_throw_sign
else:
self.g.look_at = None
def turn_to_throw_sign(self):
self.g.look_at = self.throw_sign['position']
self.wait_time -= utils.TICK
if self.wait_time <= 0:
self.state = self.throw_items
def throw_items(self):
if self.g.item_lock or self.g.get('drop_waiting'):
return
slots = self._throwable_slots(
self.throw_sign['item_ids'], self.throw_failed_slots)
if not slots:
print('Finished throwing', self.throw_sign['item_name'],
'at sign', self.throw_sign['position'])
self.g.look_at = None
self.throw_sign = None
self.state = self.choose_throw_sign
return
slot_num, item = slots[0]
if self.g.game.drop_inventory_slot(slot_num, whole_stack=True):
self.pending_throw = {
'slot': slot_num,
'item_id': item.item_id,
'item_count': item.item_count,
'deadline': time.monotonic() + 4.0,
}
self.state = self.wait_for_throw
def wait_for_throw(self):
pending = self.pending_throw
if pending is None:
self.state = self.throw_items
return
item = self.g.inv.get(pending['slot'])
if (item is None or not item.present or
item.item_id != pending['item_id'] or
item.item_count < pending['item_count']):
print('Throw confirmed from inventory slot', pending['slot'])
self.pending_throw = None
self.state = self.throw_items
elif (self.g.get('drop_waiting') is None and
time.monotonic() >= pending['deadline']):
print('Throw was not confirmed from slot', pending['slot'])
self.throw_failed_slots.add(pending['slot'])
self.pending_throw = None
self.state = self.throw_items
def init(self):
self.skip_inventory_slots = set()
self.skip_items = []
@@ -81,6 +194,11 @@ class CacheItemsStates:
self.container_item_ids = None
self.current_container_key = None
self.container_was_full_on_open = None
self.throw_signs = []
self.checked_throw_signs = set()
self.throw_sign = None
self.throw_failed_slots = set()
self.pending_throw = None
num_stacks = self.g.game.count_inventory_slots()
has_override = 'minimum' in self.__dict__
@@ -106,13 +224,15 @@ class CacheItemsStates:
w = self.g.world
p = utils.pint(self.g.pos)
self.throw_signs = self._find_throw_signs()
self.checked_throw_signs = set()
self.labeled_chests = w.find_labeled_chests(p, 80)
self.checked_labeled_chests = set()
self.trapped_chests = w.find_blocks_indexed(p, blocks.TRAPPED_CHEST_IDS)
print('Found {} labeled chests; found {} trapped chests: {}'.format(
len(self.labeled_chests), len(self.trapped_chests),
self.trapped_chests))
self.state = self.choose_trapped_chest
self.state = self.choose_throw_sign
def _opening_in_bad_region(self, world, opening):
opening = tuple(opening)
@@ -522,6 +642,11 @@ class CacheItemsStates:
self.trapped_chests = []
self.bad_areas = []
self.wait_time = 0
self.throw_signs = []
self.checked_throw_signs = set()
self.throw_sign = None
self.throw_failed_slots = set()
self.pending_throw = None
def run(self):
self._refresh_useless_chests()
+99 -1
View File
@@ -4,7 +4,7 @@ from collections import namedtuple
import re
import time
import random
from math import floor
from math import cos, floor, sin
from itertools import count
from copy import copy
@@ -99,6 +99,104 @@ class World:
result.sort(key=lambda sign: utils.phyp(center, sign['position']))
return result
@staticmethod
def _sign_text_normal(sign, state_id):
properties = blocks.PROPS.get(state_id, {})
facing = properties.get('facing')
cardinal = {
'north': (0.0, 0.0, -1.0),
'south': (0.0, 0.0, 1.0),
'west': (-1.0, 0.0, 0.0),
'east': (1.0, 0.0, 0.0),
}
normal = cardinal.get(facing)
if normal is None:
try:
rotation = int(properties.get('rotation', 0)) % 16
except (TypeError, ValueError):
rotation = 0
angle = rotation * (2 * 3.141592653589793 / 16)
normal = (-sin(angle), 0.0, cos(angle))
if sign.get('side') == 'back':
normal = tuple(-component for component in normal)
return normal
def find_throw_signs(self, center, bot_name, distance=80):
"""Find nearby signs directing this bot to throw an item at them."""
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())
text = text.casefold().replace('minecraft:', '')
tokens = re.findall(r'[a-z0-9_]+', text)
if (len(tokens) < 3 or tokens[0] not in addresses or
tokens[1] != 'throw'):
continue
item_name = '_'.join(tokens[2:])
item_ids = items.storage_item_ids_for_label(item_name)
if not item_ids:
item_ids = items.get_set({item_name})
if not item_ids:
continue
state_id = self.block_at(*sign['position'])
result.append({
'position': tuple(sign['position']),
'side': sign['side'],
'lines': sign['lines'],
'item_name': item_name,
'item_ids': item_ids,
'normal': self._sign_text_normal(sign, state_id),
})
result.sort(key=lambda directive: utils.phyp(
center, directive['position']))
return result
def find_throw_openings(self, sign, center, radius=3):
"""Find standable, visible throw positions within radius of a sign."""
sign_pos = tuple(sign['position'])
normal_x, _, normal_z = sign['normal']
face_point = (sign_pos[0] + 0.5 + normal_x * 0.49,
sign_pos[1] + 0.5,
sign_pos[2] + 0.5 + normal_z * 0.49)
openings = []
for dx in range(-radius, radius + 1):
for dy in range(-radius, radius + 1):
for dz in range(-radius, radius + 1):
distance = utils.hypot(dx, dy, dz)
if distance > radius or distance == 0:
continue
position = (sign_pos[0] + dx, sign_pos[1] + dy,
sign_pos[2] + dz)
if not self._cache_opening_standable(position):
continue
eye = (position[0] + 0.5, position[1] + 1.62,
position[2] + 0.5)
if not self._has_cache_line_of_sight(
eye, face_point, sign_pos):
continue
horizontal_distance = utils.hypot(dx, dz)
alignment = (
(dx * normal_x + dz * normal_z) / horizontal_distance
if horizontal_distance else -1.0)
openings.append({
'position': position,
'look_at': sign_pos,
'distance': distance,
'alignment': alignment,
'path_distance': utils.phyp(center, position),
})
openings.sort(key=lambda opening: (
-opening['alignment'], opening['path_distance'],
opening['distance'], opening['position']))
return openings
def _double_chest_positions(self, chest):
state_id = self.block_at(*chest)
properties = blocks.PROPS.get(state_id, {})
+134
View File
@@ -30,6 +30,140 @@ class CacheItemsTests(unittest.TestCase):
'Found 11 labeled chests; found 0 trapped chests: []',
output.getvalue())
def test_throw_signs_are_checked_before_cache_containers(self):
directive = {
'position': (2, 64, 0), 'side': 'front',
'item_name': 'seeds', 'item_ids': {items.WHEAT_SEEDS_ID},
}
class FakeWorld:
@staticmethod
def find_throw_signs(_center, _bot_name, _distance):
return [directive]
@staticmethod
def find_labeled_chests(*_args):
return []
@staticmethod
def find_blocks_indexed(*_args):
return []
state = CacheItemsStates(Munch(
world=FakeWorld(), pos=(0, 64, 0), name='mosfet1'))
state.find_trapped_chests()
self.assertIs(state.state.__func__, state.choose_throw_sign.__func__)
self.assertEqual(state.throw_signs, [directive])
def test_throw_sign_does_not_bypass_cache_inventory_threshold(self):
class FakeWorld:
@staticmethod
def find_throw_signs(*_args):
raise AssertionError('throw signs are checked only at threshold')
class FakeGame:
@staticmethod
def count_inventory_slots():
return 1
state = CacheItemsStates(Munch(
world=FakeWorld(), pos=(0, 64, 0), name='mosfet2',
game=FakeGame(), inv={
9: Munch(present=True, item_id=items.WHEAT_SEEDS_ID,
item_count=12),
}, minimum_cache_slots=27))
state.init()
self.assertIs(state.state.__func__, state.cleanup.__func__)
def test_throw_sign_throws_target_item_at_cache_threshold(self):
position = (2, 64, 0)
opening = (1, 64, 0)
seed = Munch(present=True, item_id=items.WHEAT_SEEDS_ID,
item_count=12)
dropped = []
g = Munch(
name='mosfet2', pos=(0, 64, 0), inv={9: seed},
item_lock=False, drop_waiting=None, path=[], look_at=None,
minimum_cache_slots=27,
)
directive = {
'position': position, 'side': 'front', 'item_name': 'seeds',
'item_ids': items.storage_item_ids_for_label('seeds'),
}
class FakeWorld:
@staticmethod
def find_throw_signs(_center, bot_name, _distance):
self.assertEqual(bot_name, 'mosfet2')
return [directive]
@staticmethod
def find_throw_openings(sign, center, radius):
self.assertEqual(sign, directive)
self.assertEqual(radius, 3)
return [{'position': opening, 'alignment': 1.0}]
@staticmethod
def find_labeled_chests(*_args):
return []
@staticmethod
def find_blocks_indexed(*_args):
return []
@staticmethod
def path_to_place(start, target):
return [start, target]
class FakeGame:
@staticmethod
def count_inventory_slots():
return 27
@staticmethod
def drop_inventory_slot(slot, whole_stack=True):
dropped.append((slot, whole_stack))
g.drop_waiting = {'slot': slot}
return True
@staticmethod
def select_item(_item_ids):
return False
g.world = FakeWorld()
g.game = FakeGame()
state = CacheItemsStates(g)
state.init()
self.assertIs(state.state.__func__, state.find_trapped_chests.__func__)
state.find_trapped_chests()
self.assertIs(state.state.__func__, state.choose_throw_sign.__func__)
state.choose_throw_sign()
self.assertEqual(state.opening, opening)
g.pos = opening
state.going_to_throw_sign()
self.assertEqual(g.look_at, position)
state.wait_time = 0
state.turn_to_throw_sign()
state.throw_items()
self.assertEqual(dropped, [(9, True)])
self.assertIs(state.state.__func__, state.wait_for_throw.__func__)
g.drop_waiting = None
g.inv[9] = Munch(present=False, item_id=0, item_count=0)
state.wait_for_throw()
state.throw_items()
self.assertIs(state.state.__func__, state.choose_throw_sign.__func__)
state.choose_throw_sign()
self.assertIs(state.state.__func__, state.choose_trapped_chest.__func__)
state.choose_trapped_chest()
state.select_chest()
self.assertIs(state.state.__func__, state.cleanup.__func__)
def test_wanted_single_stack_is_not_considered_transferable(self):
wanted_id = items.WHEAT_SEEDS_ID
old_wanted = items.WANTED_ITEMS
+110
View File
@@ -0,0 +1,110 @@
import unittest
from munch import Munch
from mosfet.info import blocks, items
from mosfet.world import World
def wall_sign_state(facing):
name = 'oak_wall_sign'
data = blocks.MCD_BLOCKS[name]
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 ThrowSignTests(unittest.TestCase):
def test_throw_directives_support_group_bot_and_item_categories(self):
group_sign = (0, 64, 0)
individual_sign = (4, 64, 0)
chunks = FakeChunks(
block_entities={
group_sign: {'data': {
'front_text': {'messages': [
'mosfet', 'throw seeds', '', '',
]},
'back_text': {'messages': [
'mosfet3 throw bread', '', '', '',
]},
}},
individual_sign: {'data': {'front_text': {'messages': [
'mosfet2 throw wheat_seeds', '', '', '',
]}}},
},
states={
group_sign: wall_sign_state('north'),
individual_sign: wall_sign_state('west'),
})
world = World(Munch(chunks=chunks))
bot2 = world.find_throw_signs((0, 64, 0), 'mosfet2', 10)
self.assertEqual(len(bot2), 2)
group = next(sign for sign in bot2 if sign['position'] == group_sign)
individual = next(sign for sign in bot2
if sign['position'] == individual_sign)
self.assertEqual(group['item_ids'],
items.storage_item_ids_for_label('seeds'))
self.assertEqual(individual['item_ids'],
{items.WHEAT_SEEDS_ID})
self.assertEqual(group['normal'], (0.0, 0.0, -1.0))
self.assertEqual(individual['normal'], (-1.0, 0.0, 0.0))
bot1 = world.find_throw_signs((0, 64, 0), 'mosfet1', 10)
self.assertEqual([sign['position'] for sign in bot1], [group_sign])
def test_back_text_uses_back_face_normal(self):
position = (0, 64, 0)
world = World(Munch(chunks=FakeChunks(
block_entities={position: {'data': {
'front_text': {'messages': ['front', '', '', '']},
'back_text': {'messages': [
'mosfet2 throw seeds', '', '', '',
]},
}}},
states={position: wall_sign_state('north')})))
directive = world.find_throw_signs(position, 'mosfet2', 3)[0]
self.assertEqual(directive['side'], 'back')
self.assertEqual(directive['normal'], (0.0, 0.0, 1.0))
def test_throw_openings_prefer_text_face_and_skip_chute_holes(self):
sign_pos = (0, 64, 0)
states = {sign_pos: wall_sign_state('north')}
for x in range(-4, 5):
for z in range(-4, 5):
states[(x, 63, z)] = blocks.STONE
# The closest point on the sign's text-facing side is a drop chute.
states[(0, 63, -1)] = blocks.AIR
directive = {
'position': sign_pos,
'side': 'front',
'normal': (0.0, 0.0, -1.0),
}
world = World(Munch(chunks=FakeChunks(states=states)))
openings = world.find_throw_openings(
directive, center=(2, 64, 0), radius=3)
self.assertTrue(openings)
self.assertNotIn((0, 64, -1), {
tuple(opening['position']) for opening in openings
})
self.assertLessEqual(max(opening['distance'] for opening in openings), 3)
self.assertGreater(openings[0]['alignment'], 0.9)
self.assertEqual(tuple(openings[0]['position']), (0, 64, -2))
if __name__ == '__main__':
unittest.main()