Скрипт:
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
Generated 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.
"""
screen = minecraft.screen
if screen is None:
return False
Generated code
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))
elif isinstance(slots_arg, list):
slots_to_process = slots_arg
else:
return False # Invalid argument type
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
return True
IGNORE_WHEN_COPYING_START
content_copy
download
Use code with caution.
IGNORE_WHEN_COPYING_END
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)
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:
# No echo for error message
return
if not open_targeted_chest():
return
sleep(0.2)
if not take_items(slots_to_action):
close_chest() # Attempt to close chest even if taking items failed
return
sleep(0.2)
close_chest()
IGNORE_WHEN_COPYING_START
content_copy
download
Use code with caution.
IGNORE_WHEN_COPYING_END
if name == "main":
main()
Я хочу использовать этот скрипт как функцию в другом скрипте, импортировав его туда. Проблема заключается в том, что этот скрипт принимает sys.argv для работы. Как мне передать значения для этого скрипта при вызове из другого скрипта?
Assistant
Чтобы использовать этот скрипт как функцию в другом скрипте, вам нужно модифицировать его, чтобы он мог принимать аргументы напрямую, а не только через sys.argv. Вот как это можно сделать:
Измените функцию main(), чтобы она принимала аргументы напрямую:
python
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
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()
Оставьте блок запуска скрипта как есть, чтобы он работал и как самостоятельный скрипт:
python
if __name__ == "__main__":
main()
Теперь в другом скрипте вы можете импортировать и использовать функции:
python
# В вашем другом скрипте
import chest_script # Предполагаем, что ваш скрипт называется chest_script.py
# Вызов с конкретными слотами
chest_script.main(["0", "1", "2"])
# Или вызов с "all"
chest_script.main(["all"])
# Также можно использовать отдельные функции
if chest_script.open_targeted_chest():
chest_script.take_items("all")
chest_script.close_chest()
Такой подход позволит вам использовать скрипт как модуль с функциями, которые можно вызывать с нужными параметрами, и при этом сохранит возможность запускать его как самостоятельный скрипт.
Хотели бы вы, чтобы я объяснил или разбил этот код подробнее?