Перепиши код чтобы он работал.
import sys
from time import sleep
import minescript # minescript все еще нужен для других функций
from lib_java import JavaClass, java_class_map, java_member_map
def wait_screen(timeout_ms: int = 500) -> bool:
"""
Waits for the screen name to become available within a specified period.
Args:
timeout_ms (int): Maximum time to wait in milliseconds.
Returns:
bool: True if a screen name is detected within the wait period, False otherwise.
"""
steps = timeout_ms // 50
for _ in range(steps):
if minescript.screen_name() is not None:
return True
sleep(0.05)
return False
def open_targeted_chest() -> bool:
"""
Attempts to open the chest block currently targeted by the player.
Returns:
bool: True if a chest was successfully opened, False otherwise.
"""
block = minescript.player_get_targeted_block()
if block is None or "chest" not in block.type.lower():
return False
code
minescript.press_key_bind("key.use", True)
r = wait_screen()
minescript.press_key_bind("key.use", False)
if not r:
return False
return True
def take_items(slots_arg: list[int] | str) -> bool:
"""
Transfers items from the specified inventory slots to the player's inventory using quick move.
Args:
slots_arg (list[int] | str): A list of slot indices to move items from,
or "all" to move items from standard chest slots (0-26).
Returns:
bool: True if the operation was performed, False if no screen is open or other error.
"""
mode = False
code
screen = minecraft.screen
if screen is None:
return False
container_menu = screen.getMenu()
if container_menu is None:
return False
if container_menu.containerId is None:
return False # Or handle as an error if needed, but for silence, just fail.
mouse_button = 0
slots_to_process: list[int]
if isinstance(slots_arg, str) and slots_arg.lower() == "all":
slots_to_process = list(range(27))
if isinstance(slots_arg[:1], str) and slots_arg.lower() == "store":
slots_to_process = slots_arg
mode = True
elif isinstance(slots_arg, list):
slots_to_process = slots_arg
else:
return False # Invalid argument type
if mode:
for slot_index in slots_to_process[1:]:
try:
slot_id = int(slot_index)
if slot_id < 0:
continue # Skip invalid slot index
dc_offset = 36
dc_offset_hotbar = 9
dc_inv_size = 89
if slot_id>0 and slot_id<9:
slot_id = dc_inv_size - dc_offset_hotbar + slot_id
else:
slot_id = dc_inv_size - dc_offset + slot_id
except ValueError:
continue # Skip non-integer slot index
for slot_index in slots_to_process:
try:
slot_id = int(slot_index)
if slot_id < 0:
continue # Skip invalid slot index
except ValueError:
continue # Skip non-integer slot index
minecraft.gameMode.handleInventoryMouseClick(
container_menu.containerId,
slot_id,
mouse_button,
ClickType.QUICK_MOVE,
minecraft.player,
)
sleep(0.01)
return True
def close_chest():
"""
Closes the currently open chest GUI in Minecraft by simulating an Escape key press.
"""
screen = minecraft.screen
if screen is not None:
screen.keyPressed(256, 1, 0)
for _ in range(10): # Wait a moment for screen to actually close
if minecraft.screen is None:
break
sleep(0.05)
def main(args=None):
if args is None:
# Если аргументы не переданы, используем sys.argv
if len(sys.argv) < 2:
return
slots_input_args = sys.argv[1:]
else:
# Используем переданные аргументы
slots_input_args = args
code
slots_to_action: list[int] | str
if len(slots_input_args) == 1 and slots_input_args[0].lower() == "all":
slots_to_action = "all"
else:
try:
slots_to_action = [int(slot) for slot in slots_input_args]
except ValueError:
return
if not open_targeted_chest():
return
sleep(0.2)
if not take_items(slots_to_action):
close_chest()
return
sleep(0.2)
close_chest()
if name == "main":
main()
Assistant
Код, который вы предоставили, содержит несколько логических ошибок и недочетов в реализации функций take_items и store_items, а также в обработке аргументов. В частности, функция take_items пыталась обрабатывать логику "store", а store_items была реализована крайне неверно.
Ниже приведена переработанная версия кода. Я разделил логику take (забрать из сундука) и store (положить в сундук), а также исправил вычисление ID слотов для инвентаря игрока при помещении предметов в сундук.
Основные изменения:
take_items: Убрана вся логика, связанная с "store" и dc_offset, так как она была неуместна. Функция теперь исключительно забирает предметы из указанных слотов сундука в инвентарь игрока.
_get_gui_slot_id_from_player_slot: Добавлена новая вспомогательная функция для корректного преобразования внутренних слотов инвентаря игрока (0-35) в ID слотов, используемые в графическом интерфейсе сундука (например, для слотов инвентаря игрока, которые начинаются после слотов сундука). Это критично для функции store_items.
store_items: Полностью переписана для правильного перемещения предметов из инвентаря игрока в сундук. Она использует новую вспомогательную функцию для получения правильных ID слотов.
main: Переработана для обработки двух команд: "take" (забрать) и "store" (положить). Теперь вы можете запускать скрипт, указывая, что именно вы хотите сделать и с какими слотами.
import sys
from time import sleep
import minescript # minescript все еще нужен для других функций
from lib_java import JavaClass, java_class_map, java_member_map
# Mojang -> Intermediary mappings
# Это часть кода остается без изменений, она нужна для инициализации Java-классов.
mc_class_name = minescript.version_info().minecraft_class_name
if mc_class_name == "net.minecraft.class_310": # 1.16.5, 1.17.1, 1.18.2, 1.19.2 uses this for MinecraftClient
java_class_map.update({
"net.minecraft.client.Minecraft": "net.minecraft.class_310",
"net.minecraft.world.inventory.ClickType": "net.minecraft.class_1713",
})
java_member_map.update({
"getInstance": "method_1551",
"player": "field_1724",
"screen": "field_1755",
"gameMode": "field_1761",
"handleInventoryMouseClick": "method_2906",
"getMenu": "method_17577",
"containerId": "field_7763",
"keyPressed": "method_25404",
})
elif mc_class_name == "net.minecraft.client.Minecraft":
pass
Minecraft = JavaClass("net.minecraft.client.Minecraft")
ClickType = JavaClass("net.minecraft.world.inventory.ClickType")
minecraft = Minecraft.getInstance()
def wait_screen(timeout_ms: int = 500) -> bool:
"""
Waits for the screen name to become available within a specified period.
Args:
timeout_ms (int): Maximum time to wait in milliseconds.
Returns:
bool: True if a screen name is detected within the wait period, False otherwise.
"""
steps = timeout_ms // 50
for _ in range(steps):
if minescript.screen_name() is not None:
return True
sleep(0.05)
return False
def open_targeted_chest() -> bool:
"""
Attempts to open the chest block currently targeted by the player.
Returns:
bool: True if a chest was successfully opened, False otherwise.
"""
block = minescript.player_get_targeted_block()
if block is None or "chest" not in block.type.lower():
print("No chest targeted or block is not a chest.")
return False
minescript.press_key_bind("key.use", True)
# Даем игре время среагировать и открыть GUI сундука
r = wait_screen()
minescript.press_key_bind("key.use", False)
if not r:
print("Failed to detect chest screen after opening attempt.")
return False
return True
def _get_gui_slot_id_from_player_slot(player_inv_slot: int, container_size: int = 27) -> int:
"""
Converts a player's internal inventory slot (0-35) to its corresponding
GUI slot ID within a container screen (e.g., chest GUI).
Player internal slots:
0-8: Hotbar
9-35: Main inventory (3x9)
Common GUI slot mapping for a chest (container_size=27):
0-26: Chest slots
27-53: Player's main inventory slots (maps to internal 9-35)
54-62: Player's hotbar slots (maps to internal 0-8)
Args:
player_inv_slot (int): The player's internal inventory slot (0-35).
container_size (int): The number of slots in the opened container (e.g., 27 for a single chest).
Returns:
int: The corresponding GUI slot ID.
Raises:
ValueError: If player_inv_slot is out of valid range (0-35).
"""
if not 0 <= player_inv_slot <= 35:
raise ValueError(f"Invalid player inventory slot: {player_inv_slot}. Must be 0-35.")
if 0 <= player_inv_slot <= 8: # Hotbar slots
# Hotbar slots are typically after the main inventory in the GUI
return container_size + 27 + player_inv_slot
else: # Main inventory slots (9-35)
# Main inventory slots are typically directly after the container slots
return container_size + (player_inv_slot - 9)
def take_items(slots_arg: list[int] | str) -> bool:
"""
Transfers items from the specified inventory slots of the *opened container*
to the player's inventory using quick move.
Args:
slots_arg (list[int] | str): A list of slot indices within the container (e.g., 0-26 for chest)
to move items from, or "all" to move items from standard chest slots (0-26).
Returns:
bool: True if the operation was performed, False if no screen is open or other error.
"""
screen = minecraft.screen
if screen is None:
print("No screen open.")
return False
container_menu = screen.getMenu()
if container_menu is None:
print("No container menu detected.")
return False
if container_menu.containerId is None:
print("Container ID is None.")
return False
mouse_button = 0 # Left click
click_type = ClickType.QUICK_MOVE
slots_to_process: list[int]
if isinstance(slots_arg, str) and slots_arg.lower() == "all":
# Для сундуков обычно 27 слотов (0-26)
slots_to_process = list(range(27))
elif isinstance(slots_arg, list):
slots_to_process = slots_arg
else:
print(f"Invalid type for slots_arg: {type(slots_arg)}. Expected list[int] or 'all'.")
return False
for slot_index in slots_to_process:
try:
slot_id = int(slot_index)
if slot_id < 0: # Пропускаем отрицательные индексы
print(f"Skipping invalid slot_id (negative): {slot_id}")
continue
except ValueError:
print(f"Skipping non-integer slot_index: {slot_index}")
continue
minecraft.gameMode.handleInventoryMouseClick(
container_menu.containerId,
slot_id, # Это прямой ID слота в контейнере (сундуке)
mouse_button,
click_type,
minecraft.player,
)
sleep(0.01) # Небольшая задержка между кликами
return True
def store_items(player_slots_arg: list[int]) -> bool:
"""
Transfers items from the specified player inventory slots to the *opened container*
using quick move.
Args:
player_slots_arg (list[int]): A list of player inventory slot indices (0-35)
to move items from.
(0-8 for hotbar, 9-35 for main inventory).
Returns:
bool: True if the operation was performed, False if no screen is open or other error.
"""
screen = minecraft.screen
if screen is None:
print("No screen open.")
return False
container_menu = screen.getMenu()
if container_menu is None:
print("No container menu detected.")
return False
if container_menu.containerId is None:
print("Container ID is None.")
return False
# Предполагаем размер сундука 27 слотов.
# В более сложном сценарии можно попытаться определить размер контейнера динамически.
chest_size = 27
mouse_button = 0 # Left click
click_type = ClickType.QUICK_MOVE
for player_inv_slot_index in player_slots_arg:
try:
player_inv_slot = int(player_inv_slot_index)
# Проверяем, что это действительный слот инвентаря игрока (0-35)
if not 0 <= player_inv_slot <= 35:
print(f"Skipping invalid player inventory slot: {player_inv_slot}")
continue
except ValueError:
print(f"Skipping non-integer player_inv_slot_index: {player_inv_slot_index}")
continue
try:
# Получаем ID слота в GUI сундука, соответствующий слоту инвентаря игрока
gui_slot_id = _get_gui_slot_id_from_player_slot(player_inv_slot, chest_size)
except ValueError as e:
print(f"Error getting GUI slot ID for player slot {player_inv_slot}: {e}")
continue
minecraft.gameMode.handleInventoryMouseClick(
container_menu.containerId,
gui_slot_id, # Используем вычисленный ID слота в GUI
mouse_button,
click_type,
minecraft.player,
)
sleep(0.01) # Небольшая задержка между кликами
return True
def close_chest():
"""
Closes the currently open chest GUI in Minecraft by simulating an Escape key press.
"""
screen = minecraft.screen
if screen is not None:
print("Closing chest screen...")
# 256 - это код клавиши ESCAPE
screen.keyPressed(256, 1, 0) # KeyCode, ScanCode, Modifiers
# Даем игре время на закрытие экрана
for _ in range(20): # Увеличил количество итераций ожидания
if minecraft.screen is None:
print("Chest screen closed.")
break
sleep(0.05)
else:
print("Warning: Chest screen might not have closed completely.")
def main(args=None):
if args is None:
if len(sys.argv) < 3:
print("Usage: python script.py <command> <slots...>")
print("Commands:")
print(" take all - Take all items from chest (slots 0-26)")
print(" take <slot1> <slot2>... - Take specific items from chest slots")
print(" store <slot1> <slot2>... - Store specific items from player inventory slots (0-35) to chest")
return
command = sys.argv[1].lower()
slots_input_args = sys.argv[2:]
else:
if not args or len(args) < 2:
print("Usage for main(): main(['take', 'all']) or main(['store', '0', '1', '2'])")
return
command = args[0].lower()
slots_input_args = args[1:]
slots_to_action: list[int] | str = [] # Инициализация для type hinting
if command not in ["take", "store"]:
print(f"Error: Unknown command '{command}'. Use 'take' or 'store'.")
return
# Преобразование аргументов слотов в список целых чисел
# Специальный случай для "all" только для команды "take"
if command == "take" and len(slots_input_args) == 1 and slots_input_args[0].lower() == "all":
slots_to_action = "all"
else:
try:
slots_to_action = [int(slot) for slot in slots_input_args]
except ValueError:
print("Error: Slot numbers must be integers.")
return
if not slots_to_action: # Проверка на пустой список слотов, если не "all"
print("Error: No slots specified.")
return
# Открываем сундук
print("Attempting to open targeted chest...")
if not open_targeted_chest():
print("Failed to open chest. Exiting.")
return
sleep(0.2) # Небольшая задержка после открытия
action_successful = False
if command == "take":
print(f"Attempting to take items from chest slots: {slots_to_action}...")
action_successful = take_items(slots_to_action)
elif command == "store":
# 'store' не может использовать 'all', только конкретные слоты игрока
if isinstance(slots_to_action, str):
print("Error: Cannot 'store all'. Please specify player inventory slots (0-35) to store.")
else:
print(f"Attempting to store items from player inventory slots: {slots_to_action} to chest...")
action_successful = store_items(slots_to_action)
if not action_successful:
print(f"Operation '{command}' failed.")
else:
print(f"Operation '{command}' completed successfully.")
sleep(0.2) # Небольшая задержка перед закрытием
close_chest()
if __name__ == "__main__":
main()