Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7e43001d9d | ||
|
|
b642204ced | ||
|
|
2d5bf2df22 | ||
|
|
20e53537b1 | ||
|
|
e290aa25fa | ||
|
|
ea887c7019 | ||
|
|
c79ee932a3 | ||
|
|
930f4f3868 | ||
|
|
11add13779 | ||
|
|
9cbadbd551 | ||
|
|
a16b297db7 | ||
|
|
c65705fef8 | ||
|
|
be5fe260e3 | ||
|
|
87eb566a5e | ||
|
|
9783631f94 | ||
|
|
688297e968 | ||
|
|
34d902c46d | ||
|
|
a019b54396 | ||
|
|
95f4aa4821 | ||
|
|
9251edc36a | ||
|
|
43b37b76f6 | ||
|
|
ab8f59a89b | ||
|
|
a60d913c60 | ||
|
|
c323ea8373 | ||
|
|
09035793e2 | ||
|
|
ef7bf1d7da | ||
|
|
5262cbd411 | ||
|
|
4c27f5058e | ||
|
|
b89f0f6ed2 | ||
|
|
b71774b9aa | ||
|
|
659fa49ea1 | ||
|
|
efa2140a91 | ||
|
|
b9d43c7c37 | ||
|
|
7d4f045100 | ||
|
|
1ecec547ae | ||
|
|
9fd565c3c9 | ||
|
|
459e288407 | ||
|
|
23ecfa4446 | ||
|
|
6dbc61284a | ||
|
|
4129686b07 | ||
|
|
67c0ed5af4 | ||
|
|
fab7ea0873 | ||
|
|
61128e8d27 | ||
|
|
563aa53eec | ||
|
|
f45a1b6b82 | ||
|
|
f7f58f5d07 | ||
|
|
b6f7ce9948 | ||
|
|
59c76471f2 | ||
|
|
891f14b988 | ||
|
|
d43533bcfe |
@@ -103,3 +103,4 @@ ENV/
|
||||
|
||||
minecraft_data/
|
||||
mcdata/
|
||||
build/
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# Bot Development Notes
|
||||
|
||||
- Target **Minecraft 26.3 / protocol 777 only**. Do not add old-version compatibility.
|
||||
- Put protocol-777 changes in the main modules; do not create `*_26_3.py` copies.
|
||||
- Entry point: `python mosfet.py` from this repository root; use `.venv` dependencies.
|
||||
- Use the editable sibling `../pyCraft` checkout for shared protocol packet support.
|
||||
- Keep packet IDs and layouts aligned with `PROTOCOL_777.html` and the local 26.3 server; do not infer them from older protocol versions.
|
||||
- You can test bots on the Minecraft server running locally: `SERVER=127.0.0.1`.
|
||||
- The local server runs out of `~/tmp/minecraft`. Read `server.properties` for the RCON password.
|
||||
- Use offline test accounts `mosfet1` and, when an observer is needed, `mosfet2`; read passwords from environment variables, never hard-code them.
|
||||
- If `python mosfet.py` is already running, feel free to kill the script.
|
||||
- Stop test bots and confirm no bot process remains afterward.
|
||||
- Don’t change existing job sequencing/behavior unless the request asks for it; port packet and data handling in place.
|
||||
- Check README and command gates before assuming a legacy command is available on 26.3.
|
||||
- Run tests with `.venv/bin/python -m unittest discover -s tests -v`.
|
||||
- Run a syntax check with `.venv/bin/python -m compileall -q mosfet tests` and `git diff --check`.
|
||||
- Add regression tests for packet encodings, world-state behavior, and migrated job state transitions.
|
||||
- Do not git commit changes until explicitly asked each time.
|
||||
- If changes span both repositories, commit bot and pyCraft changes separately.
|
||||
|
||||
## Theory
|
||||
|
||||
- **Runtime flow:** `mosfet.py` owns global state, the dashboard, and hot reload; it calls `mosfet/connect.py` to connect and initialize the 26.3 runtime.
|
||||
- **Connection setup:** `connect.py` handles offline login/AuthMe and wires the current world, entity, inventory, chat, command, game, and job adapters.
|
||||
- **Packet-to-state flow:** `../pyCraft/minecraft/networking/modern.py` defines protocol-777 wire packets; `mosfet/protocol/modern.py` and `packets.py` add bot-specific packet classes; `mosfet/protocol/managers.py` updates cached world, entities, and inventory.
|
||||
- **Tick flow:** `mosfet/bot.py` advances movement/physics, then ticks the active job and game actions. `mosfet/path.py` supplies A* navigation over `mosfet/world.py` and the loaded block-state cache.
|
||||
- **Commands and jobs:** `mosfet/commands.py` parses chat commands; `mosfet/job.py` selects existing job sequences; each `mosfet/jobs/*.py` module implements a state machine. Keep job sequencing intact unless requested.
|
||||
- **Game actions:** `mosfet/game.py` sends current-protocol actions such as block breaking, inventory selection, item use, and punches/arm swings.
|
||||
- **Data:** `mosfet/info/data/26.3/` contains checked-in Minecraft data; `mosfet/info/{blocks,items,mobs,mcdata}.py` exposes it to runtime code. `PROTOCOL_777.html` is the local packet reference.
|
||||
- **Validation:** `tests/` contains offline regression tests; use the test and compile commands above before committing.
|
||||
|
||||
## Live Checks
|
||||
|
||||
- For one-off live checks, start `mosfet.py` inside a Python heredoc so the test can inspect `app.g` and shut the bot down cleanly. Run from the repo root, keep `SERVER=127.0.0.1`.
|
||||
|
||||
```sh
|
||||
SERVER=127.0.0.1 PLAYER_NAME=mosfet1 .venv/bin/python - <<'PY'
|
||||
import importlib.util, os, threading, time
|
||||
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"mosfet_runtime", os.path.abspath("mosfet.py"))
|
||||
app = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(app)
|
||||
g = app.g
|
||||
runner = threading.Thread(target=app.main, name="mosfet-test", daemon=True)
|
||||
runner.start()
|
||||
try:
|
||||
deadline = time.monotonic() + 20
|
||||
while time.monotonic() < deadline:
|
||||
if g.get("connected") and g.get("pos") and g.chunks.check_loaded(2):
|
||||
break
|
||||
time.sleep(0.1)
|
||||
else:
|
||||
raise TimeoutError("bot did not finish joining/loading nearby chunks")
|
||||
print(time.monotonic(), "mosfet1 position:", tuple(g.pos))
|
||||
g.commands.handle_chat(("CHAT", "test", "tester: 1ping"))
|
||||
finally:
|
||||
if g.get("job") and g.get("connection") and g.connection.connected:
|
||||
g.job.stop()
|
||||
g.running = False
|
||||
runner.join(timeout=5)
|
||||
if runner.is_alive():
|
||||
raise RuntimeError("bot test thread did not stop")
|
||||
PY
|
||||
```
|
||||
|
||||
- Give enough time for the bot and world to load.
|
||||
- Always include the `finally` cleanup.
|
||||
- When printing during live checks, include `time.monotonic()` to better understand the timing of events.
|
||||
@@ -1,48 +1,62 @@
|
||||
# Mosfet Minecraft Bot
|
||||
|
||||
A general-purpose Minecraft 1.16 bot written in Python that uses an actual
|
||||
Minecraft account to play.
|
||||
A Minecraft 26.3 bot written in Python that uses an offline-mode account to
|
||||
play. The connection path targets protocol 777; older Minecraft protocol
|
||||
versions are not supported.
|
||||
|
||||
Mosfet is able to farm wood by cutting trees, farm crops, gather sand, farm
|
||||
netherwart, and trade with villagers to get emeralds. He can eat, sleep, and
|
||||
flee from threats.
|
||||
The original bot included wood/sand/crop farming, villager trading, eating,
|
||||
sleeping, and threat avoidance. On the current 26.3 runtime, path following,
|
||||
crop harvest/replant, and loiter/threat avoidance are migrated; other legacy
|
||||
jobs remain unavailable until ported to protocol 777.
|
||||
|
||||
## Requirements
|
||||
## Requirements and setup
|
||||
|
||||
- Python >= 3.6
|
||||
- pip, virtualenv, git, wget, unzip
|
||||
- Python 3.11+
|
||||
- The locally updated pyCraft checkout at `../pyCraft`
|
||||
|
||||
## Linux Setup
|
||||
|
||||
Assuming Debian / Ubuntu based distro:
|
||||
From the repository root, create and activate a virtual environment, then
|
||||
install the connection-mode dependencies:
|
||||
|
||||
```
|
||||
$ sudo apt update
|
||||
$ sudo apt install build-essential python3 python3-dev python3-pip virtualenv git wget unzip
|
||||
|
||||
$ git clone https://git.tannercollin.com/tanner/minecraft-bot.git
|
||||
$ cd minecraft-bot/
|
||||
$ python3 -m venv .venv
|
||||
$ source .venv/bin/activate
|
||||
$ python -m pip install astar flask flask-cors munch watchdog -e ../pyCraft
|
||||
```
|
||||
|
||||
## Running
|
||||
|
||||
If you want to use the built-in burner account (Minecraft name `mattstack`):
|
||||
Run the bot directly with Python. For the Protospace offline-mode server:
|
||||
|
||||
```
|
||||
$ SERVER=minecraft.example.com ./run_linux.sh
|
||||
$ SERVER=127.0.0.1 python mosfet.py
|
||||
```
|
||||
|
||||
Or, use `PORT` to specify a custom port to connect to:
|
||||
`mosfet.py` defaults to that server, player name `mosfet1`, and the current
|
||||
AuthMe password. Override `SERVER`, `PORT`, `PLAYER_NAME`, or `GAME_PASSWORD`
|
||||
through environment variables as needed. Microsoft authentication is not used.
|
||||
The dashboard is served at `/` (normally `http://localhost:3300`) and can be
|
||||
rebuilt with `npm --prefix web_interface run build`. It uses bundled Minecraft
|
||||
item icons where available, then fetches and caches missing textures from the
|
||||
26.3 asset CDN. If no texture is available, it displays a two-letter
|
||||
placeholder.
|
||||
|
||||
```
|
||||
$ SERVER=localhost PORT=12345 ./run_linux.sh
|
||||
```
|
||||
Inventory item icons are from https://mcitemgallery.com/
|
||||
|
||||
Or, if you have your own alt account for the bot:
|
||||
Python edits under `mosfet/` are hot-reloaded in place; the player connection is
|
||||
kept alive. Edits to connection/bootstrap files are reported as deferred until
|
||||
the next manual start, rather than triggering an automatic reconnect.
|
||||
|
||||
```
|
||||
$ EMAIL=you@domain.com PASSWORD=supersecret SERVER=minecraft.example.com ./run_linux.sh
|
||||
```
|
||||
The 26.3 client now handles AuthMe, chat commands, chunk/world-state caching,
|
||||
modern block/item/entity data, entity tracking, inventory/component sync,
|
||||
path-following movement (`1goto x y z`), inventory draining (`1drain`),
|
||||
normal/trapped-chest caching (`1cache`, also run by 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
|
||||
crop farming), and the crop harvest/replant loop (`1farm crops`), and death-screen respawning (`1respawn`). 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
|
||||
intentionally want another server.
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -62,11 +76,16 @@ would be ran like `1farm wood` or `1pos`.
|
||||
The exception are the below public commands, they can optionally be prefixed with `!`
|
||||
and all bots will run the command.
|
||||
|
||||
Commands can be issued in public chat or private message like `/msg mosfet1
|
||||
1farm wood`. The bot will reply the same way the command was issued.
|
||||
|
||||
Use `echo` to make Mosfet run Minecraft commands. For example, `1echo /sethome
|
||||
home` will cause him to issue the `/sethome` command.
|
||||
The current 26.3 command path handles public chat and direct messages, replying
|
||||
in the same channel. Verified commands are `!ping`, `!pos`, `!loaded`,
|
||||
`!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
|
||||
`1farm crops`. The command catalog below is retained from
|
||||
the legacy bot; other inventory actions, arbitrary block interaction, and the
|
||||
other farming/trading commands are not yet available on 26.3. Common item
|
||||
components (names, damage, enchantments, book
|
||||
contents, and shulker contents) are decoded; unrecognized component types are
|
||||
marked partial rather than silently discarded.
|
||||
|
||||
### Public Commands
|
||||
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
import importlib
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
import json
|
||||
|
||||
import logging
|
||||
log = logging.getLogger('werkzeug')
|
||||
log.setLevel(logging.ERROR)
|
||||
|
||||
from flask import Flask
|
||||
from flask_cors import CORS
|
||||
build_folder = 'web_interface/build'
|
||||
app = Flask(__name__, template_folder=build_folder, static_folder=build_folder, static_url_path='')
|
||||
CORS(app)
|
||||
|
||||
from munch import Munch
|
||||
from watchdog.observers import Observer
|
||||
from watchdog.events import PatternMatchingEventHandler
|
||||
|
||||
from mosfet import bot
|
||||
|
||||
global_state = Munch()
|
||||
g = global_state
|
||||
g.connection = False
|
||||
g.name = None
|
||||
g.mcdata = False
|
||||
g.pos = False
|
||||
g.dimension = None
|
||||
g.item_lock = False
|
||||
g.inv = {}
|
||||
g.objects = {}
|
||||
g.mobs = {}
|
||||
g.players = {}
|
||||
g.player_names = {}
|
||||
g.window = None
|
||||
g.job = None
|
||||
g.correction_count = 0
|
||||
g.holding = 0
|
||||
g.afk = False
|
||||
g.health = 20
|
||||
g.food = 20
|
||||
g.sand_origin = None
|
||||
|
||||
@app.route('/api/global')
|
||||
def api_global():
|
||||
data = json.dumps(g, default=lambda o: str(o), indent=4)
|
||||
|
||||
response = app.response_class(
|
||||
response=data,
|
||||
status=200,
|
||||
mimetype='application/json'
|
||||
)
|
||||
return response
|
||||
|
||||
@app.route('/')
|
||||
def root():
|
||||
return app.send_static_file('index.html')
|
||||
|
||||
reload_timeout = time.time()
|
||||
|
||||
def main():
|
||||
def reload_bot(event):
|
||||
global reload_timeout
|
||||
if time.time() - reload_timeout > 2.0:
|
||||
reload_timeout = time.time()
|
||||
print('Reloading...')
|
||||
g.running = False
|
||||
|
||||
event_handler = PatternMatchingEventHandler(patterns=['*.py'], ignore_patterns=['./main.py'])
|
||||
event_handler.on_any_event = reload_bot
|
||||
|
||||
observer = Observer()
|
||||
observer.schedule(event_handler, 'mosfet', recursive=True)
|
||||
observer.start()
|
||||
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
g.running = True
|
||||
bot.bot(global_state)
|
||||
importlib.reload(bot)
|
||||
except BaseException as e:
|
||||
g.running = True
|
||||
traceback.print_exc()
|
||||
print('Locking...')
|
||||
while g.running:
|
||||
time.sleep(1)
|
||||
importlib.reload(bot)
|
||||
except KeyboardInterrupt:
|
||||
observer.stop()
|
||||
observer.join()
|
||||
|
||||
def run_api():
|
||||
host = '0.0.0.0'
|
||||
port = 3300
|
||||
|
||||
while True:
|
||||
print('Trying to run web interface on port:', port)
|
||||
print('If it works, go to http://localhost:' + str(port))
|
||||
try:
|
||||
app.run(host=host, port=port)
|
||||
except OSError:
|
||||
print()
|
||||
print('Error: Port already taken.')
|
||||
port += 1
|
||||
|
||||
if __name__ == '__main__':
|
||||
threading.Thread(target=run_api).start()
|
||||
time.sleep(1)
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,529 @@
|
||||
import importlib
|
||||
import json
|
||||
import queue
|
||||
import re
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
import sys
|
||||
from math import floor
|
||||
from pathlib import Path
|
||||
|
||||
import logging
|
||||
log = logging.getLogger('werkzeug')
|
||||
log.setLevel(logging.ERROR)
|
||||
|
||||
from flask import Flask, abort, jsonify, request, send_file
|
||||
from flask_cors import CORS
|
||||
build_folder = 'web_interface/build'
|
||||
app = Flask(__name__, template_folder=build_folder, static_folder=build_folder, static_url_path='')
|
||||
CORS(app)
|
||||
|
||||
from munch import Munch
|
||||
from watchdog.observers import Observer
|
||||
from watchdog.events import FileSystemEventHandler
|
||||
|
||||
from mosfet import connect
|
||||
|
||||
global_state = Munch()
|
||||
g = global_state
|
||||
g.connection = False
|
||||
g.connected = False
|
||||
g.connection_status = 'disconnected'
|
||||
g.player_position = None
|
||||
g.last_chat = None
|
||||
g.name = None
|
||||
g.mcdata = False
|
||||
g.pos = False
|
||||
g.dimension = None
|
||||
g.item_lock = False
|
||||
g.inv = {}
|
||||
g.objects = {}
|
||||
g.mobs = {}
|
||||
g.players = {}
|
||||
g.player_names = {}
|
||||
g.window = None
|
||||
g.job = None
|
||||
g.correction_count = 0
|
||||
g.holding = 0
|
||||
g.afk = False
|
||||
g.health = None
|
||||
g.food = None
|
||||
g.hunger = None
|
||||
g.food_saturation = None
|
||||
g.saturation = None
|
||||
g.health_update_received = False
|
||||
g.health_updated_at = None
|
||||
g.dead = False
|
||||
g.sand_origin = None
|
||||
g.reload_lock = threading.RLock()
|
||||
_item_icon_cache = Path(__file__).resolve().parent / 'web_interface' / 'item_cache'
|
||||
_item_icon_locks = {}
|
||||
_item_icon_locks_guard = threading.Lock()
|
||||
|
||||
def _api_plain(value, depth=0):
|
||||
"""Convert item component values into bounded JSON-safe structures."""
|
||||
if depth > 12:
|
||||
return '[nested data omitted]'
|
||||
if value is None or isinstance(value, (str, int, float, bool)):
|
||||
return value
|
||||
if isinstance(value, dict):
|
||||
return {str(key): _api_plain(item, depth + 1)
|
||||
for key, item in value.items()}
|
||||
if isinstance(value, (list, tuple, set)):
|
||||
return [_api_plain(item, depth + 1) for item in value]
|
||||
if (type(value).__name__ in ('Slot', 'ItemStackData') and
|
||||
all(hasattr(value, key) for key in
|
||||
('present', 'item_id', 'item_count'))):
|
||||
return {
|
||||
'present': value.present,
|
||||
'item_id': value.item_id,
|
||||
'item_count': value.item_count,
|
||||
'components': _api_plain(getattr(value, 'components', {}), depth + 1),
|
||||
'components_unknown': bool(getattr(value, 'components_unknown', False)),
|
||||
}
|
||||
if hasattr(value, 'value'):
|
||||
return _api_plain(value.value, depth + 1)
|
||||
if hasattr(value, 'items'):
|
||||
try:
|
||||
return {str(key): _api_plain(item, depth + 1)
|
||||
for key, item in value.items()}
|
||||
except Exception:
|
||||
pass
|
||||
return str(value)
|
||||
|
||||
|
||||
def _api_json_safe(value, depth=0):
|
||||
"""Normalize snapshots for JSON, including non-string dictionary keys."""
|
||||
if depth > 12:
|
||||
return '[nested data omitted]'
|
||||
if value is None or isinstance(value, (str, int, float, bool)):
|
||||
return value
|
||||
if isinstance(value, dict):
|
||||
return {str(key): _api_json_safe(item, depth + 1)
|
||||
for key, item in value.items()}
|
||||
if isinstance(value, (list, tuple, set)):
|
||||
return [_api_json_safe(item, depth + 1) for item in value]
|
||||
|
||||
converted = _api_json_default(value)
|
||||
if converted is value:
|
||||
return str(value)
|
||||
return _api_json_safe(converted, depth + 1)
|
||||
|
||||
|
||||
def _api_json_default(value):
|
||||
"""Serialize live protocol objects without invoking fragile __repr__ code."""
|
||||
from minecraft.networking.packets import Packet
|
||||
|
||||
if isinstance(value, Packet):
|
||||
fields = {key: item for key, item in vars(value).items()
|
||||
if key != 'context'}
|
||||
return {'__type__': type(value).__name__,
|
||||
'packet_name': getattr(value, 'packet_name', None),
|
||||
'fields': fields}
|
||||
if (type(value).__name__ in ('Slot', 'ItemStackData') and
|
||||
all(hasattr(value, key) for key in
|
||||
('present', 'item_id', 'item_count'))):
|
||||
return _api_plain(value)
|
||||
if all(hasattr(value, key) for key in ('x', 'y', 'z')):
|
||||
return {'x': value.x, 'y': value.y, 'z': value.z}
|
||||
if isinstance(value, (bytes, bytearray)):
|
||||
return value.hex()
|
||||
try:
|
||||
return str(value)
|
||||
except Exception:
|
||||
return object.__repr__(value)
|
||||
|
||||
|
||||
@app.route('/api/global')
|
||||
def api_global():
|
||||
snapshot = dict(g)
|
||||
job = g.get('job')
|
||||
job_state = getattr(job, 'state', None) if job else None
|
||||
snapshot['job_state'] = getattr(job_state, '__name__', 'idle')
|
||||
chunks = g.get('chunks')
|
||||
if chunks is not None and hasattr(chunks, 'chunks'):
|
||||
snapshot['chunk_state'] = {
|
||||
'loaded': len(chunks.chunks),
|
||||
'center': chunks.center,
|
||||
'radius': chunks.radius,
|
||||
'dimension': chunks.dimension,
|
||||
}
|
||||
response = app.response_class(
|
||||
response=json.dumps(_api_json_safe(snapshot)),
|
||||
status=200,
|
||||
mimetype='application/json'
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
def _minimap_surface_cell(chunks, x, z):
|
||||
"""Return the uppermost solid/water block in a loaded world column."""
|
||||
from mosfet.info import blocks
|
||||
|
||||
chunk_x, chunk_z = floor(x / 16), floor(z / 16)
|
||||
chunk = chunks.chunks.get((chunk_x, chunk_z))
|
||||
if chunk is None:
|
||||
return None
|
||||
|
||||
local_x, local_z = x - chunk_x * 16, z - chunk_z * 16
|
||||
min_y = getattr(chunks, 'min_y', -64)
|
||||
for section_y in sorted(chunk.sections, reverse=True):
|
||||
if section_y * 16 + 15 < min_y:
|
||||
continue
|
||||
section = chunk.sections[section_y]
|
||||
if section.get('non_empty_blocks') == 0:
|
||||
continue
|
||||
for y in range(section_y * 16 + 15, max(min_y, section_y * 16) - 1, -1):
|
||||
state_id = chunk.get_block_at(local_x, y, local_z)
|
||||
if state_id is None or state_id == blocks.AIR:
|
||||
continue
|
||||
if (state_id in blocks.NON_SOLID_IDS and
|
||||
state_id not in blocks.WATER_IDS):
|
||||
continue
|
||||
return {'block': blocks.BLOCKS.get(state_id, 'unknown'), 'y': y}
|
||||
return None
|
||||
|
||||
|
||||
@app.route('/api/minimap')
|
||||
def api_minimap():
|
||||
position = g.get('pos') or g.get('player_position')
|
||||
chunks = g.get('chunks')
|
||||
if (not g.get('connected') or position is None or position is False or
|
||||
chunks is None or not hasattr(chunks, 'chunks')):
|
||||
return jsonify(ready=False, cells=[])
|
||||
|
||||
try:
|
||||
radius = int(request.args.get('radius', 12))
|
||||
except (TypeError, ValueError):
|
||||
radius = 12
|
||||
radius = max(4, min(32, radius))
|
||||
try:
|
||||
radius_x = int(request.args.get('radius_x', radius))
|
||||
except (TypeError, ValueError):
|
||||
radius_x = radius
|
||||
try:
|
||||
radius_z = int(request.args.get('radius_z', radius))
|
||||
except (TypeError, ValueError):
|
||||
radius_z = radius
|
||||
radius_x = max(4, min(48, radius_x))
|
||||
radius_z = max(4, min(32, radius_z))
|
||||
center_x, center_z = floor(position.x), floor(position.z)
|
||||
center_y = floor(position.y)
|
||||
lock = getattr(chunks, 'lock', None)
|
||||
if lock is not None:
|
||||
lock.acquire()
|
||||
try:
|
||||
cells = [
|
||||
[_minimap_surface_cell(chunks, center_x + dx, center_z + dz)
|
||||
for dx in range(-radius_x, radius_x + 1)]
|
||||
for dz in range(-radius_z, radius_z + 1)
|
||||
]
|
||||
finally:
|
||||
if lock is not None:
|
||||
lock.release()
|
||||
|
||||
ready = any(cell is not None for row in cells for cell in row)
|
||||
return jsonify(
|
||||
ready=ready,
|
||||
center={'x': center_x, 'y': center_y, 'z': center_z},
|
||||
yaw=float(g.get('yaw', 0.0) or 0.0),
|
||||
radius=radius,
|
||||
radius_x=radius_x,
|
||||
radius_z=radius_z,
|
||||
cells=cells if ready else [],
|
||||
)
|
||||
|
||||
|
||||
@app.route('/api/items')
|
||||
def api_items():
|
||||
from mosfet.info.items import ITEM_NAMES
|
||||
data = {str(item_id): name for item_id, name in ITEM_NAMES.items()}
|
||||
return app.response_class(
|
||||
response=json.dumps(data), status=200, mimetype='application/json')
|
||||
|
||||
|
||||
@app.route('/api/inventory/drop', methods=['POST'])
|
||||
def api_inventory_drop():
|
||||
origin = request.headers.get('Origin')
|
||||
if origin:
|
||||
from urllib.parse import urlparse
|
||||
if urlparse(origin).netloc.lower() != request.host.lower():
|
||||
return jsonify(ok=False, error='cross-origin inventory actions are blocked'), 403
|
||||
|
||||
payload = request.get_json(silent=True) or {}
|
||||
if not isinstance(payload, dict):
|
||||
return jsonify(ok=False, error='JSON body must be an object'), 400
|
||||
try:
|
||||
slot = int(payload.get('slot'))
|
||||
except (TypeError, ValueError):
|
||||
return jsonify(ok=False, error='slot must be an integer'), 400
|
||||
action = payload.get('action')
|
||||
if action not in ('one', 'stack', 'matching'):
|
||||
return jsonify(ok=False, error='unknown inventory action'), 400
|
||||
if not g.get('connected') or not g.get('game'):
|
||||
return jsonify(ok=False, error='bot is not connected'), 503
|
||||
|
||||
with g.reload_lock:
|
||||
item = g.inv.get(slot)
|
||||
if slot < 5 or slot > 45 or not item or not getattr(item, 'present', False):
|
||||
return jsonify(ok=False, error='that inventory slot is empty or protected'), 409
|
||||
if action == 'matching':
|
||||
count = g.game.start_dump(item.item_id)
|
||||
if count is None:
|
||||
return jsonify(ok=False, error='another inventory action is running'), 409
|
||||
if not count:
|
||||
return jsonify(ok=False, error='no matching stacks to drop'), 409
|
||||
return jsonify(ok=True, action=action, stacks=count)
|
||||
if not g.game.drop_inventory_slot(
|
||||
slot, whole_stack=(action == 'stack')):
|
||||
return jsonify(ok=False, error='another inventory action is running or the menu is open'), 409
|
||||
return jsonify(ok=True, action=action, slot=slot)
|
||||
|
||||
|
||||
def _item_texture_urls(name):
|
||||
root = 'https://assets.mcasset.cloud/26.3/assets/minecraft/textures'
|
||||
yield root + '/item/{}.png'.format(name)
|
||||
yield root + '/block/{}.png'.format(name)
|
||||
simplified = re.sub(
|
||||
r'_(slab|stairs|wall|fence_gate|fence|door|trapdoor|button|'
|
||||
r'pressure_plate|sign|hanging_sign|carpet|banner|bed|candle)$',
|
||||
'', name)
|
||||
if simplified != name:
|
||||
yield root + '/block/{}.png'.format(simplified)
|
||||
yield root + '/item/{}.png'.format(simplified)
|
||||
|
||||
|
||||
def _fetch_item_texture(name):
|
||||
for url in _item_texture_urls(name):
|
||||
request = urllib.request.Request(
|
||||
url, headers={'User-Agent': 'curl/8.0 Mosfet/26.3'})
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=4) as response:
|
||||
image = response.read(2 * 1024 * 1024 + 1)
|
||||
if len(image) <= 2 * 1024 * 1024 and image.startswith(b'\x89PNG\r\n\x1a\n'):
|
||||
return image
|
||||
except (urllib.error.URLError, TimeoutError, OSError):
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
@app.route('/api/item-icon/<name>')
|
||||
def api_item_icon(name):
|
||||
from mosfet.info.items import ITEM_NAMES
|
||||
if not re.fullmatch(r'[a-z0-9_]+', name):
|
||||
abort(404)
|
||||
if name not in set(ITEM_NAMES.values()):
|
||||
abort(404)
|
||||
|
||||
with _item_icon_locks_guard:
|
||||
lock = _item_icon_locks.setdefault(name, threading.Lock())
|
||||
_item_icon_cache.mkdir(parents=True, exist_ok=True)
|
||||
cached = _item_icon_cache / (name + '.png')
|
||||
with lock:
|
||||
if not cached.is_file():
|
||||
image = _fetch_item_texture(name)
|
||||
if image is None:
|
||||
abort(404)
|
||||
temporary = cached.with_suffix('.tmp')
|
||||
temporary.write_bytes(image)
|
||||
temporary.replace(cached)
|
||||
return send_file(cached, mimetype='image/png', max_age=86400)
|
||||
|
||||
|
||||
@app.route('/')
|
||||
def root():
|
||||
return app.send_static_file('index.html')
|
||||
|
||||
def main():
|
||||
"""Run the 26.3 client with in-place development hot reload.
|
||||
|
||||
Application modules are refreshed while the current socket and player
|
||||
session remain alive. Connection/bootstrap and packet-schema edits are
|
||||
reported as deferred because their listeners cannot safely be replaced
|
||||
without reconnecting.
|
||||
"""
|
||||
g.running = True
|
||||
changes = queue.Queue()
|
||||
observer = Observer()
|
||||
source_root = Path(__file__).resolve().parent / 'mosfet'
|
||||
|
||||
def enqueue_change(event):
|
||||
if event.is_directory:
|
||||
return
|
||||
path = getattr(event, 'dest_path', None) if event.event_type == 'moved' else event.src_path
|
||||
if not path or Path(path).suffix != '.py' or '__pycache__' in path:
|
||||
return
|
||||
changes.put(str(Path(path).resolve()))
|
||||
|
||||
def module_name(path):
|
||||
source = Path(path)
|
||||
try:
|
||||
relative = source.relative_to(source_root)
|
||||
except ValueError:
|
||||
return None
|
||||
parts = list(relative.with_suffix('').parts)
|
||||
if parts and parts[-1] == '__init__':
|
||||
parts.pop()
|
||||
return '.'.join(('mosfet', *parts))
|
||||
|
||||
def reload_changed(paths):
|
||||
paths = sorted(set(path for path in paths if Path(path).is_file()))
|
||||
if not paths:
|
||||
return
|
||||
|
||||
# Don't execute a half-written editor save. If any file is syntactically
|
||||
# invalid, keep the currently running code untouched.
|
||||
try:
|
||||
for path in paths:
|
||||
source = Path(path)
|
||||
compile(source.read_text(encoding='utf-8'), str(source), 'exec')
|
||||
except (OSError, SyntaxError, UnicodeError):
|
||||
print('[hot reload] waiting for a valid save', flush=True)
|
||||
return
|
||||
|
||||
deferred = []
|
||||
modules = []
|
||||
for path in paths:
|
||||
name = module_name(path)
|
||||
if not name:
|
||||
continue
|
||||
if name in ('mosfet.connect', 'mosfet') or name == 'mosfet.monkey_patch':
|
||||
deferred.append(name)
|
||||
else:
|
||||
modules.append(name)
|
||||
if deferred:
|
||||
print('[hot reload] {} changed; connection/bootstrap changes are '
|
||||
'deferred until the next start (no disconnect performed)'.format(
|
||||
', '.join(sorted(set(deferred)))), flush=True)
|
||||
if not modules:
|
||||
return
|
||||
if not g.get('connected') or not g.get('commands'):
|
||||
deadline = time.monotonic() + 15.0
|
||||
while (g.running and time.monotonic() < deadline and
|
||||
(not g.get('connected') or not g.get('commands'))):
|
||||
time.sleep(0.1)
|
||||
if not g.get('connected') or not g.get('commands'):
|
||||
print('[hot reload] runtime not ready; change left for next save',
|
||||
flush=True)
|
||||
return
|
||||
|
||||
managers_changed = bool(
|
||||
{'mosfet.protocol.managers', 'mosfet.protocol.types'} & set(modules))
|
||||
core_modules = {
|
||||
'mosfet.bot', 'mosfet.commands', 'mosfet.game', 'mosfet.job',
|
||||
'mosfet.path', 'mosfet.print_help', 'mosfet.utils',
|
||||
'mosfet.vector', 'mosfet.world', 'mosfet.info.blocks',
|
||||
'mosfet.info.items', 'mosfet.info.mcdata', 'mosfet.info.mobs',
|
||||
}
|
||||
# bot.py reloads the legacy gameplay modules and job state classes as
|
||||
# one coherent group. Reload protocol adapters first so rebinding sees
|
||||
# their latest definitions.
|
||||
direct_modules = [name for name in modules
|
||||
if name not in core_modules and
|
||||
not name.startswith('mosfet.jobs.')]
|
||||
if managers_changed and 'mosfet.protocol.managers' not in direct_modules:
|
||||
direct_modules.append('mosfet.protocol.managers')
|
||||
priority = {
|
||||
'mosfet.protocol.types': 0,
|
||||
'mosfet.protocol.packets': 1,
|
||||
'mosfet.protocol.managers': 2,
|
||||
'mosfet.protocol.modern': 3,
|
||||
}
|
||||
direct_modules.sort(key=lambda name: (priority.get(name, 10), name))
|
||||
|
||||
connection = g.connection
|
||||
packet_lock = getattr(connection, 'packet_listener_lock', None)
|
||||
try:
|
||||
if packet_lock is None:
|
||||
with g.reload_lock:
|
||||
apply_reload(direct_modules, managers_changed)
|
||||
else:
|
||||
# Match packet dispatch's lock order (listener lock, then the
|
||||
# runtime lock) so callbacks cannot race listener replacement.
|
||||
with packet_lock:
|
||||
with g.reload_lock:
|
||||
apply_reload(direct_modules, managers_changed)
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
print('[hot reload] failed; connection left running', flush=True)
|
||||
|
||||
def apply_reload(direct_modules, managers_changed):
|
||||
for name in direct_modules:
|
||||
module = sys.modules.get(name)
|
||||
if module is not None:
|
||||
importlib.reload(module)
|
||||
bot_module = sys.modules.get('mosfet.bot')
|
||||
if bot_module is None:
|
||||
bot_module = importlib.import_module('mosfet.bot')
|
||||
bot_module = importlib.reload(bot_module)
|
||||
bot_module.refresh_runtime(global_state,
|
||||
reload_managers=managers_changed)
|
||||
print('[hot reload] refreshed {} (session preserved)'.format(
|
||||
', '.join(direct_modules) if direct_modules else 'bot runtime'),
|
||||
flush=True)
|
||||
|
||||
def reload_worker():
|
||||
while True:
|
||||
path = changes.get()
|
||||
if path is None:
|
||||
return
|
||||
batch = {path}
|
||||
stopping = False
|
||||
# Coalesce the burst of modified/moved events from editor saves.
|
||||
while True:
|
||||
try:
|
||||
candidate = changes.get(timeout=0.4)
|
||||
except queue.Empty:
|
||||
break
|
||||
if candidate is None:
|
||||
stopping = True
|
||||
break
|
||||
batch.add(candidate)
|
||||
time.sleep(0.15)
|
||||
reload_changed(batch)
|
||||
if stopping:
|
||||
return
|
||||
|
||||
event_handler = FileSystemEventHandler()
|
||||
event_handler.on_modified = enqueue_change
|
||||
event_handler.on_created = enqueue_change
|
||||
event_handler.on_moved = enqueue_change
|
||||
observer.schedule(event_handler, str(source_root), recursive=True)
|
||||
observer.start()
|
||||
worker = threading.Thread(target=reload_worker,
|
||||
name='mosfet-hot-reloader', daemon=True)
|
||||
worker.start()
|
||||
|
||||
try:
|
||||
connect.main(global_state)
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
except BaseException:
|
||||
traceback.print_exc()
|
||||
finally:
|
||||
g.running = False
|
||||
changes.put(None)
|
||||
observer.stop()
|
||||
observer.join()
|
||||
worker.join(timeout=2.0)
|
||||
|
||||
def run_api():
|
||||
host = '0.0.0.0'
|
||||
port = 3300
|
||||
|
||||
while True:
|
||||
print('Trying to run web interface on port:', port)
|
||||
print('If it works, go to http://localhost:' + str(port))
|
||||
try:
|
||||
app.run(host=host, port=port)
|
||||
except OSError:
|
||||
print()
|
||||
print('Error: Port already taken.')
|
||||
port += 1
|
||||
|
||||
if __name__ == '__main__':
|
||||
threading.Thread(target=run_api, daemon=True).start()
|
||||
main()
|
||||
@@ -1,11 +1,13 @@
|
||||
if __name__ == '__main__':
|
||||
print('Run main.py instead.')
|
||||
print('Run mosfet.py instead.')
|
||||
exit(1)
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import importlib
|
||||
import threading
|
||||
import traceback
|
||||
from math import floor, ceil
|
||||
from copy import copy
|
||||
|
||||
@@ -55,8 +57,67 @@ PITCH_ANGLE_DIR = vector.Vector3D((0, 1, 0))
|
||||
YAW_ANGLE_DIR = vector.Vector3D((0, 0, -1))
|
||||
YAW_ANGLE_REF = vector.Vector3D((0, 1, 0))
|
||||
YAW_LOOK_AHEAD = 4
|
||||
PLAYER_EYE_HEIGHT = 1.62
|
||||
MAX_DOWNWARD_PITCH = 45.0
|
||||
|
||||
|
||||
def look_direction_from_eye(position, target):
|
||||
eye = vector.Point3D((position.x, position.y + PLAYER_EYE_HEIGHT,
|
||||
position.z))
|
||||
return eye - target
|
||||
|
||||
|
||||
def navigation_look_target(path_points):
|
||||
if len(path_points) > YAW_LOOK_AHEAD:
|
||||
point = path_points[YAW_LOOK_AHEAD]
|
||||
elif path_points:
|
||||
point = path_points[-1]
|
||||
else:
|
||||
return None
|
||||
return vector.Point3D((point[0], point[1] + 1, point[2]))
|
||||
|
||||
|
||||
def update_pitch(g, look_at_d):
|
||||
if look_at_d is None:
|
||||
target_pitch = 0.0
|
||||
elif look_at_d.length() > 0.6:
|
||||
target_pitch = look_at_d.normalized().angleDeg(PITCH_ANGLE_DIR)
|
||||
target_pitch = (target_pitch - 90) * -1
|
||||
else:
|
||||
return
|
||||
target_pitch = min(target_pitch, MAX_DOWNWARD_PITCH)
|
||||
g.pitch += utils.cap(target_pitch - g.pitch, 10)
|
||||
|
||||
|
||||
def update_yaw(g, look_at_d, max_turn=30, fixed_target=None):
|
||||
if fixed_target is not None:
|
||||
g.yaw += utils.cap(fixed_target - g.yaw, max_turn)
|
||||
return
|
||||
if look_at_d.length() <= 0.6:
|
||||
return
|
||||
target_yaw = look_at_d.normalized().signedAngleDeg(
|
||||
other=YAW_ANGLE_DIR, ref=YAW_ANGLE_REF)
|
||||
delta = (target_yaw - g.yaw + 180) % 360 - 180
|
||||
g.yaw = (g.yaw + utils.cap(delta, max_turn) + 180) % 360 - 180
|
||||
|
||||
|
||||
def missing_movement_chunks(g):
|
||||
"""Return chunks needed for local physics and the next path steps only."""
|
||||
position = g.get('pos')
|
||||
if position is None or position is False:
|
||||
return [(None, None)]
|
||||
points = [position]
|
||||
points.extend(g.path[:2])
|
||||
required = set()
|
||||
for point in points:
|
||||
if hasattr(point, 'x'):
|
||||
x, z = point.x, point.z
|
||||
else:
|
||||
x, z = point[0], point[2]
|
||||
required.add((floor(x / 16), floor(z / 16)))
|
||||
return sorted((x, z) for x, z in required
|
||||
if g.chunks.get_chunk(x, z) is None)
|
||||
|
||||
|
||||
def tick(global_state):
|
||||
g = global_state
|
||||
@@ -64,19 +125,48 @@ def tick(global_state):
|
||||
|
||||
target = None
|
||||
|
||||
# make sure current chunks are loaded for physics
|
||||
if not g.chunks.check_loaded(g.info.render_distance):
|
||||
# Require only chunks touched by local physics and the next path steps.
|
||||
# A few unrelated holes in the wider view cache must not stall jobs.
|
||||
missing_chunks = missing_movement_chunks(g)
|
||||
if missing_chunks:
|
||||
if g.get('movement_status') != 'waiting_for_chunks':
|
||||
print('[movement] status=waiting_for_chunks near {}'.format(
|
||||
utils.pint(p)), flush=True)
|
||||
g.movement_status = 'waiting_for_chunks'
|
||||
if not g.chunks.loading:
|
||||
print('Loading chunks', end='', flush=True)
|
||||
g.chunks.loading = time.time()
|
||||
packet = serverbound.play.PositionAndLookPacket(x=p.x, feet_y=p.y, z=p.z, pitch=0, yaw=0, on_ground=True)
|
||||
now = time.time()
|
||||
if now - g.get('chunk_wait_report_at', 0) >= 5:
|
||||
center = g.chunks.center
|
||||
print('\n[movement] chunk wait: pos={}, center={}, '
|
||||
'loaded={}, missing_required={}'.format(
|
||||
utils.pint(p), g.chunks.center,
|
||||
len(g.chunks.chunks), missing_chunks), flush=True)
|
||||
g.chunk_wait_report_at = now
|
||||
from minecraft.networking.modern import (
|
||||
ClientTickEnd, PlayerPositionRotation,
|
||||
)
|
||||
packet = PlayerPositionRotation(
|
||||
x=p.x, y=p.y, z=p.z, pitch=0, yaw=0, on_ground=True)
|
||||
g.connection.write_packet(packet, force=True)
|
||||
g.connection.write_packet(ClientTickEnd(), force=True)
|
||||
return
|
||||
else:
|
||||
if g.chunks.loading:
|
||||
print()
|
||||
print('Chunks loaded in', round(time.time() - g.chunks.loading, 2), 's')
|
||||
g.chunks.loading = False
|
||||
g.chunk_wait_report_at = 0
|
||||
status = ('draining_inventory' if g.get('draining') else
|
||||
'following_path' if g.path else 'running_job')
|
||||
if g.get('movement_status') != status:
|
||||
print('[movement] status={}'.format(status), flush=True)
|
||||
g.movement_status = status
|
||||
|
||||
door_pause = (g.game.handle_path_doors()
|
||||
if g.get('game') and
|
||||
hasattr(g.game, 'handle_path_doors') else False)
|
||||
|
||||
########## object physics ##########
|
||||
# note: it's possible the chunk data is out of date when this runs
|
||||
@@ -112,7 +202,7 @@ def tick(global_state):
|
||||
|
||||
########## player physics ##########
|
||||
|
||||
if g.path and len(g.path):
|
||||
if g.path and len(g.path) and not door_pause:
|
||||
target = vector.Point3D(g.path[0])
|
||||
target.x += 0.5
|
||||
target.z += 0.5
|
||||
@@ -167,41 +257,42 @@ def tick(global_state):
|
||||
|
||||
if g.look_at:
|
||||
look_at = vector.Point3D(g.look_at)
|
||||
elif g.path and len(g.path) > YAW_LOOK_AHEAD:
|
||||
look_at = vector.Point3D(g.path[YAW_LOOK_AHEAD])
|
||||
elif g.path and len(g.path):
|
||||
look_at = vector.Point3D(g.path[-1])
|
||||
look_at = navigation_look_target(g.path)
|
||||
else:
|
||||
look_at = None
|
||||
|
||||
if look_at:
|
||||
look_at.x += 0.5
|
||||
look_at.y += 0.5
|
||||
look_at.z += 0.5
|
||||
look_at_d = p - look_at
|
||||
|
||||
if look_at_d.length() > 0.6:
|
||||
target_pitch = look_at_d.normalized().angleDeg(PITCH_ANGLE_DIR)
|
||||
target_pitch = (target_pitch - 90) * -1
|
||||
target_pitch_d = target_pitch - g.pitch
|
||||
g.pitch += utils.cap(target_pitch_d, 10)
|
||||
update_pitch(g, look_direction_from_eye(p, look_at))
|
||||
|
||||
# remove vertical component for yaw calculation
|
||||
look_at_d.y = 0
|
||||
|
||||
if look_at_d.length() > 0.6:
|
||||
target_yaw = look_at_d.normalized().signedAngleDeg(other=YAW_ANGLE_DIR, ref=YAW_ANGLE_REF)
|
||||
target_yaw_d = target_yaw - g.yaw
|
||||
target_yaw_d = (target_yaw_d + 180) % 360 - 180
|
||||
g.yaw += utils.cap(target_yaw_d, 30)
|
||||
update_yaw(g, look_at_d,
|
||||
fixed_target=g.get('yaw_target_override'))
|
||||
else:
|
||||
target_pitch_d = 0 - g.pitch
|
||||
g.pitch += utils.cap(target_pitch_d, 10)
|
||||
update_pitch(g, None)
|
||||
if g.get('yaw_target_override') is not None:
|
||||
update_yaw(g, None,
|
||||
fixed_target=g.yaw_target_override)
|
||||
|
||||
packet = serverbound.play.PositionAndLookPacket(x=p.x, feet_y=p.y, z=p.z, pitch=g.pitch, yaw=g.yaw, on_ground=(not in_air))
|
||||
g.connection.write_packet(packet)
|
||||
from minecraft.networking.modern import (
|
||||
ClientTickEnd, PlayerPositionRotation,
|
||||
)
|
||||
packet = PlayerPositionRotation(
|
||||
x=p.x, y=p.y, z=p.z, pitch=g.pitch, yaw=g.yaw,
|
||||
on_ground=(not in_air))
|
||||
# Keep the client-tick boundary after its movement packet on the wire.
|
||||
g.connection.write_packet(packet, force=True)
|
||||
g.connection.write_packet(ClientTickEnd(), force=True)
|
||||
|
||||
g.job.tick()
|
||||
g.game.tick() # order important for correction_count
|
||||
if g.job:
|
||||
g.job.tick()
|
||||
if g.game:
|
||||
g.game.tick() # order important for correction_count
|
||||
|
||||
|
||||
def init(global_state):
|
||||
@@ -221,6 +312,11 @@ def init(global_state):
|
||||
g.break_time = 0
|
||||
|
||||
g.dumping = None
|
||||
g.dump_waiting = None
|
||||
g.dump_dropped = 0
|
||||
g.dump_total = 0
|
||||
g.dump_error = None
|
||||
g.drop_waiting = None
|
||||
g.draining = False
|
||||
g.item_lock = False
|
||||
g.command_lock = False
|
||||
@@ -251,11 +347,8 @@ def bot(global_state):
|
||||
if not SERVER:
|
||||
print()
|
||||
print('You must specify a server to connect to. For example:')
|
||||
print('SERVER=minecraft.example.com ./run_linux.sh')
|
||||
print('SERVER=localhost PORT=12345 ./run_linux.sh')
|
||||
print()
|
||||
print('If you want to use your own account:')
|
||||
print('EMAIL=you@domain.com PASSWORD=supersecret SERVER=minecraft.example.com ./run_linux.sh')
|
||||
print('SERVER=minecraft.example.com python mosfet.py')
|
||||
print('SERVER=localhost PORT=12345 python mosfet.py')
|
||||
os._exit(0)
|
||||
elif not g.connection:
|
||||
if EMAIL and PASSWORD:
|
||||
@@ -274,7 +367,7 @@ def bot(global_state):
|
||||
print('')
|
||||
print('Did you forget to specify an email?')
|
||||
print('If you want to use your own account:')
|
||||
print('EMAIL=you@domain.com PASSWORD=supersecret SERVER=minecraft.example.com ./run_linux.sh')
|
||||
print('Set SERVER and run python mosfet.py.')
|
||||
os._exit(0)
|
||||
else:
|
||||
print('No username or password provided, using burner minecraft account...')
|
||||
@@ -327,3 +420,208 @@ def bot(global_state):
|
||||
g.connection.early_outgoing_packet_listeners = []
|
||||
|
||||
print('Bot module loaded.')
|
||||
|
||||
|
||||
def start_automation(global_state, initialize=True):
|
||||
"""Start or replace the movement worker without replacing the connection."""
|
||||
g = global_state
|
||||
g.protocol_version = 777
|
||||
if initialize:
|
||||
g.time = 0.0
|
||||
g.time_base = None
|
||||
g.time_update_received_at = None
|
||||
g.clock_rate = 1.0
|
||||
g.path = []
|
||||
g.look_at = None
|
||||
g.y_v = 0.0
|
||||
g.y_a = 0.0
|
||||
g.crawling = False
|
||||
g.afk_timeout = 0.0
|
||||
g.objects = g.get('objects') or {}
|
||||
g.players = g.get('players') or {}
|
||||
g.breaking = None
|
||||
g.break_time = 0.0
|
||||
g.item_lock = False
|
||||
g.minimum_cache_slots = g.get('minimum_cache_slots', 27)
|
||||
g.maximum_supply_slots = g.get('maximum_supply_slots', 33)
|
||||
g.draining = False
|
||||
g.dumping = None
|
||||
g.dump_waiting = None
|
||||
g.dump_dropped = 0
|
||||
g.dump_total = 0
|
||||
g.dump_error = None
|
||||
g.drop_waiting = None
|
||||
g.drain_slots = []
|
||||
g.drain_waiting = None
|
||||
g.drain_dropped = 0
|
||||
g.drain_total = 0
|
||||
g.drain_error = None
|
||||
g.correction_count = g.get('correction_count', 0)
|
||||
g.yaw = float(g.get('yaw', 0.0) or 0.0)
|
||||
g.pitch = float(g.get('pitch', 0.0) or 0.0)
|
||||
g.holding_slot = g.get('holding_slot', 0)
|
||||
g.holding_hand = 0
|
||||
g.chunks.loading = False
|
||||
# Readiness below is based on nearby chunks, not unrelated view holes.
|
||||
g.movement_paused = False
|
||||
g.movement_status = 'idle'
|
||||
g.movement_error = None
|
||||
# Keep the active port constrained to the migrated job subset.
|
||||
from mosfet.game import Game
|
||||
from mosfet.job import JobStates
|
||||
g.game = Game(g)
|
||||
g.job = JobStates(g)
|
||||
|
||||
# Preserve active work during hot reloads, but give the worker all fields
|
||||
# introduced by the currently migrated inventory controls.
|
||||
g.setdefault('draining', False)
|
||||
g.setdefault('dumping', None)
|
||||
g.setdefault('dump_waiting', None)
|
||||
g.setdefault('dump_dropped', 0)
|
||||
g.setdefault('dump_total', 0)
|
||||
g.setdefault('dump_error', None)
|
||||
g.setdefault('drop_waiting', None)
|
||||
g.setdefault('drain_slots', [])
|
||||
g.setdefault('drain_waiting', None)
|
||||
g.setdefault('drain_dropped', 0)
|
||||
g.setdefault('drain_total', 0)
|
||||
g.setdefault('drain_error', None)
|
||||
g.setdefault('item_lock', False)
|
||||
g.setdefault('minimum_cache_slots', 27)
|
||||
g.setdefault('maximum_supply_slots', 33)
|
||||
g.setdefault('holding_slot', 0)
|
||||
g.setdefault('holding_hand', 0)
|
||||
g.setdefault('time', 0.0)
|
||||
|
||||
old_stop = g.get('movement_stop_event')
|
||||
old_worker = g.get('movement_thread')
|
||||
if old_stop is not None:
|
||||
old_stop.set()
|
||||
if old_worker is not None and old_worker is not threading.current_thread():
|
||||
old_worker.join(timeout=1.0)
|
||||
stop_event = threading.Event()
|
||||
g.movement_stop_event = stop_event
|
||||
|
||||
def run():
|
||||
from mosfet import bot, utils
|
||||
loaded_since = None
|
||||
initial_world_ready = False
|
||||
|
||||
def set_status(status):
|
||||
if g.movement_status != status:
|
||||
print('[movement] status={}'.format(status), flush=True)
|
||||
g.movement_status = status
|
||||
|
||||
while (not stop_event.is_set() and g.get('running', True) and
|
||||
g.get('connection') and g.connection.connected):
|
||||
started = time.monotonic()
|
||||
now = time.monotonic()
|
||||
game = g.get('game')
|
||||
if game is not None:
|
||||
game._advance_world_time()
|
||||
if not initial_world_ready:
|
||||
if not bot.missing_movement_chunks(g):
|
||||
if loaded_since is None:
|
||||
loaded_since = now
|
||||
elif now - loaded_since >= 0.5:
|
||||
initial_world_ready = True
|
||||
else:
|
||||
loaded_since = None
|
||||
# Wait once for the initial position/chunk batch. After that,
|
||||
# bot.tick() keeps requesting chunks at cache boundaries instead
|
||||
# of gating itself forever on a momentary missing column.
|
||||
movement_ready = initial_world_ready
|
||||
job_active = (g.job is not None and g.job.state != g.job.idle)
|
||||
has_work = (bool(g.path) or job_active or bool(g.breaking) or
|
||||
bool(g.draining) or g.get('dumping') is not None or
|
||||
bool(g.get('drop_waiting')))
|
||||
if g.get('movement_paused'):
|
||||
set_status('paused')
|
||||
elif has_work and not movement_ready:
|
||||
set_status('waiting_for_chunks')
|
||||
elif has_work and movement_ready:
|
||||
try:
|
||||
reload_lock = g.get('reload_lock')
|
||||
if reload_lock is None:
|
||||
bot.tick(g)
|
||||
else:
|
||||
with reload_lock:
|
||||
bot.tick(g)
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
g.movement_error = traceback.format_exc()
|
||||
g.path = []
|
||||
g.movement_status = 'error'
|
||||
print('[movement] stopped after navigation error',
|
||||
flush=True)
|
||||
return
|
||||
elif not has_work and not g.get('movement_paused'):
|
||||
set_status('idle')
|
||||
delay = max(0.0, utils.TICK - (time.monotonic() - started))
|
||||
time.sleep(delay)
|
||||
|
||||
worker = threading.Thread(target=run, name='mosfet-movement',
|
||||
daemon=True)
|
||||
g.movement_thread = worker
|
||||
worker.start()
|
||||
return worker
|
||||
|
||||
|
||||
def _remove_instance_listeners(connection, instance):
|
||||
if connection is None or instance is None:
|
||||
return
|
||||
for name in ('packet_listeners', 'early_packet_listeners',
|
||||
'outgoing_packet_listeners',
|
||||
'early_outgoing_packet_listeners'):
|
||||
listeners = getattr(connection, name, [])
|
||||
listeners[:] = [listener for listener in listeners
|
||||
if getattr(getattr(listener, 'callback', None),
|
||||
'__self__', None) is not instance]
|
||||
|
||||
|
||||
def refresh_runtime(global_state, reload_managers=False):
|
||||
"""Rebind reloadable runtime adapters without touching the connection."""
|
||||
g = global_state
|
||||
connection = g.get('connection')
|
||||
|
||||
_remove_instance_listeners(connection, g.get('chat'))
|
||||
_remove_instance_listeners(connection, g.get('game'))
|
||||
if reload_managers:
|
||||
_remove_instance_listeners(connection, g.get('entities'))
|
||||
_remove_instance_listeners(connection, g.get('inventory'))
|
||||
|
||||
if reload_managers:
|
||||
from mosfet.protocol import managers
|
||||
if connection and g.get('chunks'):
|
||||
current = g.chunks
|
||||
replacement = managers.WorldState(current.min_y)
|
||||
replacement.__dict__.update(current.__dict__)
|
||||
g.chunks = replacement
|
||||
g.world_state = replacement
|
||||
connection.world_state = replacement
|
||||
from mosfet.info import blocks as block_data
|
||||
from mosfet.info import items as item_data
|
||||
g.mcdata = DataManager()
|
||||
g.entities = managers.EntityManager(g)
|
||||
g.inventory = managers.InventoryManager(g)
|
||||
# Keep data references in the reloaded legacy Game adapter current.
|
||||
_ = (block_data, item_data)
|
||||
|
||||
from mosfet.protocol.modern import ModernChatManager
|
||||
g.chat = ModernChatManager(g)
|
||||
g.world = world.World(g)
|
||||
g.game = game.Game(g)
|
||||
|
||||
state_name = getattr(g.get('job'), 'state', None)
|
||||
state_name = getattr(state_name, '__name__', None)
|
||||
g.job = job.JobStates(g)
|
||||
if state_name and state_name != 'idle':
|
||||
replacement_state = getattr(g.job, state_name, None)
|
||||
if replacement_state is not None:
|
||||
g.job.state = replacement_state
|
||||
g.commands = commands.Commands(g)
|
||||
if not reload_managers:
|
||||
g.mcdata = DataManager()
|
||||
start_automation(g, initialize=False)
|
||||
print('[hot reload] runtime adapters refreshed; connection kept alive',
|
||||
flush=True)
|
||||
|
||||
@@ -10,7 +10,6 @@ from mosfet.protocol.types import Slot
|
||||
from mosfet import print_help
|
||||
from mosfet import utils
|
||||
from mosfet import path
|
||||
from mosfet import bot
|
||||
from mosfet.info import blocks
|
||||
from mosfet.info import items
|
||||
from mosfet.info import mobs
|
||||
@@ -21,8 +20,18 @@ class Commands:
|
||||
|
||||
self.g.chat.set_handler(self.handle_chat)
|
||||
|
||||
def _send_reply(self, reply, private=False, sender=None):
|
||||
if private and not reply.startswith('/'):
|
||||
if isinstance(sender, str) and re.fullmatch(r'[A-Za-z0-9_]{1,16}', sender):
|
||||
self.g.chat.send('/msg {} {}'.format(sender, reply))
|
||||
else:
|
||||
self.g.chat.send('/r ' + reply)
|
||||
else:
|
||||
self.g.chat.send(reply)
|
||||
|
||||
def handle_chat(self, message):
|
||||
source, sender, text = message
|
||||
source, sender, text = message[:3]
|
||||
reply_target = message[3] if len(message) > 3 else sender
|
||||
reply = ''
|
||||
private = False
|
||||
for_me = False
|
||||
@@ -39,13 +48,15 @@ class Commands:
|
||||
|
||||
text = text.replace('zzz', '!zzz')
|
||||
|
||||
match = re.match(r'(.*\W+)\s+(['+bot_num+'|!])(\w+) ?(.*)', text)
|
||||
match = re.match(
|
||||
r'(.*\W+)\s+([{}!])(\w+) ?(.*)'.format(re.escape(bot_num)),
|
||||
text)
|
||||
if match:
|
||||
meta, prefix, command, data = match.groups()
|
||||
else:
|
||||
return
|
||||
|
||||
if '-> me' in meta:
|
||||
if source == 'DM' or '-> me' in meta:
|
||||
private = True
|
||||
|
||||
if prefix == bot_num:
|
||||
@@ -54,6 +65,19 @@ class Commands:
|
||||
if data.startswith('[') and data.endswith(']'):
|
||||
command = 'nosquarebrackets'
|
||||
|
||||
unsupported = {
|
||||
'trade', 'gapple', 'fill',
|
||||
'break', 'open', 'click', 'use', 'interact',
|
||||
}
|
||||
if ((command == 'gather' and data.lower().strip() != 'wood') or
|
||||
command in unsupported or
|
||||
(command == 'farm' and
|
||||
not data.lower().startswith('crop') and
|
||||
data.lower().strip() not in ('wood', 'wart'))):
|
||||
reply = 'not migrated to Minecraft 26.3 yet'
|
||||
print('Reply:', reply)
|
||||
self._send_reply(reply, private, reply_target)
|
||||
return
|
||||
|
||||
try:
|
||||
|
||||
@@ -92,6 +116,14 @@ class Commands:
|
||||
if command == 'pos':
|
||||
reply = str(utils.pint(self.g.pos))[1:-1] + ', ' + self.g.dimension
|
||||
|
||||
## !health - replies with health, hunger, and saturation
|
||||
if command == 'health':
|
||||
if not self.g.get('health_update_received'):
|
||||
reply = 'health status not received yet'
|
||||
else:
|
||||
reply = 'health {:.1f}, hunger {}/20, saturation {:.2f}'.format(
|
||||
self.g.health, self.g.food, self.g.food_saturation)
|
||||
|
||||
## !afk - goes AFK with /afk
|
||||
if command == 'afk':
|
||||
if not self.g.afk:
|
||||
@@ -111,30 +143,75 @@ class Commands:
|
||||
if command == 'inv' or command == 'inventory':
|
||||
inv_list = []
|
||||
uniq_item_counts = {}
|
||||
for i in self.g.inv.values():
|
||||
if i.present:
|
||||
inv_list.append((items.ITEM_NAMES[i.item_id], str(i.item_id), i.item_count))
|
||||
for slot, i in self.g.inv.items():
|
||||
if not i.present:
|
||||
continue
|
||||
base_name = items.ITEM_NAMES.get(i.item_id, str(i.item_id))
|
||||
components = getattr(i, 'components', {}) or {}
|
||||
custom_name = components.get('custom_name') or components.get('item_name')
|
||||
if isinstance(custom_name, dict):
|
||||
custom_name = custom_name.get('text') or custom_name.get('raw')
|
||||
display_name = str(custom_name or base_name)
|
||||
details = []
|
||||
for key in ('enchantments', 'stored_enchantments'):
|
||||
for name, level in components.get(key, {}).items():
|
||||
details.append('{} {}'.format(name, level))
|
||||
contents = components.get('container')
|
||||
if contents:
|
||||
nested_count = sum(bool(getattr(item, 'present', False))
|
||||
for item in contents)
|
||||
details.append('{} items inside'.format(nested_count))
|
||||
written = components.get('written_book_content')
|
||||
if written:
|
||||
title = written.get('title', {}).get('raw', '')
|
||||
details.append('book: {} ({} pages)'.format(
|
||||
title, len(written.get('pages', []))))
|
||||
writable = components.get('writable_book_content')
|
||||
if writable:
|
||||
details.append('writable book ({} pages)'.format(
|
||||
len(writable)))
|
||||
if getattr(i, 'components_unknown', False):
|
||||
details.append('components partial')
|
||||
detail_text = ' [{}]'.format(', '.join(details)) if details else ''
|
||||
inv_list.append((slot, display_name, str(i.item_id),
|
||||
i.item_count, detail_text))
|
||||
uniq_item_counts[i.item_id] = (
|
||||
uniq_item_counts.get(i.item_id, 0) + i.item_count)
|
||||
|
||||
if i.item_id not in uniq_item_counts:
|
||||
uniq_item_counts[i.item_id] = 0
|
||||
uniq_item_counts[i.item_id] += i.item_count
|
||||
|
||||
inv_list.sort()
|
||||
console_result = '\n'.join(['{}:{} x {}'.format(*x) for x in inv_list])
|
||||
inv_list.sort(key=lambda entry: (entry[1], entry[2]))
|
||||
console_result = '\n'.join(
|
||||
'slot {}: {}:{} x {}{}'.format(*entry)
|
||||
for entry in inv_list)
|
||||
|
||||
if not console_result:
|
||||
print('Empty')
|
||||
reply = 'empty'
|
||||
else:
|
||||
print(console_result)
|
||||
if self.g.get('inventory_partial', False):
|
||||
print('Warning: inventory contains stacks with undecoded components.')
|
||||
|
||||
reply_result_1 = ', '.join(['{}:{} x {}'.format(*x) for x in inv_list])
|
||||
reply_result_2 = ', '.join(['{}:{} x {}'.format(items.ITEM_NAMES[k], str(k), v) for k,v in uniq_item_counts.items()])
|
||||
reply_result_3 = ', '.join(['{}:{}x{}'.format(items.ITEM_NAMES[k], str(k), v) for k,v in uniq_item_counts.items()])
|
||||
reply_result_4 = ', '.join(['{}:{}x{}'.format(re.sub(r'[aeiou]', '', items.ITEM_NAMES[k]), str(k), v) for k,v in uniq_item_counts.items()])
|
||||
reply_result_5 = ' '.join(['{}{}x{}'.format(re.sub(r'[aeiou]', '', items.ITEM_NAMES[k]), str(k), v) for k,v in uniq_item_counts.items()])
|
||||
reply_result_1 = ', '.join(
|
||||
'{}:{} x {}{}'.format(*entry[1:]) for entry in inv_list)
|
||||
reply_result_components = ', '.join(
|
||||
'{}{}'.format(entry[1], entry[4])
|
||||
for entry in inv_list if entry[4])
|
||||
reply_result_2 = ', '.join(
|
||||
'{}:{} x {}'.format(items.ITEM_NAMES.get(k, str(k)), str(k), v)
|
||||
for k, v in uniq_item_counts.items())
|
||||
reply_result_3 = ', '.join(
|
||||
'{}:{}x{}'.format(items.ITEM_NAMES.get(k, str(k)), str(k), v)
|
||||
for k, v in uniq_item_counts.items())
|
||||
reply_result_4 = ', '.join(
|
||||
'{}:{}x{}'.format(re.sub(r'[aeiou]', '', items.ITEM_NAMES.get(k, str(k))), str(k), v)
|
||||
for k, v in uniq_item_counts.items())
|
||||
reply_result_5 = ' '.join(
|
||||
'{}{}x{}'.format(re.sub(r'[aeiou]', '', items.ITEM_NAMES.get(k, str(k))), str(k), v)
|
||||
for k, v in uniq_item_counts.items())
|
||||
|
||||
for r in [reply_result_1, reply_result_2, reply_result_3, reply_result_4, reply_result_5]:
|
||||
for r in [reply_result_1, reply_result_components,
|
||||
reply_result_2, reply_result_3, reply_result_4,
|
||||
reply_result_5]:
|
||||
reply = r
|
||||
if len(reply) < 256:
|
||||
break
|
||||
@@ -144,7 +221,7 @@ class Commands:
|
||||
seconds = self.g.time * 3.6
|
||||
start = datetime(2000, 1, 1, hour=6)
|
||||
mctime = start + timedelta(seconds=seconds)
|
||||
reply = str(self.g.time) + ' - ' + mctime.strftime('%I:%M %p')
|
||||
reply = str(int(self.g.time)) + ' - ' + mctime.strftime('%I:%M %p')
|
||||
|
||||
## !count [id] - counts the number of items with that id
|
||||
if command == 'count' and data:
|
||||
@@ -155,7 +232,10 @@ class Commands:
|
||||
if command == 'loaded':
|
||||
l = self.g.chunks.get_loaded_area()
|
||||
reply = '{}, {}, {} to {}, {}, {}'.format(*l[0], *l[1])
|
||||
reply += ' - ' + str(len(self.g.chunks.chunks)//16) + ' chunks'
|
||||
chunk_count = getattr(
|
||||
self.g.chunks, 'loaded_chunk_count',
|
||||
len(self.g.chunks.chunks) // 16)
|
||||
reply += ' - ' + str(chunk_count) + ' chunks'
|
||||
|
||||
## !players - prints the current players
|
||||
## !players clear - clears the current player list
|
||||
@@ -244,6 +324,29 @@ class Commands:
|
||||
tree = next(self.g.world.find_trees(pos, 50))
|
||||
reply = str(tree)[1:-1]
|
||||
|
||||
## !signs [distance] - prints nearby sign text
|
||||
if command == 'signs':
|
||||
distance = float(data) if data else 32
|
||||
signs = self.g.world.find_signs(
|
||||
utils.pint(self.g.pos), distance)
|
||||
if signs:
|
||||
results = []
|
||||
for sign in signs:
|
||||
text = ' | '.join(line for line in sign['lines']
|
||||
if line.strip())
|
||||
entry = '{} {}: {}'.format(
|
||||
sign['side'], sign['position'], text)
|
||||
results.append(entry)
|
||||
print('Sign {} {}:'.format(
|
||||
sign['side'], sign['position']))
|
||||
for line in sign['lines']:
|
||||
print(' ' + line)
|
||||
reply = '; '.join(results)
|
||||
if len(reply) > 240:
|
||||
reply = reply[:237] + '...'
|
||||
else:
|
||||
reply = 'no signs found within {} blocks'.format(distance)
|
||||
|
||||
## !info [query] - replies with info on a coordinate, block, item, or player
|
||||
if command == 'info':
|
||||
if not reply:
|
||||
@@ -319,6 +422,18 @@ class Commands:
|
||||
self.g.game.respawn()
|
||||
reply = 'ok'
|
||||
|
||||
## 1sleep [new] - use a bed; `new` forces bed placement
|
||||
if command == 'sleep':
|
||||
self.g.job.sleep_with_bed_states.force_new_bed = (
|
||||
data.lower() in ('new', 'place'))
|
||||
self.g.job.state = self.g.job.sleep
|
||||
reply = 'ok'
|
||||
|
||||
## 1eat - eat one food item when hunger/health requires it
|
||||
if command == 'eat':
|
||||
self.g.job.state = self.g.job.eat
|
||||
reply = 'ok'
|
||||
|
||||
## 1gather wood - gathers wood from the world
|
||||
## 1gather sand - gathers sand from the world
|
||||
if command == 'gather' and data:
|
||||
@@ -356,15 +471,12 @@ class Commands:
|
||||
self.g.job.state = self.g.job.farm_wart
|
||||
reply = 'ok'
|
||||
elif data.startswith('crop'):
|
||||
self.g.job.state = self.g.job.farm_crop
|
||||
reply = 'ok'
|
||||
|
||||
if reply and self.g.dimension == 'overworld':
|
||||
for i in self.g.inv.values():
|
||||
if i.item_id in items.BED_IDS:
|
||||
break
|
||||
mode = self.g.get('game_mode')
|
||||
if mode is not None and mode != 0:
|
||||
reply = 'crop farming needs Survival mode'
|
||||
else:
|
||||
reply += ', I need a bed'
|
||||
self.g.job.state = self.g.job.farm_crop
|
||||
reply = 'ok'
|
||||
|
||||
## 1loiter - stands still but eats, sleeps, and flees
|
||||
if command == 'loiter':
|
||||
@@ -378,13 +490,13 @@ class Commands:
|
||||
|
||||
## 1stop - stops the current job and resets bot
|
||||
if command == 'stop':
|
||||
self.g.job.stop()
|
||||
self.g.game.close_window()
|
||||
bot.init(self.g)
|
||||
reply = 'ok'
|
||||
|
||||
## 1drop - drops the current stack its holding
|
||||
if command == 'drop':
|
||||
self.g.game.drop_stack()
|
||||
reply = 'ok' if self.g.game.drop_stack() else 'empty or busy'
|
||||
|
||||
## 1select [id] - moves item with id into main hand
|
||||
if command == 'select' and data:
|
||||
@@ -397,16 +509,15 @@ class Commands:
|
||||
## 1dump [id] - drops all items matching id
|
||||
if command == 'dump' and data:
|
||||
item = int(data)
|
||||
if self.g.game.count_items([item]):
|
||||
self.g.dumping = item
|
||||
reply = 'ok'
|
||||
else:
|
||||
reply = 'not found'
|
||||
count = self.g.game.start_dump(item)
|
||||
reply = ('busy' if count is None else
|
||||
'ok' if count else 'not found')
|
||||
|
||||
## 1drain - drops all items in inventory
|
||||
if command == 'drain':
|
||||
self.g.draining = True
|
||||
reply = 'ok'
|
||||
count = self.g.game.start_drain()
|
||||
reply = ('busy' if count is None else
|
||||
'ok' if count else 'empty')
|
||||
|
||||
if command == 'gapple':
|
||||
self.g.job.state = self.g.job.find_gapple
|
||||
@@ -465,14 +576,12 @@ class Commands:
|
||||
navpath = self.g.world.path_to_place(pos, goal)
|
||||
|
||||
if navpath:
|
||||
self.g.path = navpath
|
||||
if self.g.job:
|
||||
self.g.job.stop()
|
||||
self.g.path = navpath
|
||||
print(len(navpath))
|
||||
print(navpath)
|
||||
print(round(time.time() - start, 3), 'seconds')
|
||||
if self.g.job:
|
||||
self.g.job.stop()
|
||||
self.g.look_at = None
|
||||
reply = 'ok'
|
||||
else:
|
||||
@@ -493,14 +602,12 @@ class Commands:
|
||||
navpath = self.g.world.path_to_place(pos, goal)
|
||||
|
||||
if navpath:
|
||||
self.g.path = navpath
|
||||
if self.g.job:
|
||||
self.g.job.stop()
|
||||
self.g.path = navpath
|
||||
print(len(navpath))
|
||||
print(navpath)
|
||||
print(round(time.time() - start, 3), 'seconds')
|
||||
if self.g.job:
|
||||
self.g.job.stop()
|
||||
self.g.look_at = None
|
||||
reply = 'ok'
|
||||
else:
|
||||
@@ -578,8 +685,5 @@ class Commands:
|
||||
if len(reply) >= 256:
|
||||
reply = 'reply too long, check console'
|
||||
|
||||
if private and not reply.startswith('/'):
|
||||
self.g.chat.send('/r ' + reply)
|
||||
else:
|
||||
self.g.chat.send(reply)
|
||||
self._send_reply(reply, private, reply_target)
|
||||
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
"""Minimal current-protocol connection mode for AuthMe / offline servers.
|
||||
|
||||
Run with SERVER=... PLAYER_NAME=mosfet1 GAME_PASSWORD=... python -m mosfet.connect
|
||||
"""
|
||||
import os
|
||||
import threading
|
||||
from minecraft.networking.connection import Connection
|
||||
from minecraft.networking.modern import (
|
||||
CancelPostjoinDialog, ChatCommand, PlayGameEventPacket, PlayShowDialog,
|
||||
PlayLogin, SubmitPostjoinLoginDialog, SystemChat, TeleportPosition,
|
||||
)
|
||||
from mosfet.protocol.managers import WorldState
|
||||
from mosfet.vector import Point3D
|
||||
|
||||
|
||||
def component_text(value):
|
||||
"""Best-effort flattening of modern anonymous-NBT chat components."""
|
||||
if value is None:
|
||||
return ''
|
||||
if isinstance(value, (str, int, float)):
|
||||
return str(value)
|
||||
if isinstance(value, (list, tuple)):
|
||||
return ''.join(component_text(item) for item in value)
|
||||
raw = getattr(value, 'value', None)
|
||||
if isinstance(raw, (str, int, float)):
|
||||
return str(raw)
|
||||
if raw is not None and raw is not value and hasattr(raw, 'items'):
|
||||
value = raw
|
||||
tags = getattr(value, 'tags', None)
|
||||
if tags is not None:
|
||||
value = tags
|
||||
if hasattr(value, 'items'):
|
||||
fields = dict(value.items())
|
||||
if 'text' in fields:
|
||||
return component_text(fields['text']) + component_text(fields.get('extra', []))
|
||||
if 'translate' in fields:
|
||||
translation = component_text(fields['translate'])
|
||||
arguments = fields.get('with', [])
|
||||
if translation == 'commands.message.display.incoming' and len(arguments) >= 2:
|
||||
return '{} whispers to you: {}'.format(
|
||||
component_text(arguments[0]),
|
||||
component_text(arguments[1]))
|
||||
return translation + component_text(arguments)
|
||||
return ''.join(component_text(v) for v in fields.values())
|
||||
if isinstance(value, (list, tuple)):
|
||||
return ''.join(component_text(item) for item in value)
|
||||
return str(value)
|
||||
|
||||
|
||||
def main(global_state=None, *, server=None, port=None, username=None,
|
||||
password=None):
|
||||
server = server or os.environ.get('SERVER', '127.0.0.1')
|
||||
port = int(port or os.environ.get('PORT', '25565'))
|
||||
username = username or os.environ.get('PLAYER_NAME', 'mosfet1')
|
||||
password = password or os.environ.get('GAME_PASSWORD', 'mosfetbot')
|
||||
|
||||
connection = Connection(server, port, username=username,
|
||||
allowed_versions=['26.3'],
|
||||
handle_exception=False)
|
||||
connection.authme_password = password
|
||||
connection.world_state = WorldState()
|
||||
connection.dimension_types_by_id = []
|
||||
sent_auth_commands = set()
|
||||
if global_state is not None:
|
||||
global_state.connection = connection
|
||||
global_state.name = username
|
||||
global_state.connected = False
|
||||
global_state.connection_status = 'connecting'
|
||||
global_state.player_position = None
|
||||
global_state.world_state = connection.world_state
|
||||
global_state.chunks = connection.world_state
|
||||
from mosfet.protocol.managers import DataManager
|
||||
global_state.mcdata = DataManager()
|
||||
|
||||
@connection.listener(PlayLogin)
|
||||
def on_play_login(packet):
|
||||
if global_state is not None:
|
||||
global_state.connected = True
|
||||
global_state.connection_status = 'in_game'
|
||||
global_state.player_id = packet.player_id
|
||||
global_state.game_mode = packet.game_mode
|
||||
global_state.dimension = packet.dimension.removeprefix('minecraft:')
|
||||
packet.render_distance = packet.chunk_radius
|
||||
global_state.info = packet
|
||||
global_state.eid = packet.player_id
|
||||
global_state.command_lock = False
|
||||
from mosfet.world import World
|
||||
from mosfet.commands import Commands
|
||||
from mosfet.protocol.modern import ModernChatManager
|
||||
from mosfet.protocol.managers import (
|
||||
ChestOpenManager, EntityManager, InventoryManager,
|
||||
)
|
||||
from mosfet.bot import start_automation
|
||||
global_state.world = World(global_state)
|
||||
global_state.chat = ModernChatManager(global_state)
|
||||
global_state.entities = EntityManager(global_state)
|
||||
global_state.inventory = InventoryManager(global_state)
|
||||
global_state.chest_open_manager = ChestOpenManager(global_state)
|
||||
global_state.commands = Commands(global_state)
|
||||
start_automation(global_state)
|
||||
|
||||
|
||||
def send_auth_command(action):
|
||||
if action in sent_auth_commands:
|
||||
return
|
||||
sent_auth_commands.add(action)
|
||||
command = '/register {0} {0}'.format(password) if action == 'register' \
|
||||
else '/login ' + password
|
||||
print('[AuthMe] sending ' + command.split()[0], flush=True)
|
||||
connection.write_packet(ChatCommand(command=command.lstrip('/')),
|
||||
force=True)
|
||||
|
||||
@connection.listener(PlayGameEventPacket)
|
||||
def on_game_event(packet):
|
||||
if global_state is not None and packet.event == 3:
|
||||
global_state.game_mode = int(packet.value)
|
||||
|
||||
@connection.listener(TeleportPosition)
|
||||
def on_spawn(packet):
|
||||
if global_state is not None:
|
||||
position = getattr(connection, 'player_position', None)
|
||||
if position is None:
|
||||
position = (packet.x, packet.y, packet.z,
|
||||
packet.yaw, packet.pitch)
|
||||
x, y, z, yaw, pitch = position
|
||||
global_state.player_position = (x, y, z)
|
||||
global_state.pos = Point3D(global_state.player_position)
|
||||
global_state.yaw = yaw
|
||||
global_state.pitch = pitch
|
||||
if getattr(connection, 'authme_mode', 'register') == 'register':
|
||||
send_auth_command('register')
|
||||
|
||||
@connection.listener(PlayShowDialog)
|
||||
def on_authme_dialog(packet):
|
||||
is_login = b'login' in packet.payload.lower()
|
||||
print('[AuthMe] dismissing the post-join dialog to use /commands.',
|
||||
flush=True)
|
||||
if is_login:
|
||||
connection.write_packet(SubmitPostjoinLoginDialog(
|
||||
password=password), force=True)
|
||||
else:
|
||||
connection.write_packet(CancelPostjoinDialog(), force=True)
|
||||
send_auth_command('register')
|
||||
|
||||
@connection.listener(SystemChat)
|
||||
def on_system_chat(packet):
|
||||
message = component_text(packet.content)
|
||||
chat_handled = False
|
||||
if global_state is not None:
|
||||
global_state.last_chat = message
|
||||
chat = global_state.get('chat')
|
||||
if chat is not None:
|
||||
chat_handled = chat.handle_system_chat(packet, message)
|
||||
if not chat_handled:
|
||||
print('[server] ' + message, flush=True)
|
||||
lowered = message.lower()
|
||||
if 'already registered' in lowered:
|
||||
send_auth_command('login')
|
||||
elif 'register' in lowered and any(word in lowered for word in
|
||||
('password', 'account', '/register')):
|
||||
send_auth_command('register')
|
||||
elif any(word in lowered for word in
|
||||
('please login', 'please log in', 'log in', '/login',
|
||||
'authenticate', 'authentication required')):
|
||||
send_auth_command('login')
|
||||
|
||||
connection.connect()
|
||||
print('Connected as {} to {}:{} using offline protocol 777.'.format(
|
||||
username, server, port), flush=True)
|
||||
shutdown_requested = False
|
||||
try:
|
||||
while connection.connected:
|
||||
if global_state is not None and not global_state.get('running', True):
|
||||
shutdown_requested = True
|
||||
break
|
||||
thread = connection.networking_thread
|
||||
if thread is None:
|
||||
break
|
||||
thread.join(timeout=0.5)
|
||||
if connection.connected:
|
||||
connection.disconnect(immediate=True)
|
||||
if connection.exception and not shutdown_requested:
|
||||
raise connection.exception
|
||||
print('Connection ended.', flush=True)
|
||||
except KeyboardInterrupt:
|
||||
shutdown_requested = True
|
||||
print('Disconnecting...', flush=True)
|
||||
connection.disconnect()
|
||||
finally:
|
||||
if connection.connected:
|
||||
connection.disconnect(immediate=True)
|
||||
if global_state is not None:
|
||||
worker = global_state.get('movement_thread')
|
||||
if worker and worker is not threading.current_thread():
|
||||
worker.join(timeout=1.0)
|
||||
global_state.connection = False
|
||||
global_state.connected = False
|
||||
global_state.connection_status = 'disconnected'
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -2,10 +2,16 @@ import re
|
||||
import time
|
||||
import random
|
||||
from itertools import count
|
||||
from math import floor, isfinite
|
||||
from munch import Munch
|
||||
|
||||
from minecraft.networking.packets import Packet, clientbound, serverbound
|
||||
from minecraft.networking.types import BlockFace
|
||||
from minecraft.networking.types import BlockFace, Byte, Short, VarInt
|
||||
from minecraft.networking.modern import (
|
||||
ClientTickEnd, ContainerClickSwapPacket, PlayerActionPacket,
|
||||
PunchPacket, SetCarriedItemPacket, SetHeldSlotPacket,
|
||||
UseItemOnBlockPacket,
|
||||
)
|
||||
|
||||
from mosfet.protocol.packets import (
|
||||
SetSlotPacket, PlayerDiggingPacket,
|
||||
@@ -19,6 +25,10 @@ from mosfet.protocol.packets import (
|
||||
)
|
||||
|
||||
from mosfet.protocol.types import Slot
|
||||
from mosfet.protocol.modern import (
|
||||
ClientCommandPacket, PlayerCommandPacket, PlayerInputPacket,
|
||||
UpdateTimePacket, UseItemPacket,
|
||||
)
|
||||
|
||||
from mosfet import utils
|
||||
from mosfet import path
|
||||
@@ -29,7 +39,43 @@ from mosfet.info import items
|
||||
from mosfet.info import mcdata
|
||||
from mosfet.info import mobs
|
||||
|
||||
class Game:
|
||||
class ContainerClickDropPacket(Packet):
|
||||
"""Drop the full stack in one player-inventory slot (protocol 777)."""
|
||||
id = 0x12
|
||||
packet_name = 'container click drop'
|
||||
|
||||
def write_fields(self, packet_buffer):
|
||||
VarInt.send(self.container_id, packet_buffer)
|
||||
VarInt.send(self.state_id, packet_buffer)
|
||||
Short.send(self.slot, packet_buffer)
|
||||
Byte.send(getattr(self, 'button', 1), packet_buffer)
|
||||
VarInt.send(4, packet_buffer) # ContainerInput.THROW
|
||||
VarInt.send(0, packet_buffer) # no changed-slot predictions
|
||||
VarInt.send(0, packet_buffer) # empty carried item stack
|
||||
|
||||
|
||||
class ContainerClickQuickMovePacket(Packet):
|
||||
"""Shift-click an inventory slot into the open container (protocol 777)."""
|
||||
id = 0x12
|
||||
packet_name = 'container click quick move'
|
||||
|
||||
def write_fields(self, packet_buffer):
|
||||
VarInt.send(self.container_id, packet_buffer)
|
||||
VarInt.send(self.state_id, packet_buffer)
|
||||
Short.send(self.slot, packet_buffer)
|
||||
Byte.send(0, packet_buffer) # mouse button
|
||||
VarInt.send(1, packet_buffer) # ContainerInput.QUICK_MOVE
|
||||
VarInt.send(0, packet_buffer) # no changed-slot predictions
|
||||
VarInt.send(0, packet_buffer) # empty carried item stack
|
||||
|
||||
|
||||
class ContainerClosePacket(Packet):
|
||||
id = 0x13
|
||||
packet_name = 'container close'
|
||||
definition = [{'container_id': VarInt}]
|
||||
|
||||
|
||||
class LegacyGame:
|
||||
def __init__(self, global_state):
|
||||
self.g = global_state
|
||||
|
||||
@@ -123,8 +169,59 @@ class Game:
|
||||
if new_path:
|
||||
self.g.path = new_path
|
||||
|
||||
def handle_set_held_slot(self, packet):
|
||||
slot = int(packet.slot)
|
||||
if not 0 <= slot <= 8:
|
||||
return
|
||||
self.g.holding_slot = slot
|
||||
self.g.holding_hand = 0
|
||||
item = self.g.inv.get(36 + slot)
|
||||
self.g.holding = (item.item_id if item and
|
||||
getattr(item, 'present', False) else 0)
|
||||
|
||||
def _set_world_clock(self, total_ticks, partial_tick=0.0, rate=1.0):
|
||||
self.g.time_base = float(total_ticks) + float(partial_tick)
|
||||
self.g.clock_rate = float(rate)
|
||||
self.g.time_update_received_at = time.monotonic()
|
||||
self._advance_world_time()
|
||||
|
||||
def _advance_world_time(self):
|
||||
received_at = self.g.get('time_update_received_at')
|
||||
time_base = self.g.get('time_base')
|
||||
if received_at is None or time_base is None:
|
||||
return
|
||||
elapsed_ticks = max(0.0, time.monotonic() - received_at) / utils.TICK
|
||||
self.g.time = (time_base + elapsed_ticks *
|
||||
self.g.get('clock_rate', 1.0)) % 24000
|
||||
|
||||
def handle_time_update(self, packet):
|
||||
self.g.time = packet.time_of_day % 24000
|
||||
if hasattr(packet, 'time_of_day'):
|
||||
self._set_world_clock(packet.time_of_day)
|
||||
return
|
||||
|
||||
updates = getattr(packet, 'clock_updates', ())
|
||||
if not updates:
|
||||
return
|
||||
|
||||
registries = getattr(self.g.connection, 'registry_ids', {})
|
||||
clock_names = {
|
||||
index: name
|
||||
for name, index in registries.get(
|
||||
'minecraft:world_clock', {}).items()
|
||||
}
|
||||
dimension = self.g.get('dimension', 'overworld')
|
||||
preferred = [
|
||||
update for update in updates
|
||||
if clock_names.get(update['clock_id'], '').removeprefix(
|
||||
'minecraft:') in (dimension, 'overworld')
|
||||
]
|
||||
update = preferred[0] if preferred else updates[0]
|
||||
self.g.clock_id = update['clock_id']
|
||||
self.g.clock_name = clock_names.get(update['clock_id'])
|
||||
self.g.world_age = packet.age
|
||||
self._set_world_clock(update['total_ticks'],
|
||||
update.get('partial_tick', 0.0),
|
||||
update.get('rate', 1.0))
|
||||
|
||||
def handle_set_slot(self, packet):
|
||||
g = self.g
|
||||
@@ -304,10 +401,21 @@ class Game:
|
||||
packet.face = 1
|
||||
self.g.connection.write_packet(packet)
|
||||
|
||||
def open_container(self, location):
|
||||
bid = self.g.chunks.get_block_at(*location)
|
||||
# TODO: check if block is a chest??
|
||||
self.place_block(location, BlockFace.TOP)
|
||||
def open_container(self, location, face=BlockFace.TOP, cursor=None):
|
||||
location = tuple(int(value) for value in location)
|
||||
positions = {location}
|
||||
world = self.g.get('world')
|
||||
if world and hasattr(world, '_double_chest_positions'):
|
||||
positions.update(world._double_chest_positions(location))
|
||||
for offset in ((1, 0, 0), (-1, 0, 0), (0, 0, 1),
|
||||
(0, 0, -1), (0, 1, 0), (0, -1, 0)):
|
||||
positions.add(utils.padd(location, offset))
|
||||
self.g.pending_chest_open = {
|
||||
'position': location,
|
||||
'positions': tuple(sorted(positions)),
|
||||
'requested_at': time.monotonic(),
|
||||
}
|
||||
self.place_block(location, face, cursor=cursor)
|
||||
|
||||
def handle_window(self, packet):
|
||||
print(packet)
|
||||
@@ -568,3 +676,708 @@ class Game:
|
||||
|
||||
if not self.g.path:
|
||||
self.g.correction_count = 0
|
||||
|
||||
|
||||
# Active game facade. The constructor registers no legacy packet listeners;
|
||||
# migrated actions use the 26.3 packet classes imported above.
|
||||
class Game(LegacyGame):
|
||||
ARM_SWING_INTERVAL = 0.1
|
||||
DOOR_AUTO_OPEN_GRACE = 0.25
|
||||
DOOR_TURN_DURATION = 0.3
|
||||
|
||||
def __init__(self, global_state):
|
||||
self.g = global_state
|
||||
self.sequence = 0
|
||||
self.break_deadline = None
|
||||
self.breaking_state = None
|
||||
self.next_swing_at = 0.0
|
||||
self.door_navigation = None
|
||||
self.g.yaw_target_override = None
|
||||
self.g.unopenable_doors = self.g.get('unopenable_doors') or set()
|
||||
|
||||
from mosfet.protocol.packets import SetHealthPacket
|
||||
# Health is a protocol-777 packet, not the legacy UpdateHealthPacket.
|
||||
# Register its decoder on an already-running reactor as well, so a
|
||||
# hot reload can enable health tracking without reconnecting. Rebuild
|
||||
# the base map first to remove any stale decoder for an earlier ID.
|
||||
reactor = self.g.connection.reactor
|
||||
if hasattr(reactor, 'clientbound_packets'):
|
||||
context = self.g.connection.context
|
||||
reactor.clientbound_packets = {
|
||||
packet.get_id(context): packet
|
||||
for packet in reactor.__class__.get_clientbound_packets(context)
|
||||
}
|
||||
reactor.clientbound_packets[SetHealthPacket.id] = SetHealthPacket
|
||||
reactor.clientbound_packets[UpdateTimePacket.id] = UpdateTimePacket
|
||||
self.g.connection.register_packet_listener(
|
||||
self.handle_set_health, SetHealthPacket)
|
||||
self.g.connection.register_packet_listener(
|
||||
self.handle_time_update, UpdateTimePacket)
|
||||
self.g.connection.register_packet_listener(
|
||||
self.handle_set_held_slot, SetHeldSlotPacket)
|
||||
|
||||
self.g.setdefault('time_base', None)
|
||||
self.g.setdefault('time_update_received_at', None)
|
||||
self.g.setdefault('clock_rate', 1.0)
|
||||
|
||||
if not self.g.get('health_update_received', False):
|
||||
self.g.health = None
|
||||
self.g.food = None
|
||||
self.g.hunger = None
|
||||
self.g.food_saturation = None
|
||||
self.g.saturation = None
|
||||
self.g.health_update_received = False
|
||||
self.g.health_updated_at = None
|
||||
self.g.dead = False
|
||||
|
||||
def handle_set_health(self, packet):
|
||||
self.g.health = float(packet.health)
|
||||
self.g.food = int(packet.food)
|
||||
self.g.hunger = self.g.food
|
||||
self.g.food_saturation = float(packet.food_saturation)
|
||||
self.g.saturation = self.g.food_saturation
|
||||
self.g.health_update_received = True
|
||||
self.g.health_updated_at = time.time()
|
||||
self.g.dead = self.g.health <= 0
|
||||
print('[status] health={:.1f} hunger={} saturation={:.2f}'.format(
|
||||
self.g.health, self.g.food, self.g.food_saturation), flush=True)
|
||||
|
||||
def _send_action(self, packet):
|
||||
self.g.connection.write_packet(packet, force=True)
|
||||
self.g.connection.write_packet(ClientTickEnd(), force=True)
|
||||
|
||||
def _next_sequence(self):
|
||||
self.sequence += 1
|
||||
return self.sequence
|
||||
|
||||
def _door_info(self, position):
|
||||
state_id = self.g.world.block_at(*position)
|
||||
if state_id not in blocks.DOOR_IDS:
|
||||
return None
|
||||
properties = blocks.PROPS.get(state_id, {})
|
||||
lower = tuple(position)
|
||||
if properties.get('half') == 'upper':
|
||||
lower = utils.padd(lower, path.BLOCK_BELOW)
|
||||
lower_state = self.g.world.block_at(*lower)
|
||||
if lower_state in blocks.DOOR_IDS:
|
||||
state_id = lower_state
|
||||
properties = blocks.PROPS.get(state_id, {})
|
||||
return lower, state_id, properties
|
||||
|
||||
def _toggle_door(self, lower, state_id):
|
||||
position = utils.pint(self.g.pos)
|
||||
dx, dz = position[0] - lower[0], position[2] - lower[2]
|
||||
if abs(dx) > abs(dz):
|
||||
if dx >= 0:
|
||||
face, cursor = BlockFace.EAST, (0.95, 0.5, 0.5)
|
||||
else:
|
||||
face, cursor = BlockFace.WEST, (0.05, 0.5, 0.5)
|
||||
elif abs(dz) > 0:
|
||||
if dz >= 0:
|
||||
face, cursor = BlockFace.SOUTH, (0.5, 0.5, 0.95)
|
||||
else:
|
||||
face, cursor = BlockFace.NORTH, (0.5, 0.5, 0.05)
|
||||
else:
|
||||
face, cursor = BlockFace.TOP, (0.5, 0.95, 0.5)
|
||||
|
||||
boxes = blocks.COLLISION_BOXES.get(state_id, ())
|
||||
if boxes:
|
||||
box = boxes[0]
|
||||
cursor = ((box[0] + box[3]) / 2,
|
||||
(box[1] + box[4]) / 2,
|
||||
(box[2] + box[5]) / 2)
|
||||
self.place_block(lower, face, cursor=cursor)
|
||||
|
||||
def _look_at_with_yaw_separation(self, target, fallback=None):
|
||||
"""Keep target yaw far enough from the player to avoid the near-zero guard."""
|
||||
player = self.g.pos
|
||||
player_x = player.x if hasattr(player, 'x') else player[0]
|
||||
player_z = player.z if hasattr(player, 'z') else player[2]
|
||||
center = [target[0] + 0.5, target[1] + 0.5, target[2] + 0.5]
|
||||
dx, dz = player_x - center[0], player_z - center[2]
|
||||
distance = utils.hypot(dx, dz)
|
||||
if distance < 0.8:
|
||||
if distance < 1e-6 and fallback is not None:
|
||||
dx, dz = fallback
|
||||
distance = utils.hypot(dx, dz)
|
||||
if distance > 1e-6:
|
||||
scale = 0.8 / distance
|
||||
center[0] = player_x - dx * scale
|
||||
center[2] = player_z - dz * scale
|
||||
return tuple(value - 0.5 for value in center)
|
||||
|
||||
def _door_yaw_target(self, look_at):
|
||||
target = vector.Point3D(look_at)
|
||||
target.x += 0.5
|
||||
target.z += 0.5
|
||||
position = self.g.pos
|
||||
if not hasattr(position, 'x'):
|
||||
position = vector.Point3D(position)
|
||||
direction = position - target
|
||||
direction.y = 0
|
||||
if direction.length() <= 0.6:
|
||||
return self.g.yaw
|
||||
return direction.normalized().signedAngleDeg(
|
||||
other=bot.YAW_ANGLE_DIR, ref=bot.YAW_ANGLE_REF)
|
||||
|
||||
def _begin_door_turn(self, navigation, target, fallback=None):
|
||||
look_at = self._look_at_with_yaw_separation(target, fallback)
|
||||
yaw = self.g.yaw
|
||||
target_yaw = self._door_yaw_target(look_at)
|
||||
delta = (target_yaw - yaw + 180) % 360 - 180
|
||||
navigation['yaw_origin'] = yaw
|
||||
navigation['yaw_door_target'] = yaw + delta
|
||||
self.g.yaw_target_override = navigation['yaw_door_target']
|
||||
self.g.look_at = look_at
|
||||
|
||||
def _begin_door_return(self, navigation, now):
|
||||
navigation['phase'] = 'turning_back'
|
||||
navigation['deadline'] = now + self.DOOR_TURN_DURATION
|
||||
self.g.yaw_target_override = navigation.get('yaw_origin')
|
||||
target = navigation.get('forward_look_at')
|
||||
self.g.look_at = (self._look_at_with_yaw_separation(target)
|
||||
if target is not None else
|
||||
navigation['previous_look_at'])
|
||||
|
||||
def _restore_door_look(self, navigation):
|
||||
self.g.look_at = navigation['previous_look_at']
|
||||
self.g.yaw_target_override = None
|
||||
self.door_navigation = None
|
||||
|
||||
def handle_path_doors(self):
|
||||
"""Open closed wooden doors in the active route and close them after crossing."""
|
||||
now = time.monotonic()
|
||||
navigation = self.door_navigation
|
||||
if navigation is not None:
|
||||
lower = navigation['position']
|
||||
info = self._door_info(lower)
|
||||
is_open = bool(info and info[2].get('open') == 'true')
|
||||
|
||||
if navigation['phase'] == 'checking':
|
||||
if (info is None or
|
||||
info[1] not in blocks.OPENABLE_DOOR_IDS):
|
||||
self._restore_door_look(navigation)
|
||||
return False
|
||||
if is_open:
|
||||
navigation['phase'] = 'crossing'
|
||||
navigation['opened_by_bot'] = False
|
||||
navigation['saw_open'] = True
|
||||
self.g.look_at = navigation['previous_look_at']
|
||||
return False
|
||||
if now >= navigation['deadline']:
|
||||
navigation['phase'] = 'opening'
|
||||
navigation['opened_by_bot'] = True
|
||||
navigation['deadline'] = now + 2.0
|
||||
print('[door] opening on path at', lower, flush=True)
|
||||
self._toggle_door(lower, info[1])
|
||||
return True
|
||||
|
||||
if navigation['phase'] == 'opening':
|
||||
if not self.g.path:
|
||||
self._restore_door_look(navigation)
|
||||
return False
|
||||
if is_open:
|
||||
navigation['phase'] = 'crossing'
|
||||
navigation['saw_open'] = True
|
||||
self.g.look_at = navigation['previous_look_at']
|
||||
return False
|
||||
if now > navigation['deadline']:
|
||||
upper = utils.padd(lower, path.BLOCK_ABOVE)
|
||||
self.g.unopenable_doors.update((lower, upper))
|
||||
goal = navigation['goal']
|
||||
self._restore_door_look(navigation)
|
||||
current = utils.pint(self.g.pos)
|
||||
self.g.path = (self.g.world.path_to_place(current, goal)
|
||||
or [])
|
||||
print('Door did not open; routing around', lower,
|
||||
flush=True)
|
||||
return False
|
||||
return True
|
||||
|
||||
if navigation['phase'] == 'crossing':
|
||||
if navigation['after'] is not None and \
|
||||
utils.pint(self.g.pos) == navigation['after']:
|
||||
if navigation.get('saw_open', False):
|
||||
navigation['phase'] = 'turning_to_close'
|
||||
navigation['deadline'] = (
|
||||
now + self.DOOR_TURN_DURATION)
|
||||
navigation['close_door'] = (
|
||||
navigation.get('opened_by_bot', False) and
|
||||
is_open and info is not None and
|
||||
info[2].get('powered') != 'true')
|
||||
after = navigation['after']
|
||||
fallback = ((after[0] - lower[0],
|
||||
after[2] - lower[2])
|
||||
if after is not None else None)
|
||||
self._begin_door_turn(navigation, lower, fallback)
|
||||
return True
|
||||
self._restore_door_look(navigation)
|
||||
return False
|
||||
if not is_open:
|
||||
# If a pressure plate or redstone opened it, wait briefly
|
||||
# for its state update rather than toggling it closed.
|
||||
if (info is not None and
|
||||
info[1] in blocks.OPENABLE_DOOR_IDS and
|
||||
lower in self.g.path):
|
||||
navigation['phase'] = 'checking'
|
||||
navigation['opened_by_bot'] = False
|
||||
navigation['deadline'] = (
|
||||
now + self.DOOR_AUTO_OPEN_GRACE)
|
||||
return True
|
||||
if (navigation.get('saw_open') and
|
||||
navigation['after'] is not None):
|
||||
return False
|
||||
self._restore_door_look(navigation)
|
||||
return False
|
||||
|
||||
if navigation['phase'] == 'turning_to_close':
|
||||
if now >= navigation['deadline']:
|
||||
if (navigation.get('close_door') and is_open and
|
||||
info is not None and
|
||||
info[2].get('powered') != 'true'):
|
||||
navigation['phase'] = 'closing'
|
||||
navigation['deadline'] = now + 2.0
|
||||
print('[door] closing after crossing at', lower,
|
||||
flush=True)
|
||||
self._toggle_door(lower, info[1])
|
||||
else:
|
||||
self._begin_door_return(navigation, now)
|
||||
return True
|
||||
|
||||
if navigation['phase'] == 'closing':
|
||||
if not is_open or now > navigation['deadline']:
|
||||
self._begin_door_return(navigation, now)
|
||||
return True
|
||||
|
||||
if navigation['phase'] == 'turning_back':
|
||||
if now >= navigation['deadline']:
|
||||
self._restore_door_look(navigation)
|
||||
return False
|
||||
return True
|
||||
|
||||
if not self.g.path:
|
||||
return False
|
||||
|
||||
current = utils.pint(self.g.pos)
|
||||
path_index = 0
|
||||
if (len(self.g.path) > 1 and
|
||||
tuple(self.g.path[0]) == current):
|
||||
path_index = 1
|
||||
if path_index >= len(self.g.path):
|
||||
return False
|
||||
info = self._door_info(tuple(self.g.path[path_index]))
|
||||
if info is None:
|
||||
return False
|
||||
lower, state_id, properties = info
|
||||
is_open = properties.get('open') == 'true'
|
||||
if (not is_open and state_id not in blocks.OPENABLE_DOOR_IDS) or \
|
||||
utils.phyp(current, lower) > 3:
|
||||
return False
|
||||
|
||||
after_index = path_index + 1
|
||||
after = (tuple(self.g.path[after_index])
|
||||
if after_index < len(self.g.path) else None)
|
||||
if after_index + 1 < len(self.g.path):
|
||||
forward_look_at = tuple(self.g.path[after_index + 1])
|
||||
elif after is not None:
|
||||
forward_look_at = tuple(
|
||||
after[i] + 2 * (after[i] - lower[i]) for i in range(3))
|
||||
else:
|
||||
forward_look_at = None
|
||||
navigation = {
|
||||
'position': lower,
|
||||
'after': after,
|
||||
'goal': tuple(self.g.path[-1]),
|
||||
'phase': 'crossing' if is_open else 'checking',
|
||||
'deadline': now + self.DOOR_AUTO_OPEN_GRACE,
|
||||
'opened_by_bot': False,
|
||||
'saw_open': is_open,
|
||||
'close_door': False,
|
||||
'previous_look_at': self.g.get('look_at'),
|
||||
'forward_look_at': forward_look_at,
|
||||
}
|
||||
self.door_navigation = navigation
|
||||
if not is_open:
|
||||
self.g.look_at = lower
|
||||
return True
|
||||
return False
|
||||
|
||||
def animate(self):
|
||||
"""Ask the 26.3 server to broadcast a main-hand punch animation."""
|
||||
self._send_action(PunchPacket())
|
||||
|
||||
def break_block(self, location):
|
||||
location = tuple(int(value) for value in location)
|
||||
block_id = self.g.chunks.get_block_at(*location)
|
||||
if block_id is None or block_id == blocks.AIR:
|
||||
return False
|
||||
|
||||
holding = self.g.get('holding', 0)
|
||||
held_slot = (45 if self.g.get('holding_hand', 0) == 1 else
|
||||
36 + int(self.g.get('holding_slot', 0) or 0))
|
||||
held_stack = self.g.get('inv', {}).get(held_slot)
|
||||
enchantments = (getattr(held_stack, 'components', {}) or {}).get(
|
||||
'enchantments', {})
|
||||
in_water = False
|
||||
on_ground = True
|
||||
position = self.g.get('pos')
|
||||
chunks = self.g.get('chunks')
|
||||
if position is not None and chunks is not None:
|
||||
x, y, z = (floor(position.x), floor(position.y),
|
||||
floor(position.z))
|
||||
support = chunks.get_block_at(x, floor(position.y - 0.2), z)
|
||||
if support is not None:
|
||||
on_ground = support not in blocks.NON_SOLID_IDS
|
||||
feet = chunks.get_block_at(x, y, z)
|
||||
eyes = chunks.get_block_at(x, floor(position.y + 1.62), z)
|
||||
in_water = feet in blocks.WATER_IDS or eyes in blocks.WATER_IDS
|
||||
|
||||
duration = utils.break_time(
|
||||
block_id, holding, in_water=in_water, on_ground=on_ground,
|
||||
enchantments=enchantments, effects=self.g.get('effects', {}))
|
||||
if not isfinite(duration):
|
||||
return False
|
||||
|
||||
packet = PlayerActionPacket(
|
||||
action=0, location=location, face=1,
|
||||
sequence=self._next_sequence())
|
||||
self._send_action(packet)
|
||||
self.g.breaking = location
|
||||
self.breaking_state = block_id
|
||||
now = time.monotonic()
|
||||
self.break_deadline = now + duration
|
||||
self.animate()
|
||||
self.next_swing_at = now + self.ARM_SWING_INTERVAL
|
||||
return True
|
||||
|
||||
def respawn(self):
|
||||
self.g.respawn_requested_at = time.monotonic()
|
||||
self.g.connection.write_packet(
|
||||
ClientCommandPacket(action_id=0), force=True)
|
||||
self.g.connection.write_packet(ClientTickEnd(), force=True)
|
||||
|
||||
def _send_drop_click(self, slot, button=1):
|
||||
state_id = self.g.inventory_state_ids.get(0, 0)
|
||||
self.g.connection.write_packet(ContainerClickDropPacket(
|
||||
container_id=0, state_id=state_id, slot=slot,
|
||||
button=button), force=True)
|
||||
self.g.connection.write_packet(ClientTickEnd(), force=True)
|
||||
return state_id
|
||||
|
||||
def drop_inventory_slot(self, slot, whole_stack=True):
|
||||
"""Drop one item or the full stack from a player inventory slot."""
|
||||
try:
|
||||
slot = int(slot)
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
if (not 5 <= slot <= 45 or self.g.get('window') is not None or
|
||||
self.g.get('draining') or self.g.get('dumping') is not None or
|
||||
self.g.get('drop_waiting')):
|
||||
return False
|
||||
item = self.g.inv.get(slot)
|
||||
if not item or not getattr(item, 'present', False):
|
||||
return False
|
||||
count = int(item.item_count or 0)
|
||||
if count <= 0:
|
||||
return False
|
||||
button = 1 if whole_stack else 0
|
||||
state_id = self._send_drop_click(slot, button)
|
||||
self.g.drop_waiting = {
|
||||
'slot': slot, 'item_id': item.item_id,
|
||||
'expected_count': 0 if whole_stack else count - 1,
|
||||
'sent_at': time.monotonic(), 'state_id': state_id,
|
||||
}
|
||||
return True
|
||||
|
||||
def drop_stack(self):
|
||||
"""Drop the full stack in the currently held hand (26.3 click)."""
|
||||
slot = (45 if self.g.get('holding_hand', 0) == 1 else
|
||||
36 + int(self.g.get('holding_slot', 0) or 0))
|
||||
return self.drop_inventory_slot(slot, whole_stack=True)
|
||||
|
||||
def _tick_single_drop(self):
|
||||
waiting = self.g.get('drop_waiting')
|
||||
if not waiting:
|
||||
return
|
||||
item = self.g.inv.get(waiting['slot'])
|
||||
remaining = (item.item_count if item and
|
||||
getattr(item, 'present', False) and
|
||||
item.item_id == waiting['item_id'] else 0)
|
||||
if remaining <= waiting['expected_count']:
|
||||
print('[drop] server confirmed slot {} updated'.format(
|
||||
waiting['slot']), flush=True)
|
||||
self.g.drop_waiting = None
|
||||
elif time.monotonic() - waiting['sent_at'] > 3.0:
|
||||
print('[drop] timed out waiting for inventory update on slot {}'.format(
|
||||
waiting['slot']), flush=True)
|
||||
self.g.drop_waiting = None
|
||||
|
||||
def start_dump(self, item_id):
|
||||
"""Start dropping every stack of an item id from player inventory."""
|
||||
if (self.g.get('window') is not None or self.g.get('draining') or
|
||||
self.g.get('dumping') is not None or self.g.get('drop_waiting')):
|
||||
return None
|
||||
slots = [slot for slot, item in self.g.inv.items()
|
||||
if 5 <= slot <= 45 and getattr(item, 'present', False)
|
||||
and item.item_id == item_id]
|
||||
if not slots:
|
||||
return 0
|
||||
self.g.dumping = item_id
|
||||
self.g.dump_waiting = None
|
||||
self.g.dump_dropped = 0
|
||||
self.g.dump_total = len(slots)
|
||||
self.g.dump_error = None
|
||||
return len(slots)
|
||||
|
||||
def _tick_dump(self):
|
||||
item_id = self.g.get('dumping')
|
||||
if item_id is None:
|
||||
return
|
||||
waiting = self.g.get('dump_waiting')
|
||||
if waiting:
|
||||
item = self.g.inv.get(waiting['slot'])
|
||||
if (not item or not getattr(item, 'present', False) or
|
||||
item.item_id != item_id):
|
||||
self.g.dump_dropped += 1
|
||||
print('[dump] dropped stack from slot {}; {}/{} complete'.format(
|
||||
waiting['slot'], self.g.dump_dropped,
|
||||
self.g.dump_total), flush=True)
|
||||
self.g.dump_waiting = None
|
||||
elif time.monotonic() - waiting['sent_at'] > 3.0:
|
||||
self.g.dump_error = 'server did not clear inventory slot {}'.format(
|
||||
waiting['slot'])
|
||||
print('[dump] stopped: ' + self.g.dump_error, flush=True)
|
||||
self.g.dumping = None
|
||||
self.g.dump_waiting = None
|
||||
return
|
||||
else:
|
||||
return
|
||||
|
||||
for slot in range(5, 46):
|
||||
item = self.g.inv.get(slot)
|
||||
if item and getattr(item, 'present', False) and item.item_id == item_id:
|
||||
state_id = self._send_drop_click(slot)
|
||||
self.g.dump_waiting = {
|
||||
'slot': slot, 'item_count': item.item_count,
|
||||
'sent_at': time.monotonic(), 'state_id': state_id,
|
||||
}
|
||||
return
|
||||
|
||||
print('[dump] complete: dropped {} stacks of item {}'.format(
|
||||
self.g.dump_dropped, item_id), flush=True)
|
||||
self.g.dumping = None
|
||||
self.g.dump_waiting = None
|
||||
|
||||
def leave_bed(self):
|
||||
self._send_action(PlayerCommandPacket(
|
||||
entity_id=self.g.eid, action_id=0, jump_boost=0))
|
||||
|
||||
def use_item(self, hand=0):
|
||||
self._send_action(UseItemPacket(
|
||||
hand=hand, sequence=self._next_sequence(),
|
||||
yaw=float(self.g.get('yaw', 0.0)),
|
||||
pitch=float(self.g.get('pitch', 0.0))))
|
||||
|
||||
def start_drain(self):
|
||||
if (self.g.get('window') is not None or
|
||||
self.g.get('dumping') is not None or
|
||||
self.g.get('drop_waiting')):
|
||||
return None
|
||||
slots = [slot for slot, item in sorted(self.g.inv.items())
|
||||
if 9 <= slot <= 45 and getattr(item, 'present', False)]
|
||||
self.g.drain_slots = slots
|
||||
self.g.drain_waiting = None
|
||||
self.g.drain_dropped = 0
|
||||
self.g.drain_total = len(slots)
|
||||
self.g.drain_error = None
|
||||
self.g.draining = bool(slots)
|
||||
return len(slots)
|
||||
|
||||
def _tick_drain(self):
|
||||
waiting = self.g.get('drain_waiting')
|
||||
if waiting:
|
||||
slot = waiting['slot']
|
||||
state_id = self.g.inventory_state_ids.get(0, 0)
|
||||
if state_id != waiting['state_id']:
|
||||
item = self.g.inv.get(slot)
|
||||
if not item or not getattr(item, 'present', False):
|
||||
self.g.drain_dropped += 1
|
||||
print('[drain] dropped stack from slot {}; {}/{} complete'.format(
|
||||
slot, self.g.drain_dropped, self.g.drain_total), flush=True)
|
||||
self.g.drain_waiting = None
|
||||
else:
|
||||
self.g.drain_error = 'server did not clear inventory slot {}'.format(slot)
|
||||
self.g.draining = False
|
||||
self.g.drain_waiting = None
|
||||
print('[drain] stopped: ' + self.g.drain_error, flush=True)
|
||||
return
|
||||
elif time.monotonic() - waiting['sent_at'] > 3.0:
|
||||
self.g.drain_error = 'timed out waiting for inventory update on slot {}'.format(slot)
|
||||
self.g.draining = False
|
||||
self.g.drain_waiting = None
|
||||
print('[drain] stopped: ' + self.g.drain_error, flush=True)
|
||||
return
|
||||
else:
|
||||
return
|
||||
|
||||
while self.g.drain_slots:
|
||||
slot = self.g.drain_slots.pop(0)
|
||||
item = self.g.inv.get(slot)
|
||||
if not item or not getattr(item, 'present', False):
|
||||
continue
|
||||
state_id = self.g.inventory_state_ids.get(0, 0)
|
||||
packet = ContainerClickDropPacket(
|
||||
container_id=0, state_id=state_id, slot=slot)
|
||||
self.g.connection.write_packet(packet, force=True)
|
||||
self.g.connection.write_packet(ClientTickEnd(), force=True)
|
||||
self.g.drain_waiting = {
|
||||
'slot': slot, 'state_id': state_id,
|
||||
'item_count': item.item_count, 'sent_at': time.monotonic(),
|
||||
}
|
||||
return
|
||||
|
||||
self.g.draining = False
|
||||
self.g.drain_waiting = None
|
||||
print('[drain] complete: dropped {} stacks'.format(
|
||||
self.g.drain_dropped), flush=True)
|
||||
|
||||
def tick(self):
|
||||
self._advance_world_time()
|
||||
self._tick_single_drop()
|
||||
if self.g.get('dumping') is not None:
|
||||
self._tick_dump()
|
||||
if self.g.get('draining'):
|
||||
self._tick_drain()
|
||||
if not self.g.get('breaking') or self.break_deadline is None:
|
||||
return
|
||||
now = time.monotonic()
|
||||
if now < self.break_deadline:
|
||||
if now >= self.next_swing_at:
|
||||
self.animate()
|
||||
self.next_swing_at = now + self.ARM_SWING_INTERVAL
|
||||
return
|
||||
packet = PlayerActionPacket(
|
||||
action=3, location=self.g.breaking, face=1,
|
||||
sequence=self._next_sequence())
|
||||
self._send_action(packet)
|
||||
location = self.g.breaking
|
||||
if self.g.chunks.get_block_at(*location) == self.breaking_state:
|
||||
# Predict the normal client-side block removal. The server's later
|
||||
# block update is authoritative and will correct the cache if the
|
||||
# action was denied or the block changed differently.
|
||||
self.g.chunks.set_block_at(*location, blocks.AIR)
|
||||
self.g.breaking = None
|
||||
self.break_deadline = None
|
||||
self.breaking_state = None
|
||||
self.next_swing_at = 0.0
|
||||
|
||||
def cancel_break(self):
|
||||
if not self.g.get('breaking'):
|
||||
return
|
||||
packet = PlayerActionPacket(
|
||||
action=2, location=self.g.breaking, face=1,
|
||||
sequence=self._next_sequence())
|
||||
self._send_action(packet)
|
||||
self.g.breaking = None
|
||||
self.break_deadline = None
|
||||
self.breaking_state = None
|
||||
self.next_swing_at = 0.0
|
||||
|
||||
def select_item(self, item_ids):
|
||||
item_ids = set(item_ids)
|
||||
matches = [(slot, item) for slot, item in self.g.inv.items()
|
||||
if item.present and item.item_id in item_ids]
|
||||
if not matches:
|
||||
return False
|
||||
|
||||
# Prefer an already-hotbar stack; otherwise swap the requested stack
|
||||
# into an empty hotbar slot using the modern container SWAP input.
|
||||
slot, item = next(
|
||||
((slot, item) for slot, item in matches if 36 <= slot <= 44),
|
||||
matches[0])
|
||||
if slot == 45:
|
||||
self.g.holding = item.item_id
|
||||
self.g.holding_hand = 1
|
||||
self.g.connection.write_packet(ClientTickEnd(), force=True)
|
||||
return True
|
||||
self.g.holding_hand = 0
|
||||
if 36 <= slot <= 44:
|
||||
hotbar_slot = slot - 36
|
||||
elif 9 <= slot <= 35:
|
||||
empty_hotbar = next(
|
||||
(candidate - 36 for candidate in range(36, 45)
|
||||
if candidate not in self.g.inv or
|
||||
not self.g.inv[candidate].present), None)
|
||||
hotbar_slot = (empty_hotbar if empty_hotbar is not None else
|
||||
self.g.get('holding_slot', 0) or 0)
|
||||
self.g.connection.write_packet(ContainerClickSwapPacket(
|
||||
container_id=0,
|
||||
state_id=self.g.inventory_state_ids.get(0, 0),
|
||||
slot=slot, button=hotbar_slot), force=True)
|
||||
else:
|
||||
return False
|
||||
|
||||
if self.g.get('holding_slot') != hotbar_slot:
|
||||
self.g.connection.write_packet(SetCarriedItemPacket(
|
||||
slot=hotbar_slot), force=True)
|
||||
self.g.holding_slot = hotbar_slot
|
||||
self.g.holding = item.item_id
|
||||
self.g.connection.write_packet(ClientTickEnd(), force=True)
|
||||
return True
|
||||
|
||||
def place_block(self, location, face, hand=0, cursor_y=None,
|
||||
sneaking=False, cursor=None):
|
||||
location = tuple(int(value) for value in location)
|
||||
if cursor is None:
|
||||
if cursor_y is None:
|
||||
cursor_y = 0.99 if int(face) == 1 else 0.5
|
||||
cursor = (0.5, cursor_y, 0.5)
|
||||
packet = UseItemOnBlockPacket(
|
||||
hand=hand, location=location, face=int(face),
|
||||
cursor_x=float(cursor[0]), cursor_y=float(cursor[1]),
|
||||
cursor_z=float(cursor[2]), inside_block=False, world_border_hit=False,
|
||||
sequence=self._next_sequence())
|
||||
if sneaking:
|
||||
self.g.connection.write_packet(PlayerInputPacket(flags=0x20),
|
||||
force=True)
|
||||
self.g.connection.write_packet(ClientTickEnd(), force=True)
|
||||
try:
|
||||
self._send_action(packet)
|
||||
finally:
|
||||
self.g.connection.write_packet(PlayerInputPacket(flags=0),
|
||||
force=True)
|
||||
self.g.connection.write_packet(ClientTickEnd(), force=True)
|
||||
else:
|
||||
self._send_action(packet)
|
||||
|
||||
def count_window_slots(self):
|
||||
window = self.g.get('window')
|
||||
if not window:
|
||||
return 0
|
||||
return sum(
|
||||
item.present
|
||||
for slot, item in window.contents.items()
|
||||
if slot < window.container_slots)
|
||||
|
||||
def click_window(self, slot, button=0, mode=1, item=None):
|
||||
window = self.g.get('window')
|
||||
if not window:
|
||||
return False
|
||||
packet = ContainerClickQuickMovePacket(
|
||||
container_id=window.window_id,
|
||||
state_id=self.g.inventory_state_ids.get(
|
||||
window.window_id, window.state_id),
|
||||
slot=slot,
|
||||
)
|
||||
self.g.connection.write_packet(packet, force=True)
|
||||
self.g.connection.write_packet(ClientTickEnd(), force=True)
|
||||
return True
|
||||
|
||||
def close_window(self):
|
||||
window = self.g.get('window')
|
||||
if not window:
|
||||
return None
|
||||
self.g.connection.write_packet(ContainerClosePacket(
|
||||
container_id=window.window_id), force=True)
|
||||
self.g.window = None
|
||||
self.g.pending_chest_open = None
|
||||
|
||||
@@ -1,285 +1,96 @@
|
||||
import json
|
||||
import importlib
|
||||
"""Minecraft 26.3 block-state metadata and legacy automation selectors."""
|
||||
from itertools import product
|
||||
|
||||
from mosfet.info import mcdata
|
||||
|
||||
MCD_BLOCKS = {}
|
||||
for d in mcdata.mcd.blocks.values():
|
||||
MCD_BLOCKS[d['name']] = d
|
||||
|
||||
with open('minecraft_data/blocks.json') as f:
|
||||
JSON_BLOCKS = json.load(f)
|
||||
MCD_BLOCKS = mcdata.mcd.blocks
|
||||
JSON_BLOCKS = {'minecraft:' + name: data
|
||||
for name, data in MCD_BLOCKS.items()}
|
||||
|
||||
BLOCKS = {}
|
||||
for name, data in JSON_BLOCKS.items():
|
||||
for state in data['states']:
|
||||
BLOCKS[state['id']] = name.replace('minecraft:', '')
|
||||
|
||||
PROPS = {}
|
||||
for name, data in JSON_BLOCKS.items():
|
||||
for state in data['states']:
|
||||
PROPS[state['id']] = state.get('properties', {})
|
||||
COLLISION_BOXES = {}
|
||||
|
||||
for name, data in MCD_BLOCKS.items():
|
||||
first = data['minStateId']
|
||||
last = data['maxStateId']
|
||||
properties = data.get('states', [])
|
||||
property_values = [prop.get('values', []) for prop in properties]
|
||||
combinations = list(product(*property_values)) if property_values else [()]
|
||||
for offset, state_id in enumerate(range(first, last + 1)):
|
||||
BLOCKS[state_id] = name
|
||||
if offset < len(combinations):
|
||||
PROPS[state_id] = {
|
||||
prop['name']: value
|
||||
for prop, value in zip(properties, combinations[offset])
|
||||
}
|
||||
else:
|
||||
PROPS[state_id] = {}
|
||||
|
||||
shape_ref = mcdata.mcd.collision_shapes['blocks'].get(name, 1)
|
||||
refs = shape_ref if isinstance(shape_ref, list) else [shape_ref] * (last-first+1)
|
||||
for offset, state_id in enumerate(range(first, last + 1)):
|
||||
ref = refs[offset] if offset < len(refs) else refs[-1]
|
||||
COLLISION_BOXES[state_id] = mcdata.mcd.collision_shapes['shapes'].get(
|
||||
str(ref), [])
|
||||
|
||||
BREAK_DISTANCE = 6
|
||||
|
||||
AIR = 0
|
||||
STONE = 1
|
||||
SAND = 66
|
||||
SINGLE_SNOW = 3921
|
||||
SOUL_TORCH = 4008
|
||||
EMERALD_BLOCK = 5407
|
||||
|
||||
AIR = MCD_BLOCKS['air']['minStateId']
|
||||
STONE = MCD_BLOCKS['stone']['minStateId']
|
||||
SAND = MCD_BLOCKS['sand']['minStateId']
|
||||
SOUL_TORCH = MCD_BLOCKS['soul_torch']['minStateId']
|
||||
EMERALD_BLOCK = MCD_BLOCKS['emerald_block']['minStateId']
|
||||
SINGLE_SNOW = MCD_BLOCKS.get('snow', MCD_BLOCKS.get('snow_layer', {})).get(
|
||||
'minStateId', AIR)
|
||||
TEST_BLOCK = (616, 78, 496)
|
||||
|
||||
|
||||
AVOID = [
|
||||
'lava',
|
||||
'water',
|
||||
'fire',
|
||||
'magma_block',
|
||||
'oak_fence',
|
||||
'oak_fence_gate',
|
||||
'nether_brick_fence',
|
||||
'spruce_fence_gate',
|
||||
'birch_fence_gate',
|
||||
'jungle_fence_gate',
|
||||
'acacia_fence_gate',
|
||||
'dark_oak_fence_gate',
|
||||
'spruce_fence',
|
||||
'birch_fence',
|
||||
'jungle_fence',
|
||||
'acacia_fence',
|
||||
'dark_oak_fence',
|
||||
'sweet_berry_bush',
|
||||
'nether_portal',
|
||||
'end_portal',
|
||||
'cobblestone_wall',
|
||||
'mossy_cobblestone_wall',
|
||||
'brick_wall',
|
||||
'prismarine_wall',
|
||||
'red_sandstone_wall',
|
||||
'mossy_stone_brick_wall',
|
||||
'granite_wall',
|
||||
'stone_brick_wall',
|
||||
'nether_brick_wall',
|
||||
'andesite_wall',
|
||||
'red_nether_brick_wall',
|
||||
'sandstone_wall',
|
||||
'end_stone_brick_wall',
|
||||
'diorite_wall',
|
||||
'oak_sapling', # saplings can grow up and hurt
|
||||
'spruce_sapling',
|
||||
'birch_sapling',
|
||||
'jungle_sapling',
|
||||
'acacia_sapling',
|
||||
'dark_oak_sapling',
|
||||
]
|
||||
|
||||
NON_SOLID = [
|
||||
'air',
|
||||
'powered_rail',
|
||||
'detector_rail',
|
||||
'grass',
|
||||
'fern',
|
||||
'dead_bush',
|
||||
'seagrass',
|
||||
'tall_seagrass',
|
||||
'dandelion',
|
||||
'poppy',
|
||||
'blue_orchid',
|
||||
'allium',
|
||||
'azure_bluet',
|
||||
'red_tulip',
|
||||
'orange_tulip',
|
||||
'white_tulip',
|
||||
'pink_tulip',
|
||||
'oxeye_daisy',
|
||||
'cornflower',
|
||||
'wither_rose',
|
||||
'lily_of_the_valley',
|
||||
'brown_mushroom',
|
||||
'red_mushroom',
|
||||
'torch',
|
||||
'wall_torch',
|
||||
'redstone_wire',
|
||||
'wheat',
|
||||
'oak_sign',
|
||||
'spruce_sign',
|
||||
'birch_sign',
|
||||
'acacia_sign',
|
||||
'jungle_sign',
|
||||
'dark_oak_sign',
|
||||
'rail',
|
||||
'oak_wall_sign',
|
||||
'spruce_wall_sign',
|
||||
'birch_wall_sign',
|
||||
'acacia_wall_sign',
|
||||
'jungle_wall_sign',
|
||||
'dark_oak_wall_sign',
|
||||
'lever',
|
||||
'stone_pressure_plate',
|
||||
'oak_pressure_plate',
|
||||
'spruce_pressure_plate',
|
||||
'birch_pressure_plate',
|
||||
'jungle_pressure_plate',
|
||||
'acacia_pressure_plate',
|
||||
'dark_oak_pressure_plate',
|
||||
'redstone_torch',
|
||||
'redstone_wall_torch',
|
||||
'stone_button',
|
||||
'sugar_cane',
|
||||
'repeater',
|
||||
'attached_pumpkin_stem',
|
||||
'attached_melon_stem',
|
||||
'pumpkin_stem',
|
||||
'melon_stem',
|
||||
'nether_wart',
|
||||
'tripwire_hook',
|
||||
'tripwire',
|
||||
'carrots',
|
||||
'potatoes',
|
||||
'oak_button',
|
||||
'spruce_button',
|
||||
'birch_button',
|
||||
'jungle_button',
|
||||
'acacia_button',
|
||||
'dark_oak_button',
|
||||
'light_weighted_pressure_plate',
|
||||
'heavy_weighted_pressure_plate',
|
||||
'comparator',
|
||||
'activator_rail',
|
||||
'white_carpet',
|
||||
'orange_carpet',
|
||||
'magenta_carpet',
|
||||
'light_blue_carpet',
|
||||
'yellow_carpet',
|
||||
'lime_carpet',
|
||||
'pink_carpet',
|
||||
'gray_carpet',
|
||||
'light_gray_carpet',
|
||||
'cyan_carpet',
|
||||
'purple_carpet',
|
||||
'blue_carpet',
|
||||
'brown_carpet',
|
||||
'green_carpet',
|
||||
'red_carpet',
|
||||
'black_carpet',
|
||||
'sunflower',
|
||||
'lilac',
|
||||
'rose_bush',
|
||||
'peony',
|
||||
'tall_grass',
|
||||
'large_fern',
|
||||
'white_banner',
|
||||
'orange_banner',
|
||||
'magenta_banner',
|
||||
'light_blue_banner',
|
||||
'yellow_banner',
|
||||
'lime_banner',
|
||||
'pink_banner',
|
||||
'gray_banner',
|
||||
'light_gray_banner',
|
||||
'cyan_banner',
|
||||
'purple_banner',
|
||||
'blue_banner',
|
||||
'brown_banner',
|
||||
'green_banner',
|
||||
'red_banner',
|
||||
'black_banner',
|
||||
'white_wall_banner',
|
||||
'orange_wall_banner',
|
||||
'magenta_wall_banner',
|
||||
'light_blue_wall_banner',
|
||||
'yellow_wall_banner',
|
||||
'lime_wall_banner',
|
||||
'pink_wall_banner',
|
||||
'gray_wall_banner',
|
||||
'light_gray_wall_banner',
|
||||
'cyan_wall_banner',
|
||||
'purple_wall_banner',
|
||||
'blue_wall_banner',
|
||||
'brown_wall_banner',
|
||||
'green_wall_banner',
|
||||
'red_wall_banner',
|
||||
'black_wall_banner',
|
||||
'beetroots',
|
||||
'bamboo_sapling',
|
||||
'void_air',
|
||||
'cave_air',
|
||||
'lantern',
|
||||
'soul_torch',
|
||||
]
|
||||
|
||||
LOGS = [
|
||||
'oak_log',
|
||||
'spruce_log',
|
||||
'birch_log',
|
||||
'jungle_log',
|
||||
'acacia_log',
|
||||
'dark_oak_log',
|
||||
]
|
||||
|
||||
LEAVES = [
|
||||
'oak_leaves',
|
||||
'spruce_leaves',
|
||||
'birch_leaves',
|
||||
'jungle_leaves',
|
||||
'acacia_leaves',
|
||||
'dark_oak_leaves',
|
||||
]
|
||||
|
||||
SAPLINGS = [
|
||||
'oak_sapling',
|
||||
'spruce_sapling',
|
||||
'birch_sapling',
|
||||
'jungle_sapling',
|
||||
'acacia_sapling',
|
||||
'dark_oak_sapling',
|
||||
]
|
||||
|
||||
BEDS = [
|
||||
'white_bed',
|
||||
'orange_bed',
|
||||
'magenta_bed',
|
||||
'light_blue_bed',
|
||||
'yellow_bed',
|
||||
'lime_bed',
|
||||
'pink_bed',
|
||||
'gray_bed',
|
||||
'light_gray_bed',
|
||||
'cyan_bed',
|
||||
'purple_bed',
|
||||
'blue_bed',
|
||||
'brown_bed',
|
||||
'green_bed',
|
||||
'red_bed',
|
||||
'black_bed',
|
||||
]
|
||||
|
||||
INDEXED = [
|
||||
'chest',
|
||||
'trapped_chest',
|
||||
'emerald_block',
|
||||
'barrel',
|
||||
] + BEDS
|
||||
|
||||
def get_set(ids):
|
||||
def get_set(names):
|
||||
"""Return every state ID belonging to the named blocks; ignore removed names."""
|
||||
result = set()
|
||||
for block_name in ids:
|
||||
for state in JSON_BLOCKS['minecraft:' + block_name]['states']:
|
||||
result.add(state['id'])
|
||||
for name in names:
|
||||
name = name.removeprefix('minecraft:')
|
||||
data = MCD_BLOCKS.get(name)
|
||||
if data is not None:
|
||||
result.update(range(data['minStateId'], data['maxStateId'] + 1))
|
||||
return result
|
||||
|
||||
NON_SOLID_IDS = get_set(NON_SOLID)
|
||||
NON_SOLID_IDS.add(SINGLE_SNOW)
|
||||
|
||||
# Collision geometry is safer for navigation than the old hard-coded 1.16 list.
|
||||
NON_SOLID_IDS = {
|
||||
state_id for state_id, boxes in COLLISION_BOXES.items() if not boxes
|
||||
}
|
||||
AVOID = {
|
||||
'lava', 'water', 'fire', 'magma_block', 'sweet_berry_bush',
|
||||
'nether_portal', 'end_portal', 'cactus', 'powder_snow',
|
||||
}
|
||||
AVOID_IDS = get_set(AVOID)
|
||||
AVOID_IDS.update(
|
||||
state_id for state_id, name in BLOCKS.items()
|
||||
if name.endswith(('_fence', '_fence_gate', '_wall'))
|
||||
)
|
||||
WATER_IDS = get_set(['water'])
|
||||
|
||||
LOGS = sorted(name for name in MCD_BLOCKS
|
||||
if name.endswith(('_log', '_wood', '_stem', '_hyphae')))
|
||||
LEAVES = sorted(name for name in MCD_BLOCKS if name.endswith('_leaves'))
|
||||
SAPLINGS = sorted(name for name in MCD_BLOCKS
|
||||
if name.endswith('_sapling') or name.endswith('_propagule'))
|
||||
BEDS = sorted(name for name in MCD_BLOCKS if name.endswith('_bed'))
|
||||
INDEXED = ['chest', 'trapped_chest', 'emerald_block', 'barrel'] + BEDS + [
|
||||
'wheat', 'potatoes', 'carrots', 'beetroots', 'nether_wart',
|
||||
] + LOGS
|
||||
|
||||
LOG_IDS = get_set(LOGS)
|
||||
LEAF_IDS = get_set(LEAVES)
|
||||
CHEST_IDS = get_set(['chest'])
|
||||
BARREL_IDS = get_set(['barrel'])
|
||||
TRAPPED_CHEST_IDS = get_set(['trapped_chest'])
|
||||
DOOR_NAMES = sorted(name for name in MCD_BLOCKS
|
||||
if name.endswith('_door'))
|
||||
DOOR_IDS = get_set(DOOR_NAMES)
|
||||
OPENABLE_DOOR_IDS = get_set(
|
||||
name for name in DOOR_NAMES if name != 'iron_door')
|
||||
NETHERWART_IDS = get_set(['nether_wart'])
|
||||
WHEAT_IDS = get_set(['wheat'])
|
||||
POTATO_IDS = get_set(['potatoes'])
|
||||
@@ -287,21 +98,28 @@ CARROT_IDS = get_set(['carrots'])
|
||||
BEETROOT_IDS = get_set(['beetroots'])
|
||||
SAPLING_IDS = get_set(SAPLINGS)
|
||||
BED_IDS = get_set(BEDS)
|
||||
|
||||
INDEXED_IDS = set()
|
||||
for block_name in INDEXED:
|
||||
for state in JSON_BLOCKS['minecraft:' + block_name]['states']:
|
||||
INDEXED_IDS.add(state['id'])
|
||||
INDEXED_IDS = get_set(INDEXED)
|
||||
|
||||
|
||||
MATURE_WHEAT_ID = max(WHEAT_IDS)
|
||||
MATURE_POTATO_ID = max(POTATO_IDS)
|
||||
MATURE_CARROT_ID = max(CARROT_IDS)
|
||||
MATURE_BEETROOT_ID = max(BEETROOT_IDS)
|
||||
def _mature_state(name, property_name, mature_value):
|
||||
data = MCD_BLOCKS.get(name)
|
||||
if data is None:
|
||||
return None
|
||||
for state_id in range(data['minStateId'], data['maxStateId'] + 1):
|
||||
if PROPS[state_id].get(property_name) == str(mature_value):
|
||||
return state_id
|
||||
return data['maxStateId']
|
||||
|
||||
|
||||
MATURE_WHEAT_ID = _mature_state('wheat', 'age', 7)
|
||||
MATURE_POTATO_ID = _mature_state('potatoes', 'age', 7)
|
||||
MATURE_CARROT_ID = _mature_state('carrots', 'age', 7)
|
||||
MATURE_BEETROOT_ID = _mature_state('beetroots', 'age', 3)
|
||||
|
||||
|
||||
def get(block_state_id):
|
||||
return MCD_BLOCKS[BLOCKS[block_state_id]]
|
||||
|
||||
def get(bid):
|
||||
name = BLOCKS[bid]
|
||||
return MCD_BLOCKS[name]
|
||||
|
||||
def find(name):
|
||||
return MCD_BLOCKS[name]
|
||||
return MCD_BLOCKS[name.removeprefix('minecraft:')]
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2022 grepsedawk <grepsedawk@users.noreply.github.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,7 @@
|
||||
Minecraft 26.3 data files
|
||||
|
||||
Source: RosegoldMC/minecraft-data.cr, data/26.3
|
||||
https://github.com/RosegoldMC/minecraft-data.cr/tree/main/data/26.3
|
||||
|
||||
The JSON files in this directory are redistributed under the MIT License;
|
||||
see LICENSE. They are generated data, not Mojang source code.
|
||||
@@ -0,0 +1,45 @@
|
||||
[
|
||||
{"id":0,"name":"aqua_affinity"},
|
||||
{"id":1,"name":"bane_of_arthropods"},
|
||||
{"id":2,"name":"binding_curse"},
|
||||
{"id":3,"name":"blast_protection"},
|
||||
{"id":4,"name":"breach"},
|
||||
{"id":5,"name":"channeling"},
|
||||
{"id":6,"name":"density"},
|
||||
{"id":7,"name":"depth_strider"},
|
||||
{"id":8,"name":"efficiency"},
|
||||
{"id":9,"name":"feather_falling"},
|
||||
{"id":10,"name":"fire_aspect"},
|
||||
{"id":11,"name":"fire_protection"},
|
||||
{"id":12,"name":"flame"},
|
||||
{"id":13,"name":"fortune"},
|
||||
{"id":14,"name":"frost_walker"},
|
||||
{"id":15,"name":"impaling"},
|
||||
{"id":16,"name":"infinity"},
|
||||
{"id":17,"name":"knockback"},
|
||||
{"id":18,"name":"looting"},
|
||||
{"id":19,"name":"loyalty"},
|
||||
{"id":20,"name":"luck_of_the_sea"},
|
||||
{"id":21,"name":"lunge"},
|
||||
{"id":22,"name":"lure"},
|
||||
{"id":23,"name":"mending"},
|
||||
{"id":24,"name":"multishot"},
|
||||
{"id":25,"name":"piercing"},
|
||||
{"id":26,"name":"power"},
|
||||
{"id":27,"name":"projectile_protection"},
|
||||
{"id":28,"name":"protection"},
|
||||
{"id":29,"name":"punch"},
|
||||
{"id":30,"name":"quick_charge"},
|
||||
{"id":31,"name":"respiration"},
|
||||
{"id":32,"name":"riptide"},
|
||||
{"id":33,"name":"sharpness"},
|
||||
{"id":34,"name":"silk_touch"},
|
||||
{"id":35,"name":"smite"},
|
||||
{"id":36,"name":"soul_speed"},
|
||||
{"id":37,"name":"sweeping_edge"},
|
||||
{"id":38,"name":"swift_sneak"},
|
||||
{"id":39,"name":"thorns"},
|
||||
{"id":40,"name":"unbreaking"},
|
||||
{"id":41,"name":"vanishing_curse"},
|
||||
{"id":42,"name":"wind_burst"}
|
||||
]
|
||||
@@ -0,0 +1,163 @@
|
||||
[
|
||||
{"id":0,"name":"acacia_boat","width":1.375,"height":0.5625},
|
||||
{"id":1,"name":"acacia_chest_boat","width":1.375,"height":0.5625},
|
||||
{"id":2,"name":"allay","width":0.35,"height":0.6},
|
||||
{"id":3,"name":"area_effect_cloud","width":6,"height":0.5},
|
||||
{"id":4,"name":"armadillo","width":0.7,"height":0.65},
|
||||
{"id":5,"name":"armor_stand","width":0.5,"height":1.975},
|
||||
{"id":6,"name":"arrow","width":0.5,"height":0.5},
|
||||
{"id":7,"name":"axolotl","width":0.75,"height":0.42},
|
||||
{"id":8,"name":"bamboo_chest_raft","width":1.375,"height":0.5625},
|
||||
{"id":9,"name":"bamboo_raft","width":1.375,"height":0.5625},
|
||||
{"id":10,"name":"bat","width":0.5,"height":0.9},
|
||||
{"id":11,"name":"bee","width":0.7,"height":0.6},
|
||||
{"id":12,"name":"birch_boat","width":1.375,"height":0.5625},
|
||||
{"id":13,"name":"birch_chest_boat","width":1.375,"height":0.5625},
|
||||
{"id":14,"name":"blaze","width":0.6,"height":1.8},
|
||||
{"id":15,"name":"block_display","width":0,"height":0},
|
||||
{"id":16,"name":"bogged","width":0.6,"height":1.99},
|
||||
{"id":17,"name":"breeze","width":0.6,"height":1.77},
|
||||
{"id":18,"name":"breeze_wind_charge","width":0.3125,"height":0.3125},
|
||||
{"id":19,"name":"camel","width":1.7,"height":2.375},
|
||||
{"id":20,"name":"camel_husk","width":1.7,"height":2.375},
|
||||
{"id":21,"name":"cat","width":0.6,"height":0.7},
|
||||
{"id":22,"name":"cave_spider","width":0.7,"height":0.5},
|
||||
{"id":23,"name":"cherry_boat","width":1.375,"height":0.5625},
|
||||
{"id":24,"name":"cherry_chest_boat","width":1.375,"height":0.5625},
|
||||
{"id":25,"name":"chest_minecart","width":0.98,"height":0.7},
|
||||
{"id":26,"name":"chicken","width":0.4,"height":0.7},
|
||||
{"id":27,"name":"cod","width":0.5,"height":0.3},
|
||||
{"id":28,"name":"copper_golem","width":0.49,"height":0.98},
|
||||
{"id":29,"name":"command_block_minecart","width":0.98,"height":0.7},
|
||||
{"id":30,"name":"cow","width":0.9,"height":1.4},
|
||||
{"id":31,"name":"creaking","width":0.9,"height":2.7},
|
||||
{"id":32,"name":"creeper","width":0.6,"height":1.7},
|
||||
{"id":33,"name":"cushion","width":1.0,"height":0.25,"type":"other","category":"Other"},
|
||||
{"id":34,"name":"dark_oak_boat","width":1.375,"height":0.5625},
|
||||
{"id":35,"name":"dark_oak_chest_boat","width":1.375,"height":0.5625},
|
||||
{"id":36,"name":"dolphin","width":0.9,"height":0.6},
|
||||
{"id":37,"name":"donkey","width":1.3964844,"height":1.5},
|
||||
{"id":38,"name":"dragon_fireball","width":1,"height":1},
|
||||
{"id":39,"name":"drowned","width":0.6,"height":1.95},
|
||||
{"id":40,"name":"egg","width":0.25,"height":0.25},
|
||||
{"id":41,"name":"elder_guardian","width":1.9975,"height":1.9975},
|
||||
{"id":42,"name":"enderman","width":0.6,"height":2.9},
|
||||
{"id":43,"name":"endermite","width":0.4,"height":0.3},
|
||||
{"id":44,"name":"ender_dragon","width":16,"height":8},
|
||||
{"id":45,"name":"ender_pearl","width":0.25,"height":0.25},
|
||||
{"id":46,"name":"end_crystal","width":2,"height":2},
|
||||
{"id":47,"name":"evoker","width":0.6,"height":1.95},
|
||||
{"id":48,"name":"evoker_fangs","width":0.5,"height":0.8},
|
||||
{"id":49,"name":"experience_bottle","width":0.25,"height":0.25},
|
||||
{"id":50,"name":"experience_orb","width":0.5,"height":0.5},
|
||||
{"id":51,"name":"eye_of_ender","width":0.25,"height":0.25},
|
||||
{"id":52,"name":"falling_block","width":0.98,"height":0.98},
|
||||
{"id":53,"name":"fireball","width":1,"height":1},
|
||||
{"id":54,"name":"firework_rocket","width":0.25,"height":0.25},
|
||||
{"id":55,"name":"fox","width":0.6,"height":0.7},
|
||||
{"id":56,"name":"frog","width":0.5,"height":0.5},
|
||||
{"id":57,"name":"furnace_minecart","width":0.98,"height":0.7},
|
||||
{"id":58,"name":"ghast","width":4,"height":4},
|
||||
{"id":59,"name":"happy_ghast","width":4,"height":4},
|
||||
{"id":60,"name":"giant","width":3.6,"height":12},
|
||||
{"id":61,"name":"glow_item_frame","width":0.5,"height":0.5},
|
||||
{"id":62,"name":"glow_squid","width":0.8,"height":0.8},
|
||||
{"id":63,"name":"goat","width":0.9,"height":1.3},
|
||||
{"id":64,"name":"guardian","width":0.85,"height":0.85},
|
||||
{"id":65,"name":"hoglin","width":1.3964844,"height":1.4},
|
||||
{"id":66,"name":"hopper_minecart","width":0.98,"height":0.7},
|
||||
{"id":67,"name":"horse","width":1.3964844,"height":1.6},
|
||||
{"id":68,"name":"husk","width":0.6,"height":1.95},
|
||||
{"id":69,"name":"illusioner","width":0.6,"height":1.95},
|
||||
{"id":70,"name":"interaction","width":0,"height":0},
|
||||
{"id":71,"name":"iron_golem","width":1.4,"height":2.7},
|
||||
{"id":72,"name":"item","width":0.25,"height":0.25},
|
||||
{"id":73,"name":"item_display","width":0,"height":0},
|
||||
{"id":74,"name":"item_frame","width":0.5,"height":0.5},
|
||||
{"id":75,"name":"jungle_boat","width":1.375,"height":0.5625},
|
||||
{"id":76,"name":"jungle_chest_boat","width":1.375,"height":0.5625},
|
||||
{"id":77,"name":"leash_knot","width":0.375,"height":0.5},
|
||||
{"id":78,"name":"lightning_bolt","width":0,"height":0},
|
||||
{"id":79,"name":"llama","width":0.9,"height":1.87},
|
||||
{"id":80,"name":"llama_spit","width":0.25,"height":0.25},
|
||||
{"id":81,"name":"magma_cube","width":0.52,"height":0.52},
|
||||
{"id":82,"name":"mangrove_boat","width":1.375,"height":0.5625},
|
||||
{"id":83,"name":"mangrove_chest_boat","width":1.375,"height":0.5625},
|
||||
{"id":84,"name":"mannequin","width":0.6,"height":1.8},
|
||||
{"id":85,"name":"marker","width":0,"height":0},
|
||||
{"id":86,"name":"minecart","width":0.98,"height":0.7},
|
||||
{"id":87,"name":"mooshroom","width":0.9,"height":1.4},
|
||||
{"id":88,"name":"mule","width":1.3964844,"height":1.6},
|
||||
{"id":89,"name":"nautilus","width":0.875,"height":0.95},
|
||||
{"id":90,"name":"oak_boat","width":1.375,"height":0.5625},
|
||||
{"id":91,"name":"oak_chest_boat","width":1.375,"height":0.5625},
|
||||
{"id":92,"name":"ocelot","width":0.6,"height":0.7},
|
||||
{"id":93,"name":"ominous_item_spawner","width":0.25,"height":0.25},
|
||||
{"id":94,"name":"painting","width":0.5,"height":0.5},
|
||||
{"id":95,"name":"pale_oak_boat","width":1.375,"height":0.5625},
|
||||
{"id":96,"name":"pale_oak_chest_boat","width":1.375,"height":0.5625},
|
||||
{"id":97,"name":"panda","width":1.3,"height":1.25},
|
||||
{"id":98,"name":"parched","width":0.6,"height":1.99},
|
||||
{"id":99,"name":"parrot","width":0.5,"height":0.9},
|
||||
{"id":100,"name":"phantom","width":0.9,"height":0.5},
|
||||
{"id":101,"name":"pig","width":0.9,"height":0.9},
|
||||
{"id":102,"name":"piglin","width":0.6,"height":1.95},
|
||||
{"id":103,"name":"piglin_brute","width":0.6,"height":1.95},
|
||||
{"id":104,"name":"pillager","width":0.6,"height":1.95},
|
||||
{"id":105,"name":"polar_bear","width":1.4,"height":1.4},
|
||||
{"id":106,"name":"poplar_boat","width":1.375,"height":0.5625,"type":"other","category":"Vehicles"},
|
||||
{"id":107,"name":"poplar_chest_boat","width":1.375,"height":0.5625,"type":"other","category":"Vehicles"},
|
||||
{"id":108,"name":"splash_potion","width":0.25,"height":0.25},
|
||||
{"id":109,"name":"lingering_potion","width":0.25,"height":0.25},
|
||||
{"id":110,"name":"pufferfish","width":0.7,"height":0.7},
|
||||
{"id":111,"name":"rabbit","width":0.4,"height":0.5},
|
||||
{"id":112,"name":"ravager","width":1.95,"height":2.2},
|
||||
{"id":113,"name":"salmon","width":0.7,"height":0.4},
|
||||
{"id":114,"name":"sheep","width":0.9,"height":1.3},
|
||||
{"id":115,"name":"shulker","width":1,"height":1},
|
||||
{"id":116,"name":"shulker_bullet","width":0.3125,"height":0.3125},
|
||||
{"id":117,"name":"silverfish","width":0.4,"height":0.3},
|
||||
{"id":118,"name":"skeleton","width":0.6,"height":1.99},
|
||||
{"id":119,"name":"skeleton_horse","width":1.3964844,"height":1.6},
|
||||
{"id":120,"name":"slime","width":0.52,"height":0.52},
|
||||
{"id":121,"name":"small_fireball","width":0.3125,"height":0.3125},
|
||||
{"id":122,"name":"sniffer","width":1.9,"height":1.75},
|
||||
{"id":123,"name":"snowball","width":0.25,"height":0.25},
|
||||
{"id":124,"name":"snow_golem","width":0.7,"height":1.9},
|
||||
{"id":125,"name":"spawner_minecart","width":0.98,"height":0.7},
|
||||
{"id":126,"name":"spectral_arrow","width":0.5,"height":0.5},
|
||||
{"id":127,"name":"spider","width":1.4,"height":0.9},
|
||||
{"id":128,"name":"spruce_boat","width":1.375,"height":0.5625},
|
||||
{"id":129,"name":"spruce_chest_boat","width":1.375,"height":0.5625},
|
||||
{"id":130,"name":"squid","width":0.8,"height":0.8},
|
||||
{"id":131,"name":"stray","width":0.6,"height":1.99},
|
||||
{"id":132,"name":"strider","width":0.9,"height":1.7},
|
||||
{"id":133,"name":"sulfur_cube","width":0.49,"height":0.49},
|
||||
{"id":134,"name":"tadpole","width":0.4,"height":0.3},
|
||||
{"id":135,"name":"text_display","width":0,"height":0},
|
||||
{"id":136,"name":"tnt","width":0.98,"height":0.98},
|
||||
{"id":137,"name":"tnt_minecart","width":0.98,"height":0.7},
|
||||
{"id":138,"name":"trader_llama","width":0.9,"height":1.87},
|
||||
{"id":139,"name":"trident","width":0.5,"height":0.5},
|
||||
{"id":140,"name":"tropical_fish","width":0.5,"height":0.4},
|
||||
{"id":141,"name":"turtle","width":1.2,"height":0.4},
|
||||
{"id":142,"name":"vex","width":0.4,"height":0.8},
|
||||
{"id":143,"name":"villager","width":0.6,"height":1.95},
|
||||
{"id":144,"name":"vindicator","width":0.6,"height":1.95},
|
||||
{"id":145,"name":"wandering_trader","width":0.6,"height":1.95},
|
||||
{"id":146,"name":"warden","width":0.9,"height":2.9},
|
||||
{"id":147,"name":"wind_charge","width":0.3125,"height":0.3125},
|
||||
{"id":148,"name":"witch","width":0.6,"height":1.95},
|
||||
{"id":149,"name":"wither","width":0.9,"height":3.5},
|
||||
{"id":150,"name":"wither_skeleton","width":0.7,"height":2.4},
|
||||
{"id":151,"name":"wither_skull","width":0.3125,"height":0.3125},
|
||||
{"id":152,"name":"wolf","width":0.6,"height":0.85},
|
||||
{"id":153,"name":"zoglin","width":1.3964844,"height":1.4},
|
||||
{"id":154,"name":"zombie","width":0.6,"height":1.95},
|
||||
{"id":155,"name":"zombie_horse","width":1.3964844,"height":1.6},
|
||||
{"id":156,"name":"zombie_nautilus","width":0.875,"height":0.95},
|
||||
{"id":157,"name":"zombie_villager","width":0.6,"height":1.95},
|
||||
{"id":158,"name":"zombified_piglin","width":0.6,"height":1.95},
|
||||
{"id":159,"name":"player","width":0.6,"height":1.8},
|
||||
{"id":160,"name":"fishing_bobber","width":0.25,"height":0.25}
|
||||
]
|
||||
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"default":{},
|
||||
"sword_instantly_mines":{"1025":2.0,"1030":1.0,"1035":4.0,"1040":12.0,"1045":6.0,"1050":8.0,"1055":9.0},
|
||||
"sword_efficient":{"1025":2.0,"1030":1.0,"1035":4.0,"1040":12.0,"1045":6.0,"1050":8.0,"1055":9.0},
|
||||
"incorrect_for_wooden_tool":{"1026":2.0,"1027":2.0,"1028":2.0,"1029":2.0},
|
||||
"mineable/shovel":{"1026":2.0,"1031":1.0,"1036":4.0,"1041":12.0,"1046":6.0,"1051":8.0,"1056":9.0},
|
||||
"mineable/pickaxe":{"1027":2.0,"1032":1.0,"1037":4.0,"1042":12.0,"1047":6.0,"1052":8.0,"1057":9.0},
|
||||
"mineable/axe":{"1028":2.0,"1033":1.0,"1038":4.0,"1043":12.0,"1048":6.0,"1053":8.0,"1058":9.0},
|
||||
"mineable/hoe":{"1029":2.0,"1034":1.0,"1039":4.0,"1044":12.0,"1049":6.0,"1054":8.0,"1059":9.0},
|
||||
"incorrect_for_copper_tool":{"1031":1.0,"1032":1.0,"1033":1.0,"1034":1.0},
|
||||
"incorrect_for_stone_tool":{"1036":4.0,"1037":4.0,"1038":4.0,"1039":4.0},
|
||||
"incorrect_for_gold_tool":{"1041":12.0,"1042":12.0,"1043":12.0,"1044":12.0},
|
||||
"incorrect_for_iron_tool":{"1046":6.0,"1047":6.0,"1048":6.0,"1049":6.0},
|
||||
"incorrect_for_diamond_tool":{"1051":8.0,"1052":8.0,"1053":8.0,"1054":8.0},
|
||||
"incorrect_for_netherite_tool":{"1056":9.0,"1057":9.0,"1058":9.0,"1059":9.0},
|
||||
"shears_extreme_breaking_speed":{"1255":1.0},
|
||||
"shears_major_breaking_speed":{"1255":1.0},
|
||||
"shears_minor_breaking_speed":{"1255":1.0},
|
||||
"leaves":{"1255":15.0,"1025":1.5,"1030":1.5,"1035":1.5,"1040":1.5,"1045":1.5,"1050":1.5,"1055":1.5},
|
||||
"coweb":{"1255":15.0,"1025":15.0,"1030":15.0,"1035":15.0,"1040":15.0,"1045":15.0,"1050":15.0,"1055":15.0},
|
||||
"vine_or_glow_lichen":{"1255":2.0},
|
||||
"wool":{"1255":5.0},
|
||||
"plant":{"1025":1.5,"1030":1.5,"1035":1.5,"1040":1.5,"1045":1.5,"1050":1.5,"1055":1.5},
|
||||
"gourd":{"1025":1.5,"1030":1.5,"1035":1.5,"1040":1.5,"1045":1.5,"1050":1.5,"1055":1.5},
|
||||
"plant;mineable/axe":{"1025":1.5,"1030":1.5,"1035":1.5,"1040":1.5,"1045":1.5,"1050":1.5,"1055":1.5,"1028":2.0,"1033":1.0,"1038":4.0,"1043":12.0,"1048":6.0,"1053":8.0,"1058":9.0},
|
||||
"gourd;mineable/axe":{"1025":1.5,"1030":1.5,"1035":1.5,"1040":1.5,"1045":1.5,"1050":1.5,"1055":1.5,"1028":2.0,"1033":1.0,"1038":4.0,"1043":12.0,"1048":6.0,"1053":8.0,"1058":9.0},
|
||||
"leaves;mineable/hoe":{"1255":15.0,"1025":1.5,"1030":1.5,"1035":1.5,"1040":1.5,"1045":1.5,"1050":1.5,"1055":1.5,"1029":2.0,"1034":1.0,"1039":4.0,"1044":12.0,"1049":6.0,"1054":8.0,"1059":9.0},
|
||||
"leaves;mineable/axe;mineable/hoe":{
|
||||
"1255":15.0,
|
||||
"1025":1.5,
|
||||
"1030":1.5,
|
||||
"1035":1.5,
|
||||
"1040":1.5,
|
||||
"1045":1.5,
|
||||
"1050":1.5,
|
||||
"1055":1.5,
|
||||
"1028":2.0,
|
||||
"1033":1.0,
|
||||
"1038":4.0,
|
||||
"1043":12.0,
|
||||
"1048":6.0,
|
||||
"1053":8.0,
|
||||
"1058":9.0,
|
||||
"1029":2.0,
|
||||
"1034":1.0,
|
||||
"1039":4.0,
|
||||
"1044":12.0,
|
||||
"1049":6.0,
|
||||
"1054":8.0,
|
||||
"1059":9.0
|
||||
},
|
||||
"vine_or_glow_lichen;plant;mineable/axe":{"1255":2.0,"1025":1.5,"1030":1.5,"1035":1.5,"1040":1.5,"1045":1.5,"1050":1.5,"1055":1.5,"1028":2.0,"1033":1.0,"1038":4.0,"1043":12.0,"1048":6.0,"1053":8.0,"1058":9.0}
|
||||
}
|
||||
@@ -1,78 +1,45 @@
|
||||
import json
|
||||
"""Minecraft 26.3 item registry data and automation selectors."""
|
||||
from mosfet.info import mcdata
|
||||
|
||||
with open('minecraft_data/registries.json') as f:
|
||||
ITEMS = json.load(f)['minecraft:item']['entries']
|
||||
ITEMS = {
|
||||
'minecraft:' + name: dict(item, protocol_id=item['id'])
|
||||
for name, item in mcdata.mcd.items.items()
|
||||
}
|
||||
|
||||
BEDS = [
|
||||
'white_bed',
|
||||
'orange_bed',
|
||||
'magenta_bed',
|
||||
'light_blue_bed',
|
||||
'yellow_bed',
|
||||
'lime_bed',
|
||||
'pink_bed',
|
||||
'gray_bed',
|
||||
'light_gray_bed',
|
||||
'cyan_bed',
|
||||
'purple_bed',
|
||||
'blue_bed',
|
||||
'brown_bed',
|
||||
'green_bed',
|
||||
'red_bed',
|
||||
'black_bed',
|
||||
'white_bed', 'orange_bed', 'magenta_bed', 'light_blue_bed',
|
||||
'yellow_bed', 'lime_bed', 'pink_bed', 'gray_bed', 'light_gray_bed',
|
||||
'cyan_bed', 'purple_bed', 'blue_bed', 'brown_bed', 'green_bed',
|
||||
'red_bed', 'black_bed',
|
||||
]
|
||||
|
||||
SHOVELS = [
|
||||
'wooden_shovel',
|
||||
'stone_shovel',
|
||||
'golden_shovel',
|
||||
'iron_shovel',
|
||||
'diamond_shovel',
|
||||
'netherite_shovel',
|
||||
'wooden_shovel', 'stone_shovel', 'golden_shovel', 'iron_shovel',
|
||||
'diamond_shovel', 'netherite_shovel',
|
||||
]
|
||||
|
||||
AXES = [
|
||||
'wooden_axe',
|
||||
'stone_axe',
|
||||
'golden_axe',
|
||||
'iron_axe',
|
||||
'diamond_axe',
|
||||
'netherite_axe',
|
||||
'wooden_axe', 'stone_axe', 'golden_axe', 'iron_axe',
|
||||
'diamond_axe', 'netherite_axe',
|
||||
]
|
||||
|
||||
SAPLINGS = [
|
||||
'oak_sapling',
|
||||
'spruce_sapling',
|
||||
'birch_sapling',
|
||||
'jungle_sapling',
|
||||
'acacia_sapling',
|
||||
'dark_oak_sapling',
|
||||
name for name in mcdata.mcd.blocks
|
||||
if name.endswith('_sapling') or name.endswith('_propagule')
|
||||
]
|
||||
|
||||
FOOD = [
|
||||
'cooked_porkchop',
|
||||
'cooked_beef',
|
||||
'bread',
|
||||
'cooked_chicken',
|
||||
'cooked_cod',
|
||||
'cooked_salmon',
|
||||
'cooked_porkchop', 'cooked_beef', 'bread', 'cooked_chicken',
|
||||
'cooked_cod', 'cooked_salmon',
|
||||
]
|
||||
|
||||
LOGS = [
|
||||
'oak_log',
|
||||
'spruce_log',
|
||||
'birch_log',
|
||||
'jungle_log',
|
||||
'acacia_log',
|
||||
'dark_oak_log',
|
||||
name for name in mcdata.mcd.blocks
|
||||
if name.endswith(('_log', '_wood', '_stem', '_hyphae'))
|
||||
]
|
||||
|
||||
|
||||
def get_set(ids):
|
||||
result = set()
|
||||
for item_name in ids:
|
||||
result.add(ITEMS['minecraft:'+item_name]['protocol_id'])
|
||||
return result
|
||||
def get_set(names):
|
||||
return {
|
||||
ITEMS['minecraft:' + name]['protocol_id']
|
||||
for name in names if 'minecraft:' + name in ITEMS
|
||||
}
|
||||
|
||||
|
||||
BED_IDS = get_set(BEDS)
|
||||
SHOVEL_IDS = get_set(SHOVELS)
|
||||
@@ -80,23 +47,31 @@ AXE_IDS = get_set(AXES)
|
||||
FOOD_IDS = get_set(FOOD)
|
||||
SAPLING_IDS = get_set(SAPLINGS)
|
||||
LOG_IDS = get_set(LOGS)
|
||||
|
||||
ITEM_NAMES = {}
|
||||
for item_name, item in ITEMS.items():
|
||||
ITEM_NAMES[ITEMS[item_name]['protocol_id']] = item_name.replace('minecraft:', '')
|
||||
ITEM_NAMES = {item['protocol_id']: name.removeprefix('minecraft:')
|
||||
for name, item in ITEMS.items()}
|
||||
|
||||
|
||||
def get_id(name):
|
||||
return ITEMS['minecraft:' + name]['protocol_id']
|
||||
|
||||
|
||||
def get_sapling_id(tree_type):
|
||||
"""Return the plantable sapling/propagule item for a tree species."""
|
||||
for suffix in ('_sapling', '_propagule'):
|
||||
item = ITEMS.get('minecraft:' + tree_type + suffix)
|
||||
if item is not None:
|
||||
return item['protocol_id']
|
||||
return None
|
||||
|
||||
|
||||
def get_name(idx):
|
||||
return ITEM_NAMES[idx]
|
||||
|
||||
|
||||
CHEST_ID = get_id('chest')
|
||||
GAPPLE_ID = get_id('enchanted_golden_apple')
|
||||
SAND_ID = get_id('sand')
|
||||
NETHERWART_ID = get_id('nether_wart')
|
||||
|
||||
CARROT_ID = get_id('carrot')
|
||||
POTATO_ID = get_id('potato')
|
||||
WHEAT_ID = get_id('wheat')
|
||||
@@ -104,25 +79,41 @@ WHEAT_SEEDS_ID = get_id('wheat_seeds')
|
||||
BEETROOT_SEEDS_ID = get_id('beetroot_seeds')
|
||||
PUMPKIN_ID = get_id('pumpkin')
|
||||
BEETROOT_ID = get_id('beetroot')
|
||||
|
||||
EMERALD_ID = get_id('emerald')
|
||||
BERRIES_ID = get_id('sweet_berries')
|
||||
IRON_INGOT_ID = get_id('iron_ingot')
|
||||
|
||||
|
||||
_LABEL_ITEM_IDS = {
|
||||
'seeds': get_set({
|
||||
'beetroot', 'beetroot_seeds', 'carrot', 'melon_seeds',
|
||||
'nether_wart', 'pitcher_pod', 'potato', 'pumpkin_seeds',
|
||||
'torchflower_seeds', 'wheat_seeds',
|
||||
}),
|
||||
'wheat': {WHEAT_ID},
|
||||
}
|
||||
|
||||
|
||||
def storage_item_ids_for_label(label):
|
||||
"""Return protocol item IDs assigned to a sign storage label."""
|
||||
normalized = ' '.join(str(label).casefold().split()).strip(' :')
|
||||
normalized = (normalized.rstrip('s')
|
||||
if normalized not in ('seeds', 'beds') else normalized)
|
||||
return set(_LABEL_ITEM_IDS.get(normalized, ()))
|
||||
|
||||
|
||||
INIT_NEEDED_ITEMS = BED_IDS | FOOD_IDS
|
||||
INIT_NEEDED_ITEMS.add(CHEST_ID)
|
||||
|
||||
NEEDED_ITEMS = INIT_NEEDED_ITEMS
|
||||
|
||||
INIT_WANTED_ITEMS = set()
|
||||
WANTED_ITEMS = INIT_WANTED_ITEMS
|
||||
|
||||
|
||||
def set_needed(items):
|
||||
global NEEDED_ITEMS
|
||||
NEEDED_ITEMS = INIT_NEEDED_ITEMS | items
|
||||
|
||||
|
||||
def set_wanted(items):
|
||||
global WANTED_ITEMS
|
||||
WANTED_ITEMS = INIT_WANTED_ITEMS | items
|
||||
|
||||
|
||||
@@ -1,32 +1,36 @@
|
||||
"""Minecraft 26.3 client data used by the automation layer.
|
||||
|
||||
The generated data is vendored under ``mosfet/info/data/26.3`` from
|
||||
RosegoldMC/minecraft-data.cr (MIT); see that directory's LICENSE.
|
||||
"""
|
||||
import json
|
||||
from munch import Munch
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import minecraft_data
|
||||
DATA_VERSION = '26.3'
|
||||
DATA_DIR = Path(__file__).resolve().parent / 'data' / DATA_VERSION
|
||||
|
||||
mcd = minecraft_data('1.16.4')
|
||||
|
||||
with open('minecraft_data/registries.json') as f:
|
||||
DATA = json.load(f)
|
||||
def _load(name):
|
||||
with (DATA_DIR / name).open(encoding='utf-8') as source:
|
||||
return json.load(source)
|
||||
|
||||
SINGLE_CHEST = 2
|
||||
DOUBLE_CHEST = 5
|
||||
VILLAGER_TRADE = 18
|
||||
|
||||
WINDOWS = {
|
||||
SINGLE_CHEST: Munch(
|
||||
container=list(range(0, 27)),
|
||||
inventory=list(range(27, 63)),
|
||||
slot_diff=18,
|
||||
),
|
||||
DOUBLE_CHEST: Munch(
|
||||
container=list(range(0, 54)),
|
||||
inventory=list(range(54, 90)),
|
||||
slot_diff=45,
|
||||
),
|
||||
VILLAGER_TRADE: Munch(
|
||||
input1=0,
|
||||
input2=1,
|
||||
output=2,
|
||||
inventory=list(range(3, 38)),
|
||||
),
|
||||
}
|
||||
block_list = _load('blocks.json')
|
||||
item_list = _load('items.json')
|
||||
entity_list = _load('entities.json')
|
||||
materials = _load('materials.json')
|
||||
collision_shapes = _load('blockCollisionShapes.json')
|
||||
|
||||
blocks = {block['name']: block for block in block_list}
|
||||
items = {item['name']: item for item in item_list}
|
||||
entities = {entity['name']: entity for entity in entity_list}
|
||||
|
||||
mcd = SimpleNamespace(
|
||||
version=DATA_VERSION,
|
||||
blocks=blocks,
|
||||
items=items,
|
||||
entities=entities,
|
||||
materials=materials,
|
||||
collision_shapes=collision_shapes,
|
||||
)
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
from mosfet.info import items
|
||||
import json
|
||||
"""Minecraft 26.3 entity registry data and legacy mob selectors."""
|
||||
from mosfet.info import items, mcdata
|
||||
|
||||
with open('minecraft_data/registries.json') as f:
|
||||
MOBS = json.load(f)['minecraft:entity_type']['entries']
|
||||
MOBS = {
|
||||
'minecraft:' + name: dict(entity, protocol_id=entity['id'])
|
||||
for name, entity in mcdata.mcd.entities.items()
|
||||
}
|
||||
VILLAGER = MOBS['minecraft:villager']['protocol_id']
|
||||
|
||||
VILLAGER = 93
|
||||
# Villager profession enum values remain the protocol's 0-based profession IDs.
|
||||
ARMORER = 1
|
||||
BUTCHER = 2
|
||||
CARTOGRAPHER = 3
|
||||
@@ -23,53 +26,23 @@ WEAPONSMITH = 14
|
||||
TRADES = {
|
||||
ARMORER: [items.IRON_INGOT_ID],
|
||||
BUTCHER: [items.BERRIES_ID],
|
||||
FARMER: [items.PUMPKIN_ID, items.WHEAT_ID, items.POTATO_ID, items.CARROT_ID, items.BEETROOT_ID],
|
||||
FARMER: [items.PUMPKIN_ID, items.WHEAT_ID, items.POTATO_ID,
|
||||
items.CARROT_ID, items.BEETROOT_ID],
|
||||
TOOLSMITH: [items.IRON_INGOT_ID],
|
||||
WEAPONSMITH: [items.IRON_INGOT_ID],
|
||||
}
|
||||
|
||||
EVIL = [
|
||||
'blaze',
|
||||
'cave_spider',
|
||||
'creeper',
|
||||
'drowned',
|
||||
'elder_guardian',
|
||||
'ender_dragon',
|
||||
'enderman',
|
||||
'endermite',
|
||||
'evoker',
|
||||
'ghast',
|
||||
'giant',
|
||||
'guardian',
|
||||
'hoglin',
|
||||
'husk',
|
||||
'illusioner',
|
||||
'magma_cube',
|
||||
'phantom',
|
||||
'piglin',
|
||||
'piglin_brute',
|
||||
'pillager',
|
||||
'ravager',
|
||||
'shulker',
|
||||
'silverfish',
|
||||
'skeleton',
|
||||
'skeleton_horse',
|
||||
'slime',
|
||||
'spider',
|
||||
'stray',
|
||||
'vex',
|
||||
'vindicator',
|
||||
'witch',
|
||||
'wither',
|
||||
'zoglin',
|
||||
'zombie',
|
||||
'zombie_villager',
|
||||
'blaze', 'cave_spider', 'creeper', 'drowned', 'elder_guardian',
|
||||
'ender_dragon', 'enderman', 'endermite', 'evoker', 'ghast', 'giant',
|
||||
'guardian', 'hoglin', 'husk', 'illusioner', 'magma_cube', 'phantom',
|
||||
'piglin', 'piglin_brute', 'pillager', 'ravager', 'shulker', 'silverfish',
|
||||
'skeleton', 'skeleton_horse', 'slime', 'spider', 'stray', 'vex',
|
||||
'vindicator', 'witch', 'wither', 'zoglin', 'zombie', 'zombie_villager',
|
||||
]
|
||||
|
||||
EVIL_IDS = set()
|
||||
for mob_name in EVIL:
|
||||
EVIL_IDS.add(MOBS['minecraft:'+mob_name]['protocol_id'])
|
||||
|
||||
MOB_NAMES = {}
|
||||
for mob_name, mob in MOBS.items():
|
||||
MOB_NAMES[MOBS[mob_name]['protocol_id']] = mob_name.replace('minecraft:', '')
|
||||
EVIL_IDS = {
|
||||
MOBS['minecraft:' + name]['protocol_id']
|
||||
for name in EVIL if 'minecraft:' + name in MOBS
|
||||
}
|
||||
MOB_NAMES = {entity['protocol_id']: name.removeprefix('minecraft:')
|
||||
for name, entity in MOBS.items()}
|
||||
|
||||
@@ -55,7 +55,7 @@ for module in [
|
||||
importlib.reload(module)
|
||||
|
||||
|
||||
class JobStates:
|
||||
class LegacyJobStates:
|
||||
def idle(self):
|
||||
return []
|
||||
|
||||
@@ -82,7 +82,11 @@ class JobStates:
|
||||
if m.state == m.idle:
|
||||
continue
|
||||
if m.state != m.done:
|
||||
m.run()
|
||||
self.active_machine = m
|
||||
try:
|
||||
m.run()
|
||||
finally:
|
||||
self.active_machine = None
|
||||
return
|
||||
# if we went through them all
|
||||
for m in machines:
|
||||
@@ -152,9 +156,9 @@ class JobStates:
|
||||
]
|
||||
self.sleep_with_bed_states.silent = True
|
||||
self.cache_items_states.silent = True
|
||||
self.grab_supplies_states.supplies = {
|
||||
tuple(items.AXE_IDS): (1, 9),
|
||||
}
|
||||
self.grab_supplies_states.supplies = (
|
||||
self.grab_supplies_states.default_supplies())
|
||||
self.grab_supplies_states.supplies[tuple(items.AXE_IDS)] = (1, 9)
|
||||
|
||||
items.set_needed(items.AXE_IDS)
|
||||
items.set_wanted(items.SAPLING_IDS)
|
||||
@@ -256,9 +260,119 @@ class JobStates:
|
||||
|
||||
def __init__(self, global_state):
|
||||
self.g = global_state
|
||||
self.active_machine = None
|
||||
|
||||
self.init_machines()
|
||||
self.state = self.idle
|
||||
|
||||
def tick(self):
|
||||
self.run_machines(self.state())
|
||||
|
||||
|
||||
class JobStates(LegacyJobStates):
|
||||
"""26.3 facade for migrated gathering and farming workflows."""
|
||||
def __init__(self, global_state):
|
||||
self.g = global_state
|
||||
self.gather_wood_states = gather_wood.GatherWoodStates(global_state)
|
||||
self.gather_crop_states = gather_crop.GatherCropStates(global_state)
|
||||
self.gather_wart_states = gather_wart.GatherWartStates(global_state)
|
||||
self.grab_supplies_states = grab_supplies.GrabSuppliesStates(
|
||||
global_state)
|
||||
self.clear_leaves_states = clear_leaves.ClearLeavesStates(global_state)
|
||||
self.plant_tree_states = plant_tree.PlantTreeStates(global_state)
|
||||
self.grab_sapling_states = grab_sapling.GrabSaplingStates(global_state)
|
||||
self.cache_items_states = cache_items.CacheItemsStates(global_state)
|
||||
self.sleep_with_bed_states = sleep_with_bed.SleepWithBedStates(
|
||||
global_state)
|
||||
self.eat_food_states = eat_food.EatFoodStates(global_state)
|
||||
self.check_threats_states = check_threats.CheckThreatsStates(
|
||||
global_state)
|
||||
self.active_machine = None
|
||||
self.state = self.idle
|
||||
|
||||
def farm_wood(self):
|
||||
self.sleep_with_bed_states.silent = True
|
||||
self.cache_items_states.silent = True
|
||||
self.grab_supplies_states.supplies = (
|
||||
self.grab_supplies_states.default_supplies())
|
||||
self.grab_supplies_states.supplies[tuple(items.AXE_IDS)] = (1, 9)
|
||||
items.set_needed(items.AXE_IDS)
|
||||
items.set_wanted(items.SAPLING_IDS)
|
||||
return [
|
||||
self.grab_supplies_states,
|
||||
self.gather_wood_states,
|
||||
self.clear_leaves_states,
|
||||
self.plant_tree_states,
|
||||
self.grab_sapling_states,
|
||||
self.sleep_with_bed_states,
|
||||
self.eat_food_states,
|
||||
self.cache_items_states,
|
||||
]
|
||||
|
||||
def farm_wart(self):
|
||||
self.sleep_with_bed_states.silent = True
|
||||
self.cache_items_states.silent = True
|
||||
items.set_wanted({items.NETHERWART_ID})
|
||||
return [
|
||||
self.gather_wart_states,
|
||||
self.sleep_with_bed_states,
|
||||
self.eat_food_states,
|
||||
self.cache_items_states,
|
||||
]
|
||||
|
||||
def farm_crop(self):
|
||||
self.cache_items_states.silent = True
|
||||
self.sleep_with_bed_states.silent = True
|
||||
self.sleep_with_bed_states.force_new_bed = False
|
||||
items.set_wanted({
|
||||
items.CARROT_ID,
|
||||
items.POTATO_ID,
|
||||
items.WHEAT_SEEDS_ID,
|
||||
items.BEETROOT_SEEDS_ID,
|
||||
})
|
||||
return [
|
||||
self.grab_supplies_states,
|
||||
self.gather_crop_states,
|
||||
self.sleep_with_bed_states,
|
||||
self.eat_food_states,
|
||||
self.cache_items_states
|
||||
]
|
||||
|
||||
def eat(self):
|
||||
return [self.eat_food_states]
|
||||
|
||||
def sleep(self):
|
||||
self.sleep_with_bed_states.silent = False
|
||||
return [self.sleep_with_bed_states]
|
||||
|
||||
def loiter(self):
|
||||
self.sleep_with_bed_states.silent = True
|
||||
return [self.check_threats_states, self.sleep_with_bed_states,
|
||||
self.eat_food_states]
|
||||
|
||||
def stop(self):
|
||||
if self.g.get('breaking'):
|
||||
self.g.game.cancel_break()
|
||||
if self.g.get('window'):
|
||||
self.g.game.close_window()
|
||||
self.g.path = []
|
||||
self.g.look_at = None
|
||||
if self.sleep_with_bed_states.state == self.sleep_with_bed_states.sleep_bed:
|
||||
self.g.game.leave_bed()
|
||||
self.gather_wood_states.state = self.gather_wood_states.idle
|
||||
self.gather_crop_states.state = self.gather_crop_states.idle
|
||||
self.grab_supplies_states.state = self.grab_supplies_states.idle
|
||||
self.clear_leaves_states.state = self.clear_leaves_states.idle
|
||||
self.plant_tree_states.state = self.plant_tree_states.idle
|
||||
self.grab_sapling_states.state = self.grab_sapling_states.idle
|
||||
self.cache_items_states.state = self.cache_items_states.idle
|
||||
self.sleep_with_bed_states.state = self.sleep_with_bed_states.idle
|
||||
self.sleep_with_bed_states.force_new_bed = False
|
||||
self.eat_food_states.state = self.eat_food_states.idle
|
||||
self.check_threats_states.state = self.check_threats_states.idle
|
||||
self.check_threats_states.safety = None
|
||||
self.check_threats_states.external_safety = False
|
||||
self.gather_crop_states.active_section_anchor = None
|
||||
self.gather_crop_states.completed_crops = 0
|
||||
self.active_machine = None
|
||||
self.state = self.idle
|
||||
|
||||
@@ -3,7 +3,7 @@ import time
|
||||
import importlib
|
||||
import random
|
||||
from itertools import count
|
||||
from math import floor
|
||||
from math import ceil, floor
|
||||
|
||||
from minecraft.networking.types import BlockFace
|
||||
|
||||
@@ -13,66 +13,174 @@ 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
|
||||
|
||||
class CacheItemsStates:
|
||||
def idle(self):
|
||||
return None
|
||||
|
||||
def _has_compatible_labeled_chest_near(self, bed, distance=16):
|
||||
world = self.g.get('world')
|
||||
if world is None:
|
||||
return False
|
||||
keep_slots = self._needed_inventory_slots_to_keep()
|
||||
for chest in world.find_labeled_chests(bed, distance):
|
||||
positions = chest.get('positions') or (chest['position'],)
|
||||
if min(utils.phyp(bed, position) for position in positions) > distance:
|
||||
continue
|
||||
item_ids = chest['item_ids']
|
||||
for slot, item in self.g.inv.items():
|
||||
if (not 9 <= slot <= 44 or not item.present or
|
||||
item.item_id not in item_ids or
|
||||
item.item_id in items.WANTED_ITEMS):
|
||||
continue
|
||||
if (item.item_id in items.NEEDED_ITEMS and
|
||||
slot in keep_slots):
|
||||
continue
|
||||
return True
|
||||
return False
|
||||
|
||||
def init(self):
|
||||
self.skip_slots = []
|
||||
self.skip_inventory_slots = set()
|
||||
self.skip_items = []
|
||||
self.failed_transfer_slots = set()
|
||||
self.pending_transfer = None
|
||||
self.transferred_to_labeled_chest = False
|
||||
self.bad_openings = set()
|
||||
self.is_labeled_container = False
|
||||
self.container_item_ids = None
|
||||
|
||||
num_stacks = self.g.game.count_inventory_slots()
|
||||
has_override = 'minimum' in self.__dict__
|
||||
minimum = self.__dict__.pop(
|
||||
'minimum', self.g.get('minimum_cache_slots', 27))
|
||||
post_sleep_bed = self.g.pop('post_sleep_cache_bed', None)
|
||||
if (not has_override and post_sleep_bed is not None and
|
||||
self._has_compatible_labeled_chest_near(post_sleep_bed)):
|
||||
minimum = ceil(minimum / 2)
|
||||
print('Lowering cache threshold after sleep near a compatible chest:',
|
||||
minimum)
|
||||
print('Inventory amount:', num_stacks)
|
||||
if num_stacks >= self.g.minimum_cache_slots:
|
||||
if num_stacks == 0:
|
||||
self.state = self.cleanup
|
||||
elif num_stacks >= minimum:
|
||||
self.state = self.find_trapped_chests
|
||||
else:
|
||||
print('Aborting caching, not full')
|
||||
self.state = self.cleanup
|
||||
|
||||
def find_trapped_chests(self):
|
||||
print('Finding trapped chests...')
|
||||
print('Finding labeled and trapped chests...')
|
||||
w = self.g.world
|
||||
p = utils.pint(self.g.pos)
|
||||
|
||||
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:', self.trapped_chests)
|
||||
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
|
||||
|
||||
def _opening_in_bad_region(self, world, opening):
|
||||
opening = tuple(opening)
|
||||
if opening in self.bad_openings:
|
||||
return True
|
||||
if not self.bad_openings:
|
||||
return False
|
||||
nearest = min(self.bad_openings,
|
||||
key=lambda bad: utils.phyp(opening, bad))
|
||||
if (world.path_to_place(opening, nearest) and
|
||||
world.path_to_place(nearest, opening)):
|
||||
self.bad_openings.add(opening)
|
||||
return True
|
||||
return False
|
||||
|
||||
def choose_trapped_chest(self):
|
||||
print('Choosing a trapped chest...')
|
||||
print('Choosing a labeled or trapped chest...')
|
||||
self.bad_openings = set()
|
||||
w = self.g.world
|
||||
p = utils.pint(self.g.pos)
|
||||
c = self.g.chunks
|
||||
|
||||
for container in self.labeled_chests:
|
||||
key = container['positions']
|
||||
if key in self.checked_labeled_chests:
|
||||
continue
|
||||
self.checked_labeled_chests.add(key)
|
||||
if not self._has_transferable_item(container['item_ids']):
|
||||
continue
|
||||
|
||||
self.area = container['position']
|
||||
self.container_item_ids = container['item_ids']
|
||||
self.is_labeled_container = True
|
||||
for opening in w.find_cache_openings(self.area, p):
|
||||
opening_position = tuple(opening['position'])
|
||||
if self._opening_in_bad_region(w, opening_position):
|
||||
continue
|
||||
navpath = w.path_to_place(p, opening_position)
|
||||
if navpath:
|
||||
print('Going to labeled chest', container['labels'],
|
||||
self.area)
|
||||
self.opening = opening_position
|
||||
self.open_interaction = opening
|
||||
self.g.path = navpath
|
||||
self.g.look_at = None
|
||||
self.state = self.going_to_trapped_chest
|
||||
return
|
||||
self.bad_openings.add(opening_position)
|
||||
print('No path to labeled chest', self.area)
|
||||
|
||||
if not len(self.trapped_chests):
|
||||
print('No trapped chests')
|
||||
self.is_labeled_container = False
|
||||
self.container_item_ids = None
|
||||
if self.transferred_to_labeled_chest:
|
||||
print('Already cached items in labeled chests; skipping new chest')
|
||||
self.state = self.cleanup
|
||||
return
|
||||
print('No labeled or trapped chests')
|
||||
self.state = self.select_chest
|
||||
return
|
||||
|
||||
self.is_labeled_container = False
|
||||
self.container_item_ids = None
|
||||
chest = self.trapped_chests[0]
|
||||
self.area = chest
|
||||
|
||||
navpath = w.path_to_place_faked(p, chest)
|
||||
print('navpath:', navpath)
|
||||
for opening in w.find_cache_openings(chest, p):
|
||||
opening_position = tuple(opening['position'])
|
||||
if self._opening_in_bad_region(w, opening_position):
|
||||
continue
|
||||
navpath = w.path_to_place(p, opening_position)
|
||||
if navpath:
|
||||
print('navpath to trapped chest:', navpath)
|
||||
self.opening = opening_position
|
||||
self.open_interaction = opening
|
||||
self.g.path = navpath
|
||||
self.g.look_at = None
|
||||
self.state = self.going_to_trapped_chest
|
||||
return
|
||||
self.bad_openings.add(opening_position)
|
||||
|
||||
if navpath:
|
||||
self.g.path = navpath[:-1]
|
||||
self.opening = self.g.path[-1]
|
||||
self.area = chest
|
||||
self.state = self.going_to_trapped_chest
|
||||
return
|
||||
else:
|
||||
self.trapped_chests.pop(0)
|
||||
time.sleep(0.1)
|
||||
self.trapped_chests.pop(0)
|
||||
time.sleep(0.1)
|
||||
|
||||
def going_to_trapped_chest(self):
|
||||
if utils.pint(self.g.pos) == self.opening:
|
||||
self.g.look_at = self.area
|
||||
self.g.look_at = self.open_interaction['look_at']
|
||||
self.wait_time = 0.5
|
||||
self.state = self.turn_to_trapped_chest
|
||||
else:
|
||||
self.g.look_at = None
|
||||
|
||||
def turn_to_trapped_chest(self):
|
||||
self.g.look_at = self.open_interaction['look_at']
|
||||
self.wait_time -= utils.TICK
|
||||
if self.wait_time <= 0:
|
||||
self.state = self.open_chest
|
||||
|
||||
def select_chest(self):
|
||||
self.is_labeled_container = False
|
||||
self.container_item_ids = None
|
||||
if self.g.game.select_item([items.CHEST_ID]):
|
||||
self.state = self.find_cache_spot
|
||||
else:
|
||||
@@ -84,7 +192,7 @@ class CacheItemsStates:
|
||||
w = self.g.world
|
||||
p = utils.pint(self.g.pos)
|
||||
|
||||
for area in w.find_cache_areas(p, 100):
|
||||
for area in w.find_cache_areas(p, 16):
|
||||
print('Found area:', area)
|
||||
if area not in self.bad_areas:
|
||||
break
|
||||
@@ -94,12 +202,19 @@ class CacheItemsStates:
|
||||
return
|
||||
|
||||
self.area = area
|
||||
openings = w.find_cache_openings(self.area)
|
||||
openings = w.find_cache_openings(self.area, p)
|
||||
|
||||
for o in openings:
|
||||
navpath = w.path_to_place(p, o)
|
||||
self.opening = o
|
||||
if navpath: break
|
||||
self.bad_openings = set()
|
||||
for opening in openings:
|
||||
opening_position = tuple(opening['position'])
|
||||
if self._opening_in_bad_region(w, opening_position):
|
||||
continue
|
||||
navpath = w.path_to_place(p, opening_position)
|
||||
if navpath:
|
||||
self.opening = opening_position
|
||||
self.open_interaction = opening
|
||||
break
|
||||
self.bad_openings.add(opening_position)
|
||||
else: # for
|
||||
print('Unable to get to cache area', self.area)
|
||||
self.bad_areas.append(self.area)
|
||||
@@ -107,20 +222,36 @@ class CacheItemsStates:
|
||||
return
|
||||
|
||||
self.g.path = navpath
|
||||
self.g.look_at = None
|
||||
self.state = self.going_to_area
|
||||
|
||||
def going_to_area(self):
|
||||
if utils.pint(self.g.pos) == self.opening:
|
||||
self.g.look_at = self.area
|
||||
self.g.look_at = self.open_interaction['look_at']
|
||||
self.wait_time = 0.5
|
||||
self.state = self.turn_to_cache_spot
|
||||
else:
|
||||
self.g.look_at = None
|
||||
|
||||
def turn_to_cache_spot(self):
|
||||
self.g.look_at = self.open_interaction['look_at']
|
||||
self.wait_time -= utils.TICK
|
||||
if self.wait_time <= 0:
|
||||
self.state = self.place_chest
|
||||
|
||||
def place_chest(self):
|
||||
self.g.game.place_block(self.area, BlockFace.TOP)
|
||||
support = utils.padd(self.area, path.BLOCK_BELOW)
|
||||
self.g.game.place_block(support, BlockFace.TOP, sneaking=True)
|
||||
self.state = self.open_chest
|
||||
|
||||
def open_chest(self):
|
||||
print('Opening chest')
|
||||
self.g.game.open_container(self.area)
|
||||
self.failed_transfer_slots.clear()
|
||||
self.pending_transfer = None
|
||||
self.g.game.open_container(
|
||||
self.open_interaction['target'],
|
||||
face=self.open_interaction['face'],
|
||||
cursor=self.open_interaction['cursor'])
|
||||
self.wait_time = 1
|
||||
self.state = self.wait
|
||||
|
||||
@@ -131,6 +262,59 @@ class CacheItemsStates:
|
||||
else:
|
||||
self.state = self.move_items
|
||||
|
||||
def _needed_inventory_slots_to_keep(self):
|
||||
needed = set(items.NEEDED_ITEMS)
|
||||
groups = (
|
||||
items.BED_IDS, {items.CHEST_ID}, items.FOOD_IDS,
|
||||
items.AXE_IDS, items.SHOVEL_IDS,
|
||||
)
|
||||
keep = set()
|
||||
covered = set()
|
||||
for group in groups:
|
||||
group = needed.intersection(group)
|
||||
if not group:
|
||||
continue
|
||||
covered.update(group)
|
||||
stacks = [(slot, item) for slot, item in self.g.inv.items()
|
||||
if 5 <= slot <= 45 and item.present and
|
||||
item.item_id in group]
|
||||
if stacks:
|
||||
keep.add(max(stacks, key=lambda pair: pair[1].item_count)[0])
|
||||
|
||||
for item_id in needed - covered:
|
||||
stacks = [(slot, item) for slot, item in self.g.inv.items()
|
||||
if 5 <= slot <= 45 and item.present and
|
||||
item.item_id == item_id]
|
||||
if stacks:
|
||||
keep.add(max(stacks, key=lambda pair: pair[1].item_count)[0])
|
||||
return keep
|
||||
|
||||
def _has_transferable_item(self, item_ids):
|
||||
item_ids = set(item_ids)
|
||||
needed_slots = self._needed_inventory_slots_to_keep()
|
||||
planned_skip_items = set(self.skip_items)
|
||||
for inventory_slot, item in self.g.inv.items():
|
||||
if (not item.present or item.item_id not in item_ids or
|
||||
inventory_slot in self.skip_inventory_slots):
|
||||
continue
|
||||
if (item.item_id in items.NEEDED_ITEMS and
|
||||
inventory_slot in needed_slots):
|
||||
continue
|
||||
if (item.item_id in items.WANTED_ITEMS and
|
||||
item.item_id not in planned_skip_items):
|
||||
planned_skip_items.add(item.item_id)
|
||||
continue
|
||||
return True
|
||||
return False
|
||||
|
||||
def _window_player_slot(self, window_slot):
|
||||
offset = window_slot - self.g.window.container_slots
|
||||
if 0 <= offset < 27:
|
||||
return 9 + offset
|
||||
if 27 <= offset < 36:
|
||||
return 36 + offset - 27
|
||||
return None
|
||||
|
||||
def move_items(self):
|
||||
if self.g.item_lock: return
|
||||
w = self.g.window
|
||||
@@ -139,14 +323,34 @@ class CacheItemsStates:
|
||||
print('Didnt get a window, aborting')
|
||||
self.state = self.cleanup
|
||||
return
|
||||
if w.data.window_type != mcdata.SINGLE_CHEST:
|
||||
print('Got wrong window, aborting')
|
||||
if not w.container_slots:
|
||||
print('Chest contents have not arrived, aborting')
|
||||
self.g.game.close_window()
|
||||
self.state = self.cleanup
|
||||
return
|
||||
if w.container_slots not in (27, 54):
|
||||
print('Got non-chest window, aborting')
|
||||
self.g.game.close_window()
|
||||
self.state = self.cleanup
|
||||
return
|
||||
|
||||
w_info = mcdata.WINDOWS[w.data.window_type]
|
||||
w_inventory_slots = w_info.inventory
|
||||
w_container_slots = w_info.container
|
||||
if self.pending_transfer:
|
||||
pending = self.pending_transfer
|
||||
if time.monotonic() < pending['confirm_after']:
|
||||
return
|
||||
source = w.contents.get(pending['window_slot'])
|
||||
moved = (source is None or not source.present or
|
||||
source.item_id != pending['item_id'] or
|
||||
source.item_count < pending['item_count'])
|
||||
if moved:
|
||||
if pending['is_labeled']:
|
||||
self.transferred_to_labeled_chest = True
|
||||
else:
|
||||
self.failed_transfer_slots.add(pending['window_slot'])
|
||||
self.pending_transfer = None
|
||||
|
||||
w_container_slots = range(w.container_slots)
|
||||
w_inventory_slots = range(w.container_slots, len(w.contents))
|
||||
|
||||
used_slots = self.g.game.count_window_slots()
|
||||
print('used:', used_slots, 'total:', len(w_container_slots))
|
||||
@@ -154,10 +358,13 @@ class CacheItemsStates:
|
||||
print('Container is too full, aborting')
|
||||
self.g.game.close_window()
|
||||
self.g.look_at = None
|
||||
self.state = self.cleanup
|
||||
self.state = (self.close_chest if self.is_labeled_container
|
||||
else self.cleanup)
|
||||
return
|
||||
|
||||
slot_list = []
|
||||
needed_slots = (self._needed_inventory_slots_to_keep()
|
||||
if self.is_labeled_container else set())
|
||||
|
||||
for slot_num in w_inventory_slots:
|
||||
if slot_num not in w.contents:
|
||||
@@ -168,10 +375,19 @@ class CacheItemsStates:
|
||||
if not slot.present:
|
||||
continue
|
||||
|
||||
if slot.item_id in items.NEEDED_ITEMS:
|
||||
if self.is_labeled_container:
|
||||
if slot.item_id not in self.container_item_ids:
|
||||
continue
|
||||
inventory_slot = self._window_player_slot(slot_num)
|
||||
if (slot.item_id in items.NEEDED_ITEMS and
|
||||
inventory_slot in needed_slots):
|
||||
continue
|
||||
elif slot.item_id in items.NEEDED_ITEMS:
|
||||
continue
|
||||
|
||||
if slot_num in self.skip_slots:
|
||||
inventory_slot = self._window_player_slot(slot_num)
|
||||
if (inventory_slot in self.skip_inventory_slots or
|
||||
slot_num in self.failed_transfer_slots):
|
||||
continue
|
||||
|
||||
slot_list.append((slot_num, slot))
|
||||
@@ -181,12 +397,21 @@ class CacheItemsStates:
|
||||
for slot_num, slot in slot_list:
|
||||
if slot.item_id in items.WANTED_ITEMS and slot.item_id not in self.skip_items:
|
||||
print('skipping wanted item', slot)
|
||||
self.skip_slots.append(slot_num)
|
||||
inventory_slot = self._window_player_slot(slot_num)
|
||||
if inventory_slot is not None:
|
||||
self.skip_inventory_slots.add(inventory_slot)
|
||||
self.skip_items.append(slot.item_id)
|
||||
continue
|
||||
|
||||
print('moving', slot)
|
||||
|
||||
self.pending_transfer = {
|
||||
'window_slot': slot_num,
|
||||
'item_id': slot.item_id,
|
||||
'item_count': slot.item_count,
|
||||
'is_labeled': self.is_labeled_container,
|
||||
'confirm_after': time.monotonic() + 0.15,
|
||||
}
|
||||
self.g.item_lock = True
|
||||
self.g.game.click_window(slot_num, 0, 1, slot)
|
||||
return
|
||||
@@ -199,11 +424,19 @@ class CacheItemsStates:
|
||||
self.g.game.close_window()
|
||||
if not self.silent:
|
||||
self.g.chat.send('cache at ' + str(self.area)[1:-1])
|
||||
self.state = self.cleanup
|
||||
if self.is_labeled_container:
|
||||
self.is_labeled_container = False
|
||||
self.container_item_ids = None
|
||||
self.state = self.choose_trapped_chest
|
||||
else:
|
||||
self.state = self.cleanup
|
||||
|
||||
def cleanup(self):
|
||||
self.g.look_at = None
|
||||
self.state = self.done
|
||||
if (self.g.get('job') and
|
||||
getattr(self.g.job.state, '__name__', None) == 'cache_items'):
|
||||
self.g.job.state = self.g.job.idle
|
||||
|
||||
def done(self):
|
||||
# never gets ran, placeholder
|
||||
@@ -215,11 +448,19 @@ class CacheItemsStates:
|
||||
|
||||
self.silent = False
|
||||
|
||||
self.skip_slots = []
|
||||
self.skip_inventory_slots = set()
|
||||
self.failed_transfer_slots = set()
|
||||
self.pending_transfer = None
|
||||
self.transferred_to_labeled_chest = False
|
||||
self.skip_items = []
|
||||
|
||||
self.labeled_chests = []
|
||||
self.checked_labeled_chests = set()
|
||||
self.is_labeled_container = False
|
||||
self.container_item_ids = None
|
||||
self.area = None
|
||||
self.opening = None
|
||||
self.open_interaction = None
|
||||
self.trapped_chests = []
|
||||
self.bad_areas = []
|
||||
self.wait_time = 0
|
||||
|
||||
@@ -17,6 +17,10 @@ from mosfet.info import mcdata
|
||||
from mosfet.info import mobs
|
||||
|
||||
class CheckThreatsStates:
|
||||
THREAT_DISTANCE = 20
|
||||
CLEAR_DISTANCE = 30
|
||||
CHECK_INTERVAL = 2.0
|
||||
|
||||
def idle(self):
|
||||
return None
|
||||
|
||||
@@ -28,51 +32,63 @@ class CheckThreatsStates:
|
||||
w = self.g.world
|
||||
p = utils.pint(self.g.pos)
|
||||
|
||||
threats = w.find_threats(p, 40)
|
||||
threats = w.find_threats(p, self.THREAT_DISTANCE)
|
||||
|
||||
if threats:
|
||||
print('Found', len(threats), 'threats, fleeing:')
|
||||
print('Found', len(threats), 'threats, seeking safety:')
|
||||
print(threats)
|
||||
self.threats = threats
|
||||
self.state = self.find_safety
|
||||
else:
|
||||
print('Aborting, no threats')
|
||||
self.state = self.cleanup
|
||||
self.wait_time = self.CHECK_INTERVAL
|
||||
self.state = self.wait
|
||||
|
||||
def find_safety(self):
|
||||
w = self.g.world
|
||||
p = utils.pint(self.g.pos)
|
||||
|
||||
safety = w.find_blocks_indexed(p, [blocks.EMERALD_BLOCK])
|
||||
|
||||
if not safety:
|
||||
print('No emerald blocks found, aborting')
|
||||
self.state = self.cleanup
|
||||
return
|
||||
|
||||
safety.sort(key=lambda s: utils.phyp(p, s))
|
||||
print('Found emerald blocks:', safety)
|
||||
|
||||
for s in safety:
|
||||
s = utils.padd(s, path.BLOCK_ABOVE)
|
||||
navpath = w.path_to_place(p, s)
|
||||
|
||||
if navpath:
|
||||
safety_blocks = w.find_blocks_indexed(
|
||||
p, [blocks.EMERALD_BLOCK], self.THREAT_DISTANCE * 4)
|
||||
for block in safety_blocks:
|
||||
spot = utils.padd(block, path.BLOCK_ABOVE)
|
||||
if w.find_threats(spot, self.CLEAR_DISTANCE):
|
||||
continue
|
||||
navpath = w.path_to_place(p, spot)
|
||||
if navpath is not None:
|
||||
self.safety = spot
|
||||
self.external_safety = True
|
||||
self.g.path = navpath
|
||||
self.state = self.going_to_safety
|
||||
self.safety = s
|
||||
print('Going to safety', self.safety)
|
||||
print('Going to emerald safety point', self.safety)
|
||||
return
|
||||
else:
|
||||
print('Cant get to safety', self.safety)
|
||||
time.sleep(0.1)
|
||||
|
||||
print('Cant get to safety, aborting')
|
||||
self.state = self.cleanup
|
||||
# No configured emerald safe point was reachable. Retreat to a clear,
|
||||
# supported location that the modern navigator can actually reach.
|
||||
for spot in w.find_bed_areas(p, self.CLEAR_DISTANCE * 2):
|
||||
if w.find_threats(spot, self.CLEAR_DISTANCE):
|
||||
continue
|
||||
navpath = w.path_to_place(p, spot)
|
||||
if navpath is not None:
|
||||
self.safety = spot
|
||||
self.external_safety = False
|
||||
self.g.path = navpath
|
||||
self.state = self.going_to_safety
|
||||
print('Fleeing to clear area', self.safety)
|
||||
return
|
||||
|
||||
print('No reachable safe area found')
|
||||
self.wait_time = self.CHECK_INTERVAL
|
||||
self.state = self.wait
|
||||
|
||||
def going_to_safety(self):
|
||||
if utils.pint(self.g.pos) == self.safety:
|
||||
print('At safety spot, waiting to be moved')
|
||||
self.state = self.wait_for_move
|
||||
if self.external_safety:
|
||||
print('At emerald safety point, waiting for server move')
|
||||
self.state = self.wait_for_move
|
||||
else:
|
||||
print('At clear retreat spot')
|
||||
self.wait_time = 3
|
||||
self.state = self.wait
|
||||
|
||||
def wait_for_move(self):
|
||||
# wait for the server to move the bot when it's safe
|
||||
@@ -103,6 +119,8 @@ class CheckThreatsStates:
|
||||
|
||||
self.safety = None
|
||||
self.wait_time = 0
|
||||
self.threats = []
|
||||
self.external_safety = False
|
||||
|
||||
def run(self):
|
||||
self.state()
|
||||
|
||||
@@ -17,6 +17,8 @@ from mosfet.info import mcdata
|
||||
from mosfet.info import mobs
|
||||
|
||||
class ClearLeavesStates:
|
||||
LEAF_BREAK_INTERVAL = 0.6
|
||||
|
||||
def idle(self):
|
||||
return None
|
||||
|
||||
@@ -26,9 +28,13 @@ class ClearLeavesStates:
|
||||
self.state = self.cleanup
|
||||
return
|
||||
|
||||
sapling_type = self.g.chopped_tree + '_sapling'
|
||||
sapling_item = items.get_id(sapling_type)
|
||||
sapling_item = items.get_sapling_id(self.g.chopped_tree)
|
||||
if sapling_item is None:
|
||||
print('No sapling for chopped tree, skipping leaf cleanup')
|
||||
self.state = self.cleanup
|
||||
return
|
||||
num_saplings = self.g.game.count_items([sapling_item])
|
||||
sapling_type = items.get_name(sapling_item)
|
||||
print('Have', num_saplings, sapling_type, 'in inventory')
|
||||
|
||||
if num_saplings > 8:
|
||||
@@ -57,9 +63,13 @@ class ClearLeavesStates:
|
||||
def break_leaves(self):
|
||||
if not self.g.breaking:
|
||||
if self.leaves:
|
||||
now = time.monotonic()
|
||||
if now < self.next_break_at:
|
||||
return
|
||||
leaf = self.leaves.pop(0)
|
||||
self.g.look_at = leaf
|
||||
self.g.game.break_block(leaf)
|
||||
if self.g.game.break_block(leaf):
|
||||
self.next_break_at = now + self.LEAF_BREAK_INTERVAL
|
||||
print('Breaking leaf', leaf)
|
||||
else:
|
||||
self.wait_time = 1
|
||||
@@ -86,6 +96,7 @@ class ClearLeavesStates:
|
||||
|
||||
self.leaves = []
|
||||
self.wait_time = 0
|
||||
self.next_break_at = 0.0
|
||||
|
||||
def run(self):
|
||||
self.state()
|
||||
|
||||
@@ -21,41 +21,86 @@ class EatFoodStates:
|
||||
return None
|
||||
|
||||
def init(self):
|
||||
if self.g.food < 12:
|
||||
food = self.g.get('food')
|
||||
health = self.g.get('health')
|
||||
if food is None:
|
||||
print('No authoritative hunger status yet; not eating')
|
||||
self.state = self.cleanup
|
||||
return
|
||||
|
||||
if food < 12:
|
||||
print('Hungry, eating')
|
||||
self.state = self.select_food
|
||||
return
|
||||
|
||||
if self.g.health < 20 and self.g.food < 18:
|
||||
elif health is not None and health < 20 and food < 18:
|
||||
print('Low health, eating')
|
||||
self.state = self.select_food
|
||||
else:
|
||||
print('Don\'t need to eat, aborting')
|
||||
self.state = self.cleanup
|
||||
return
|
||||
|
||||
print('Don\'t need to eat, aborting')
|
||||
self.state = self.cleanup
|
||||
self.food_before = food
|
||||
self.saturation_before = self.g.get('food_saturation', 0.0) or 0.0
|
||||
self.health_before = health
|
||||
self.selected_item_id = None
|
||||
self.selected_slot = None
|
||||
self.selected_count = 0
|
||||
self.state = self.select_food
|
||||
|
||||
def select_food(self):
|
||||
if self.g.game.select_item(items.FOOD_IDS):
|
||||
self.state = self.eat_food
|
||||
else:
|
||||
if not self.g.game.select_item(items.FOOD_IDS):
|
||||
print('No food, aborting')
|
||||
self.state = self.cleanup
|
||||
return
|
||||
|
||||
self.selected_item_id = self.g.holding
|
||||
self.selected_slot = (
|
||||
45 if self.g.get('holding_hand', 0) == 1 else
|
||||
36 + self.g.get('holding_slot', 0))
|
||||
self.select_deadline = time.monotonic() + 2.0
|
||||
self.state = self.wait_for_selection
|
||||
|
||||
def wait_for_selection(self):
|
||||
selected = self.g.inv.get(self.selected_slot)
|
||||
if (selected and selected.present and
|
||||
selected.item_id == self.selected_item_id):
|
||||
self.selected_count = selected.item_count
|
||||
self.state = self.eat_food
|
||||
elif time.monotonic() >= self.select_deadline:
|
||||
print('Food did not reach the selected hand; aborting')
|
||||
self.state = self.cleanup
|
||||
|
||||
def eat_food(self):
|
||||
self.g.game.use_item(0)
|
||||
|
||||
print('Eating food')
|
||||
self.wait_time = 3
|
||||
hand = self.g.get('holding_hand', 0)
|
||||
print('Eating food from {} hand'.format(
|
||||
'off' if hand else 'main'))
|
||||
self.g.game.use_item(hand)
|
||||
self.eat_deadline = time.monotonic() + 6.0
|
||||
self.state = self.wait
|
||||
|
||||
def wait(self):
|
||||
if self.wait_time > 0:
|
||||
self.wait_time -= utils.TICK
|
||||
else:
|
||||
selected = self.g.inv.get(self.selected_slot)
|
||||
consumed = (
|
||||
not selected or not selected.present or
|
||||
selected.item_id != self.selected_item_id or
|
||||
selected.item_count < self.selected_count)
|
||||
stats_improved = (
|
||||
(self.g.get('food') is not None and
|
||||
self.g.food > self.food_before) or
|
||||
(self.g.get('food_saturation') is not None and
|
||||
self.g.food_saturation > self.saturation_before) or
|
||||
(self.health_before is not None and self.g.get('health') is not None
|
||||
and self.g.health > self.health_before))
|
||||
if consumed or stats_improved:
|
||||
print('Eating confirmed by server state')
|
||||
self.state = self.cleanup
|
||||
elif time.monotonic() >= self.eat_deadline:
|
||||
print('Food use was not confirmed by server state')
|
||||
self.state = self.cleanup
|
||||
|
||||
def cleanup(self):
|
||||
self.state = self.done
|
||||
if (self.g.get('job') and
|
||||
getattr(self.g.job.state, '__name__', None) == 'eat'):
|
||||
self.g.job.state = self.g.job.idle
|
||||
|
||||
def done(self):
|
||||
# never gets ran, placeholder
|
||||
|
||||
@@ -17,12 +17,92 @@ from mosfet.info import mcdata
|
||||
from mosfet.info import mobs
|
||||
|
||||
class GatherCropStates:
|
||||
CROPS_PER_BATCH = 16
|
||||
SECTION_MATURITY_WEIGHT = 2.0
|
||||
|
||||
def idle(self):
|
||||
return None
|
||||
|
||||
def init(self):
|
||||
self.state = self.find_new_crop
|
||||
|
||||
def _select_crop(self, candidates, crop_types, center):
|
||||
"""Stay with a connected same-species patch, nearest patch first."""
|
||||
adjacent_offsets = ((1, 0, 0), (-1, 0, 0),
|
||||
(0, 0, 1), (0, 0, -1))
|
||||
remaining = set(crop_types)
|
||||
component_for = {}
|
||||
component_sizes = {}
|
||||
component_id = 0
|
||||
|
||||
while remaining:
|
||||
seed = remaining.pop()
|
||||
species = crop_types[seed]
|
||||
stack = [seed]
|
||||
component = [seed]
|
||||
component_for[seed] = component_id
|
||||
while stack:
|
||||
x, y, z = stack.pop()
|
||||
for dx, dy, dz in adjacent_offsets:
|
||||
adjacent = (x + dx, y + dy, z + dz)
|
||||
if (adjacent in remaining and
|
||||
crop_types[adjacent] == species):
|
||||
remaining.remove(adjacent)
|
||||
component_for[adjacent] = component_id
|
||||
component.append(adjacent)
|
||||
stack.append(adjacent)
|
||||
component_sizes[component_id] = len(component)
|
||||
component_id += 1
|
||||
|
||||
eligible = [position for position in candidates
|
||||
if position not in self.bad_crops and
|
||||
position in component_for]
|
||||
if not eligible:
|
||||
self.active_section_maturity = (0, 0)
|
||||
return None, 0
|
||||
|
||||
mature_by_component = {}
|
||||
candidates_by_component = {}
|
||||
for position in eligible:
|
||||
component = component_for[position]
|
||||
mature_by_component[component] = (
|
||||
mature_by_component.get(component, 0) + 1)
|
||||
candidates_by_component.setdefault(component, []).append(position)
|
||||
|
||||
active_component = component_for.get(self.active_section_anchor)
|
||||
active_candidates = candidates_by_component.get(active_component, [])
|
||||
if active_candidates:
|
||||
section_candidates = active_candidates
|
||||
selected_component = active_component
|
||||
else:
|
||||
# Favor a nearby section if maturity is similar, but allow a
|
||||
# farther, substantially more-mature section to win. Once chosen,
|
||||
# keep working that connected component until it has no mature
|
||||
# crops left, matching the existing patch-stability behavior.
|
||||
ranked_sections = []
|
||||
for component, positions in candidates_by_component.items():
|
||||
nearest_crop = min(positions, key=lambda position: (
|
||||
utils.phyp(center, position), position))
|
||||
distance = utils.phyp(center, nearest_crop)
|
||||
maturity = (mature_by_component[component] /
|
||||
component_sizes[component])
|
||||
score = distance / (
|
||||
1.0 + self.SECTION_MATURITY_WEIGHT * maturity)
|
||||
ranked_sections.append((
|
||||
score, distance, -mature_by_component[component],
|
||||
nearest_crop, component,
|
||||
))
|
||||
selected_component = min(ranked_sections)[-1]
|
||||
section_candidates = candidates_by_component[selected_component]
|
||||
|
||||
crop = min(section_candidates, key=lambda position: (
|
||||
utils.phyp(center, position), position))
|
||||
section_size = component_sizes[selected_component]
|
||||
self.active_section_anchor = crop
|
||||
self.active_section_maturity = (
|
||||
mature_by_component[selected_component], section_size)
|
||||
return crop, section_size
|
||||
|
||||
def find_new_crop(self):
|
||||
print('Finding new crop...')
|
||||
w = self.g.world
|
||||
@@ -35,15 +115,31 @@ class GatherCropStates:
|
||||
blocks.MATURE_BEETROOT_ID,
|
||||
]
|
||||
|
||||
for crop in w.find_blocks_3d(p, mature_crops, 50, 20, True):
|
||||
if crop not in self.bad_crops:
|
||||
break
|
||||
else: # for
|
||||
print('No good crops left, aborting.')
|
||||
candidates = w.filter_work_positions(
|
||||
w.find_blocks_indexed(p, mature_crops, 50))
|
||||
crop_ids = (blocks.WHEAT_IDS | blocks.POTATO_IDS |
|
||||
blocks.CARROT_IDS | blocks.BEETROOT_IDS)
|
||||
crop_positions = w.filter_work_positions(
|
||||
w.find_blocks_indexed(p, crop_ids, 50))
|
||||
crop_types = {
|
||||
position: blocks.BLOCKS.get(w.block_at(*position))
|
||||
for position in crop_positions
|
||||
}
|
||||
crop, section_size = self._select_crop(candidates, crop_types, p)
|
||||
|
||||
if crop is None:
|
||||
print('No good crops left; running maintenance after {} harvests'.format(
|
||||
self.completed_crops))
|
||||
self.completed_crops = 0
|
||||
self.state = self.cleanup
|
||||
return
|
||||
|
||||
print('Found crop:', crop)
|
||||
mature_count, total_count = self.active_section_maturity
|
||||
maturity_percent = (100 * mature_count / total_count
|
||||
if total_count else 0)
|
||||
print('Found crop:', crop,
|
||||
'(same-species section: {}/{} mature, {:.0f}%)'.format(
|
||||
mature_count, total_count, maturity_percent))
|
||||
self.crop = crop
|
||||
self.type_id = w.block_at(*crop)
|
||||
self.state = self.nav_to_crop
|
||||
@@ -57,7 +153,7 @@ class GatherCropStates:
|
||||
if navpath:
|
||||
print('Going to crop', self.crop)
|
||||
self.g.path = navpath
|
||||
self.g.look_at = utils.padd(self.crop, path.BLOCK_BELOW)
|
||||
self.g.look_at = self.crop
|
||||
self.state = self.going_to_crop
|
||||
else:
|
||||
print('Cant get to it, blacklisting')
|
||||
@@ -71,8 +167,34 @@ class GatherCropStates:
|
||||
self.state = self.break_crop
|
||||
|
||||
def break_crop(self):
|
||||
self.g.game.break_block(self.crop)
|
||||
self.state = self.select_seed
|
||||
print('Requesting crop break at {}: block={}, mode={}, held={}'.format(
|
||||
self.crop, self.g.world.block_at(*self.crop),
|
||||
self.g.get('game_mode'), self.g.get('holding')))
|
||||
if self.g.game.break_block(self.crop):
|
||||
print('Started breaking crop {} (state {})'.format(
|
||||
self.crop, self.type_id))
|
||||
self.break_deadline = time.time() + 5.0
|
||||
self.state = self.wait_break
|
||||
else:
|
||||
print('Break request skipped; current block is',
|
||||
self.g.world.block_at(*self.crop))
|
||||
self.bad_crops.append(self.crop)
|
||||
self.state = self.find_new_crop
|
||||
|
||||
def wait_break(self):
|
||||
current_state = self.g.world.block_at(*self.crop)
|
||||
if current_state != self.type_id:
|
||||
print('Crop break confirmed at {}: {} -> {}'.format(
|
||||
self.crop, self.type_id, current_state))
|
||||
self.seed_deadline = time.monotonic() + 8.0
|
||||
self.seed_wait_logged = False
|
||||
self.state = self.select_seed
|
||||
elif time.time() > self.break_deadline:
|
||||
print('Crop break timed out at {}: expected state {}, server still has {}'.format(
|
||||
self.crop, self.type_id, current_state))
|
||||
print('Crop did not break; blacklisting', self.crop)
|
||||
self.bad_crops.append(self.crop)
|
||||
self.state = self.find_new_crop
|
||||
|
||||
def select_seed(self):
|
||||
p = utils.pint(self.g.pos)
|
||||
@@ -86,9 +208,19 @@ class GatherCropStates:
|
||||
self.target_seed = crop_seeds[self.type_id]
|
||||
|
||||
if self.g.game.select_item([self.target_seed]):
|
||||
self.seed_deadline = None
|
||||
self.state = self.wait_select
|
||||
else:
|
||||
print('Havent picked up seed yet')
|
||||
if (self.seed_deadline is not None and
|
||||
time.monotonic() > self.seed_deadline):
|
||||
print('No seed collected for crop; skipping', self.crop)
|
||||
self.bad_crops.append(self.crop)
|
||||
self.seed_deadline = None
|
||||
self.state = self.find_new_crop
|
||||
elif not getattr(self, 'seed_wait_logged', False):
|
||||
print('Waiting for crop seed {} in inventory/hotbar'.format(
|
||||
self.target_seed))
|
||||
self.seed_wait_logged = True
|
||||
return
|
||||
|
||||
def wait_select(self):
|
||||
@@ -98,17 +230,32 @@ class GatherCropStates:
|
||||
self.state = self.place_crop
|
||||
|
||||
def place_crop(self):
|
||||
p = utils.pint(self.g.pos)
|
||||
p = utils.padd(self.crop, path.BLOCK_BELOW)
|
||||
self.place_deadline = time.time() + 3.0
|
||||
self.g.game.place_block(p, BlockFace.TOP)
|
||||
print('Placed crop')
|
||||
self.state = self.wait_place
|
||||
|
||||
def wait_place(self):
|
||||
w = self.g.world
|
||||
if w.block_at(*self.crop) == blocks.AIR:
|
||||
return
|
||||
else:
|
||||
self.state = self.cleanup
|
||||
current_state = w.block_at(*self.crop)
|
||||
crop_name = blocks.BLOCKS.get(self.type_id)
|
||||
replanted = (current_state not in (None, blocks.AIR) and
|
||||
blocks.BLOCKS.get(current_state) == crop_name and
|
||||
current_state != self.type_id)
|
||||
if replanted:
|
||||
self.completed_crops += 1
|
||||
if self.completed_crops >= self.CROPS_PER_BATCH:
|
||||
print('Completed {} crop harvests; running maintenance'.format(
|
||||
self.completed_crops))
|
||||
self.completed_crops = 0
|
||||
self.state = self.cleanup
|
||||
else:
|
||||
self.state = self.find_new_crop
|
||||
elif time.time() > getattr(self, 'place_deadline', 0):
|
||||
print('Crop did not replant; blacklisting', self.crop)
|
||||
self.bad_crops.append(self.crop)
|
||||
self.state = self.find_new_crop
|
||||
|
||||
def cleanup(self):
|
||||
self.g.look_at = None
|
||||
@@ -125,7 +272,12 @@ class GatherCropStates:
|
||||
self.crop = None
|
||||
self.type_id = None
|
||||
self.target_seed = None
|
||||
self.seed_deadline = None
|
||||
self.seed_wait_logged = False
|
||||
self.active_section_anchor = None
|
||||
self.active_section_maturity = (0, 0)
|
||||
self.bad_crops = []
|
||||
self.completed_crops = 0
|
||||
|
||||
def run(self):
|
||||
self.state()
|
||||
|
||||
@@ -61,12 +61,13 @@ class GatherSandStates:
|
||||
head = utils.padd(p, path.BLOCK_ABOVE)
|
||||
|
||||
for sand in w.find_sand(self.slice, 2, p):
|
||||
if sand not in self.bad_sand:
|
||||
if (sand not in self.bad_sand and
|
||||
w.work_position_allowed(sand)):
|
||||
print('Found sand:', sand)
|
||||
break
|
||||
else: # for
|
||||
print('No good sands left, aborting.')
|
||||
self.state = self.cleanup
|
||||
print('No in-bounds sand left in this slice; trying another.')
|
||||
self.state = self.find_new_slice
|
||||
return
|
||||
|
||||
self.sand = sand
|
||||
|
||||
@@ -1,61 +1,62 @@
|
||||
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 import utils
|
||||
from mosfet.info import blocks
|
||||
from mosfet.info import items
|
||||
from mosfet.info import mcdata
|
||||
from mosfet.info import mobs
|
||||
|
||||
|
||||
class GatherWartStates:
|
||||
WARTS_PER_BATCH = 16
|
||||
BREAK_TIMEOUT = 5.0
|
||||
ITEM_TIMEOUT = 8.0
|
||||
PLACE_TIMEOUT = 3.0
|
||||
|
||||
def idle(self):
|
||||
return None
|
||||
|
||||
def init(self):
|
||||
self.state = self.find_new_wart
|
||||
|
||||
def _blacklist_wart(self):
|
||||
if self.wart is not None and self.wart not in self.bad_warts:
|
||||
self.bad_warts.append(self.wart)
|
||||
|
||||
def find_new_wart(self):
|
||||
print('Finding new wart...')
|
||||
w = self.g.world
|
||||
p = utils.pint(self.g.pos)
|
||||
|
||||
world = self.g.world
|
||||
center = utils.pint(self.g.pos)
|
||||
mature_wart = max(blocks.NETHERWART_IDS)
|
||||
for wart in w.find_blocks_3d(p, [mature_wart], 50, 20, True):
|
||||
if wart not in self.bad_warts:
|
||||
break
|
||||
else: # for
|
||||
candidates = world.find_blocks_indexed(
|
||||
center, {mature_wart}, 50)
|
||||
candidates = world.filter_work_positions(candidates)
|
||||
wart = next((position for position in candidates
|
||||
if position not in self.bad_warts), None)
|
||||
if wart is None:
|
||||
print('No good warts left, aborting.')
|
||||
self.state = self.cleanup
|
||||
return
|
||||
|
||||
print('Found wart:', wart)
|
||||
self.wart = wart
|
||||
self.type_id = mature_wart
|
||||
self.state = self.nav_to_wart
|
||||
|
||||
def nav_to_wart(self):
|
||||
w = self.g.world
|
||||
p = utils.pint(self.g.pos)
|
||||
|
||||
navpath = w.path_to_place(p, self.wart)
|
||||
world = self.g.world
|
||||
position = utils.pint(self.g.pos)
|
||||
navpath = world.path_to_place(position, self.wart)
|
||||
|
||||
if navpath:
|
||||
print('Going to wart', self.wart)
|
||||
self.g.path = navpath
|
||||
self.g.look_at = utils.padd(self.wart, path.BLOCK_BELOW)
|
||||
self.g.look_at = self.wart
|
||||
self.state = self.going_to_wart
|
||||
else:
|
||||
print('Cant get to it, blacklisting')
|
||||
time.sleep(0.1)
|
||||
self.bad_warts.append(wart)
|
||||
self._blacklist_wart()
|
||||
self.state = self.find_new_wart
|
||||
|
||||
def going_to_wart(self):
|
||||
@@ -64,63 +65,92 @@ class GatherWartStates:
|
||||
self.state = self.break_wart
|
||||
|
||||
def break_wart(self):
|
||||
self.g.game.break_block(self.wart)
|
||||
self.wait_time = 0.5
|
||||
self.state = self.wait
|
||||
current = self.g.world.block_at(*self.wart)
|
||||
if current != self.type_id:
|
||||
print('Wart changed before break; searching again')
|
||||
self._blacklist_wart()
|
||||
self.state = self.find_new_wart
|
||||
return
|
||||
|
||||
def wait(self):
|
||||
# wait for the item
|
||||
if self.wait_time > 0:
|
||||
self.wait_time -= utils.TICK
|
||||
if self.g.game.break_block(self.wart):
|
||||
self.break_deadline = time.monotonic() + self.BREAK_TIMEOUT
|
||||
self.state = self.wait_break
|
||||
else:
|
||||
print('Break request skipped; blacklisting', self.wart)
|
||||
self._blacklist_wart()
|
||||
self.state = self.find_new_wart
|
||||
|
||||
def wait_break(self):
|
||||
current = self.g.world.block_at(*self.wart)
|
||||
if current != self.type_id:
|
||||
print('Wart break confirmed at {}: {} -> {}'.format(
|
||||
self.wart, self.type_id, current))
|
||||
self.item_deadline = time.monotonic() + self.ITEM_TIMEOUT
|
||||
self.item_wait_logged = False
|
||||
self.state = self.select_wart
|
||||
elif time.monotonic() > self.break_deadline:
|
||||
print('Wart did not break; blacklisting', self.wart)
|
||||
self._blacklist_wart()
|
||||
self.state = self.find_new_wart
|
||||
|
||||
def select_wart(self):
|
||||
p = utils.pint(self.g.pos)
|
||||
|
||||
if self.g.game.select_item([items.NETHERWART_ID]):
|
||||
self.state = self.wait_select
|
||||
self.wait_time = 0.5
|
||||
else:
|
||||
print('Aborting planting, no wart')
|
||||
self.state = self.cleanup
|
||||
return
|
||||
|
||||
if time.monotonic() > self.item_deadline:
|
||||
print('No nether wart collected; skipping', self.wart)
|
||||
self._blacklist_wart()
|
||||
self.state = self.find_new_wart
|
||||
elif not self.item_wait_logged:
|
||||
print('Waiting for nether wart in inventory/hotbar')
|
||||
self.item_wait_logged = True
|
||||
|
||||
def wait_select(self):
|
||||
# wait a bit to select
|
||||
if self.wait_time > 0:
|
||||
self.wait_time -= utils.TICK
|
||||
else:
|
||||
if self.g.get('holding') == items.NETHERWART_ID:
|
||||
self.state = self.place_wart
|
||||
|
||||
def place_wart(self):
|
||||
p = utils.pint(self.g.pos)
|
||||
self.g.game.place_block(p, BlockFace.TOP)
|
||||
print('Placed wart')
|
||||
soul_sand = utils.padd(self.wart, path.BLOCK_BELOW)
|
||||
self.g.game.place_block(soul_sand, BlockFace.TOP)
|
||||
self.place_deadline = time.monotonic() + self.PLACE_TIMEOUT
|
||||
self.state = self.wait_place
|
||||
self.wait_time = 0.5
|
||||
|
||||
def wait_place(self):
|
||||
# wait a bit for chunk data to update
|
||||
if self.wait_time > 0:
|
||||
self.wait_time -= utils.TICK
|
||||
else:
|
||||
self.state = self.cleanup
|
||||
current = self.g.world.block_at(*self.wart)
|
||||
if current in blocks.NETHERWART_IDS and current != self.type_id:
|
||||
self.completed_warts += 1
|
||||
print('Nether wart replanted at', self.wart)
|
||||
if self.completed_warts >= self.WARTS_PER_BATCH:
|
||||
print('Completed {} nether wart harvests; running maintenance'.format(
|
||||
self.completed_warts))
|
||||
self.completed_warts = 0
|
||||
self.state = self.cleanup
|
||||
else:
|
||||
self.state = self.find_new_wart
|
||||
elif time.monotonic() > self.place_deadline:
|
||||
print('Nether wart did not replant; blacklisting', self.wart)
|
||||
self._blacklist_wart()
|
||||
self.state = self.find_new_wart
|
||||
|
||||
def cleanup(self):
|
||||
self.g.look_at = None
|
||||
self.state = self.done
|
||||
|
||||
def done(self):
|
||||
# never gets ran, placeholder
|
||||
return None
|
||||
|
||||
def __init__(self, global_state):
|
||||
self.g = global_state
|
||||
self.state = self.idle
|
||||
|
||||
self.wart = None
|
||||
self.type_id = None
|
||||
self.bad_warts = []
|
||||
self.wait_time = 0
|
||||
self.completed_warts = 0
|
||||
self.break_deadline = None
|
||||
self.item_deadline = None
|
||||
self.place_deadline = None
|
||||
self.item_wait_logged = False
|
||||
|
||||
def run(self):
|
||||
self.state()
|
||||
|
||||
@@ -1,20 +1,11 @@
|
||||
import re
|
||||
"""Gather naturally generated trees using the active 26.3 world/game APIs."""
|
||||
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
|
||||
|
||||
|
||||
class GatherWoodStates:
|
||||
def bair(self, p):
|
||||
@@ -39,24 +30,34 @@ class GatherWoodStates:
|
||||
w = self.g.world
|
||||
p = utils.pint(self.g.pos)
|
||||
|
||||
for tree in w.find_trees(p, 100):
|
||||
trees = w.filter_work_positions(w.find_trees(p, 100))
|
||||
for tree in trees:
|
||||
if tree in self.bad_trees:
|
||||
continue
|
||||
print('Found tree:', tree)
|
||||
if tree not in self.bad_trees:
|
||||
break
|
||||
tree_type = blocks.BLOCKS[w.block_at(*tree)].replace('_log', '')
|
||||
if items.get_sapling_id(tree_type) is None:
|
||||
print('No plantable sapling for', tree_type, '- skipping')
|
||||
self.bad_trees.append(tree)
|
||||
continue
|
||||
break
|
||||
else: # for
|
||||
print('No good trees left, aborting.')
|
||||
self.state = self.cleanup
|
||||
return
|
||||
|
||||
self.tree = tree
|
||||
self.type = blocks.BLOCKS[w.block_at(*tree)].replace('_log', '')
|
||||
self.type = tree_type
|
||||
print('Type:', self.type)
|
||||
|
||||
self.state = self.find_openings
|
||||
|
||||
def find_openings(self):
|
||||
w = self.g.world
|
||||
self.openings = w.find_tree_openings(self.tree)
|
||||
self.openings = [
|
||||
opening for opening in w.find_tree_openings(self.tree)
|
||||
if w.work_position_allowed(opening)
|
||||
]
|
||||
self.state = self.choose_opening
|
||||
|
||||
def choose_opening(self):
|
||||
|
||||
@@ -44,6 +44,8 @@ class GrabSaplingStates:
|
||||
|
||||
if s.entity_id in self.eid_blacklist:
|
||||
continue
|
||||
if not w.work_position_allowed(s_pos):
|
||||
continue
|
||||
|
||||
# skip if the sapling is floating
|
||||
if self.g.chunks.get_block_at(*check) in blocks.LEAF_IDS | {0}:
|
||||
|
||||
@@ -13,16 +13,24 @@ 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
|
||||
|
||||
class GrabSuppliesStates:
|
||||
DEFAULT_SUPPLIES = {
|
||||
tuple(items.BED_IDS): (1, 1),
|
||||
(items.CHEST_ID,): (1, 1),
|
||||
tuple(items.FOOD_IDS): (1, 1),
|
||||
}
|
||||
|
||||
def default_supplies(self):
|
||||
return dict(self.DEFAULT_SUPPLIES)
|
||||
|
||||
def idle(self):
|
||||
return None
|
||||
|
||||
def init(self):
|
||||
print('Started grab supplies states')
|
||||
self.checked_barrels = []
|
||||
self.checked_supply_chests = set()
|
||||
|
||||
used_slots = self.g.game.count_inventory_slots()
|
||||
print('used:', used_slots, 'total:', self.g.maximum_supply_slots)
|
||||
@@ -31,89 +39,240 @@ class GrabSuppliesStates:
|
||||
self.state = self.cleanup
|
||||
return
|
||||
|
||||
self.checked_ground_items = set()
|
||||
self.checked_ground_groups = set()
|
||||
self.checked_supply_chests = set()
|
||||
self.ground_stack_counts = {}
|
||||
self.ground_entity_id = None
|
||||
self.ground_position = None
|
||||
if self.supplies:
|
||||
self.state = self.check_supplies
|
||||
else:
|
||||
print('Aborting getting supplies, none specified')
|
||||
self.state = self.cleanup
|
||||
|
||||
def _has_nearby_ground_items(self, item_ids, maximum_stacks):
|
||||
if (maximum_stacks and
|
||||
self.ground_stack_counts.get(item_ids, 0) >= maximum_stacks):
|
||||
return False
|
||||
p = utils.pint(self.g.pos)
|
||||
return any(
|
||||
obj.entity_id not in self.checked_ground_items and
|
||||
utils.phyp(p, (obj.x, obj.y, obj.z)) <= 16
|
||||
for obj in self.g.world.find_objects(item_ids))
|
||||
|
||||
def has_nearby_ground_supply(self):
|
||||
return any(
|
||||
self._has_nearby_ground_items(item_ids, limits[1])
|
||||
for item_ids, limits in self.supplies.items())
|
||||
|
||||
def _record_ground_pickup(self):
|
||||
self.checked_ground_items.add(self.ground_entity_id)
|
||||
self.ground_stack_counts[self.target_items] = (
|
||||
self.ground_stack_counts.get(self.target_items, 0) + 1)
|
||||
if (self.target_maximum_stacks and
|
||||
self.ground_stack_counts[self.target_items] >=
|
||||
self.target_maximum_stacks):
|
||||
self.checked_ground_groups.add(self.target_items)
|
||||
self.g.path = []
|
||||
self.ground_entity_id = None
|
||||
self.ground_position = None
|
||||
|
||||
def check_supplies(self):
|
||||
# check if we need to grab anything
|
||||
for items, limits in self.supplies.items():
|
||||
# Search every configured item group on the ground before looking in
|
||||
# labeled chests; a missing bed must not hide a nearby chest or food drop.
|
||||
missing = []
|
||||
for item_ids, limits in self.supplies.items():
|
||||
minimum, maximum = limits
|
||||
print('Checking items:', items)
|
||||
num_items = self.g.game.count_items(items)
|
||||
print('Checking items:', item_ids)
|
||||
num_items = self.g.game.count_items(item_ids)
|
||||
print('Have:', num_items)
|
||||
|
||||
if (item_ids not in self.checked_ground_groups and
|
||||
self._has_nearby_ground_items(item_ids, maximum)):
|
||||
print('Found matching supplies on the ground')
|
||||
self.target_items = item_ids
|
||||
self.target_minimum = minimum
|
||||
self.target_maximum_stacks = maximum
|
||||
self.state = self.find_ground_items
|
||||
return
|
||||
|
||||
if num_items >= minimum:
|
||||
print('Have enough, skipping')
|
||||
continue
|
||||
|
||||
print('Need at least one item')
|
||||
self.state = self.find_barrels
|
||||
missing.append((item_ids, minimum, maximum))
|
||||
if item_ids not in self.checked_ground_groups:
|
||||
self.target_items = item_ids
|
||||
self.target_minimum = minimum
|
||||
self.target_maximum_stacks = maximum
|
||||
self.state = self.find_ground_items
|
||||
return
|
||||
|
||||
if missing:
|
||||
self.target_items, self.target_minimum, self.target_maximum_stacks = missing[0]
|
||||
print('No more ground drops; checking supply-labeled chests for',
|
||||
self.target_items)
|
||||
self.state = self.find_supply_chests
|
||||
return
|
||||
|
||||
print('Aborting, dont need any supplies')
|
||||
self.state = self.cleanup
|
||||
|
||||
def find_barrels(self):
|
||||
print('Finding barrels...')
|
||||
w = self.g.world
|
||||
p = utils.pint(self.g.pos)
|
||||
|
||||
self.barrels = w.find_blocks_indexed(p, blocks.BARREL_IDS, 80)
|
||||
print('Found:', self.barrels)
|
||||
self.state = self.choose_barrel
|
||||
|
||||
def choose_barrel(self):
|
||||
print('Choosing a barrel...')
|
||||
for barrel in self.barrels:
|
||||
if barrel in self.checked_barrels:
|
||||
continue
|
||||
if barrel in self.bad_barrels:
|
||||
continue
|
||||
|
||||
print('Chose:', barrel)
|
||||
self.barrel = barrel
|
||||
self.state = self.path_to_barrel
|
||||
def find_ground_items(self):
|
||||
stack_count = self.ground_stack_counts.get(self.target_items, 0)
|
||||
if self.target_maximum_stacks and stack_count >= self.target_maximum_stacks:
|
||||
self.checked_ground_groups.add(self.target_items)
|
||||
if (self.g.game.count_items(self.target_items) <
|
||||
self.target_minimum):
|
||||
self.state = self.find_supply_chests
|
||||
else:
|
||||
self.state = self.check_supplies
|
||||
return
|
||||
|
||||
print('No barrels')
|
||||
print('Looking for supplies on the ground...')
|
||||
p = utils.pint(self.g.pos)
|
||||
ground_items = self.g.world.find_objects(self.target_items)
|
||||
ground_items.sort(key=lambda obj: utils.phyp(
|
||||
p, (obj.x, obj.y, obj.z)))
|
||||
|
||||
for obj in ground_items:
|
||||
if obj.entity_id in self.checked_ground_items:
|
||||
continue
|
||||
current_count = self.g.game.count_items(self.target_items)
|
||||
if utils.phyp(p, (obj.x, obj.y, obj.z)) > 16:
|
||||
continue
|
||||
target = utils.pint((obj.x, obj.y, obj.z))
|
||||
self.ground_entity_id = obj.entity_id
|
||||
self.ground_position = target
|
||||
self.ground_required_count = max(
|
||||
self.target_minimum, current_count + 1)
|
||||
if utils.phyp(p, (obj.x, obj.y, obj.z)) <= 1.25:
|
||||
self.g.path = []
|
||||
self.wait_time = 1.0
|
||||
self.state = self.wait_for_ground_item
|
||||
return
|
||||
|
||||
navpath = self.g.world.path_to_place(p, target)
|
||||
if not navpath:
|
||||
self.checked_ground_items.add(obj.entity_id)
|
||||
continue
|
||||
|
||||
print('Going to ground item', obj.item_id, target)
|
||||
self.g.path = navpath
|
||||
self.state = self.going_to_ground_item
|
||||
return
|
||||
|
||||
self.checked_ground_groups.add(self.target_items)
|
||||
self.state = self.check_supplies
|
||||
|
||||
def going_to_ground_item(self):
|
||||
obj = self.g.objects.get(self.ground_entity_id)
|
||||
have_enough = (self.g.game.count_items(self.target_items) >=
|
||||
self.ground_required_count)
|
||||
if have_enough:
|
||||
print('Picked up required ground supplies')
|
||||
self._record_ground_pickup()
|
||||
self.state = self.check_supplies
|
||||
elif (obj is None or
|
||||
utils.pint(self.g.pos) == self.ground_position or
|
||||
utils.phyp(self.g.pos, (obj.x, obj.y, obj.z)) <= 1.25):
|
||||
self.wait_time = 1.0
|
||||
self.state = self.wait_for_ground_item
|
||||
|
||||
def wait_for_ground_item(self):
|
||||
if (self.g.game.count_items(self.target_items) >=
|
||||
self.ground_required_count):
|
||||
print('Picked up required ground supplies')
|
||||
self._record_ground_pickup()
|
||||
self.state = self.check_supplies
|
||||
return
|
||||
|
||||
if self.wait_time > 0:
|
||||
self.wait_time -= utils.TICK
|
||||
return
|
||||
|
||||
if self.ground_entity_id not in self.g.objects:
|
||||
# Entity removal and inventory updates can arrive in either order.
|
||||
self.state = self.check_supplies
|
||||
return
|
||||
|
||||
print('Could not pick up ground item; trying another')
|
||||
self.checked_ground_items.add(self.ground_entity_id)
|
||||
self.g.path = []
|
||||
self.ground_entity_id = None
|
||||
self.ground_position = None
|
||||
self.state = self.find_ground_items
|
||||
|
||||
@staticmethod
|
||||
def _chest_event_key(event):
|
||||
return (event.get('timestamp'), tuple(event.get('position', ())))
|
||||
|
||||
def _refresh_useless_chests(self):
|
||||
events = self.g.get('chest_open_events', ())
|
||||
current_events = {self._chest_event_key(event) for event in events}
|
||||
for event in events:
|
||||
event_key = self._chest_event_key(event)
|
||||
if event_key in self._processed_chest_open_events:
|
||||
continue
|
||||
self._processed_chest_open_events.add(event_key)
|
||||
position = tuple(event.get('position', ()))
|
||||
reopened = [key for key in self.useless_chests
|
||||
if position in key]
|
||||
for key in reopened:
|
||||
self.useless_chests.remove(key)
|
||||
self.checked_supply_chests.discard(key)
|
||||
print('Supply chest was opened by another player; checking it again:',
|
||||
position)
|
||||
self._processed_chest_open_events.intersection_update(current_events)
|
||||
|
||||
def find_supply_chests(self):
|
||||
print('Finding chests labeled for this bot\'s supplies...')
|
||||
p = utils.pint(self.g.pos)
|
||||
self.supply_chests = self.g.world.find_supply_chests(
|
||||
p, self.g.name, 80)
|
||||
print('Found:', len(self.supply_chests), 'supply-labeled chests')
|
||||
self.state = self.choose_supply_chest
|
||||
|
||||
def choose_supply_chest(self):
|
||||
print('Choosing a supply-labeled chest...')
|
||||
for container in self.supply_chests:
|
||||
key = tuple(container['positions'])
|
||||
if key in self.useless_chests or key in self.checked_supply_chests:
|
||||
continue
|
||||
self.checked_supply_chests.add(key)
|
||||
self.current_supply_chest_key = key
|
||||
self.chest = container['position']
|
||||
self.area = self.chest
|
||||
print('Chose supply chest:', self.chest)
|
||||
self.state = self.path_to_supply_chest
|
||||
return
|
||||
|
||||
print('No more supply-labeled chests')
|
||||
self.state = self.cleanup
|
||||
|
||||
def path_to_barrel(self):
|
||||
print('Finding path to barrel')
|
||||
w = self.g.world
|
||||
def path_to_supply_chest(self):
|
||||
print('Finding path to supply chest')
|
||||
p = utils.pint(self.g.pos)
|
||||
c = self.g.chunks
|
||||
|
||||
navpath = w.path_to_place_faked(p, self.barrel)
|
||||
navpath = self.g.world.path_to_place_faked(p, self.chest)
|
||||
print('navpath:', navpath)
|
||||
|
||||
if navpath:
|
||||
self.g.path = navpath[:-1]
|
||||
self.opening = self.g.path[-1]
|
||||
self.checked_barrels.append(self.barrel)
|
||||
self.area = self.barrel
|
||||
self.state = self.going_to_barrel
|
||||
self.state = self.going_to_supply_chest
|
||||
self.checked_supplies = []
|
||||
return
|
||||
else:
|
||||
print('No path, blacklisting barrel')
|
||||
time.sleep(0.1)
|
||||
self.bad_barrels.append(self.barrel)
|
||||
if len(self.bad_barrels) > 3:
|
||||
self.state = self.cleanup
|
||||
else:
|
||||
self.state = self.choose_barrel
|
||||
print('Supply chest is unreachable; trying another labeled chest')
|
||||
self.state = self.choose_supply_chest
|
||||
|
||||
def going_to_barrel(self):
|
||||
def going_to_supply_chest(self):
|
||||
if utils.pint(self.g.pos) == self.opening:
|
||||
self.g.look_at = self.area
|
||||
self.state = self.open_barrel
|
||||
self.state = self.open_supply_chest
|
||||
|
||||
def open_barrel(self):
|
||||
print('Opening barrel')
|
||||
def open_supply_chest(self):
|
||||
print('Opening supply chest')
|
||||
self.g.game.open_container(self.area)
|
||||
self.wait_time = 1
|
||||
self.state = self.wait
|
||||
@@ -149,8 +308,11 @@ class GrabSuppliesStates:
|
||||
self.state = self.grab_items
|
||||
return
|
||||
|
||||
print('Aborting, dont need any more supplies')
|
||||
self.state = self.close_barrel
|
||||
print('No matching items in this supply chest')
|
||||
key = getattr(self, 'current_supply_chest_key', None)
|
||||
if key is not None and key not in self.useless_chests:
|
||||
self.useless_chests.append(key)
|
||||
self.state = self.close_supply_chest
|
||||
|
||||
def grab_items(self):
|
||||
if self.g.item_lock: return
|
||||
@@ -160,8 +322,8 @@ class GrabSuppliesStates:
|
||||
print('Didnt get a window, aborting')
|
||||
self.state = self.cleanup
|
||||
return
|
||||
if w.data.window_type != mcdata.SINGLE_CHEST:
|
||||
print('Got wrong window, aborting')
|
||||
if w.get('container_slots', 0) not in (27, 54):
|
||||
print('Got wrong container size, aborting')
|
||||
self.state = self.cleanup
|
||||
return
|
||||
used_slots = self.g.game.count_inventory_slots()
|
||||
@@ -173,10 +335,7 @@ class GrabSuppliesStates:
|
||||
self.state = self.cleanup
|
||||
return
|
||||
|
||||
w_info = mcdata.WINDOWS[w.data.window_type]
|
||||
w_container_slots = w_info.container
|
||||
|
||||
for slot_num in w_container_slots:
|
||||
for slot_num in range(w.container_slots):
|
||||
if slot_num not in w.contents:
|
||||
continue
|
||||
|
||||
@@ -202,11 +361,11 @@ class GrabSuppliesStates:
|
||||
self.wait_time = 0.25
|
||||
self.state = self.wait
|
||||
|
||||
def close_barrel(self):
|
||||
print('Closing barrel')
|
||||
def close_supply_chest(self):
|
||||
print('Closing supply chest')
|
||||
self.g.game.close_window()
|
||||
self.g.look_at = None
|
||||
self.state = self.choose_barrel
|
||||
self.state = self.choose_supply_chest
|
||||
|
||||
def cleanup(self):
|
||||
self.state = self.done
|
||||
@@ -219,11 +378,16 @@ class GrabSuppliesStates:
|
||||
self.g = global_state
|
||||
self.state = self.idle
|
||||
|
||||
self.supplies = {}
|
||||
self.barrels = []
|
||||
self.checked_barrels = []
|
||||
self.bad_barrels = []
|
||||
self.barrel = None
|
||||
self.supplies = self.default_supplies()
|
||||
self.supply_chests = []
|
||||
self.checked_supply_chests = set()
|
||||
self.useless_chests = []
|
||||
self._processed_chest_open_events = {
|
||||
self._chest_event_key(event)
|
||||
for event in self.g.get('chest_open_events', ())
|
||||
}
|
||||
self.current_supply_chest_key = None
|
||||
self.supply_chest = None
|
||||
self.checked_supplies = []
|
||||
self.target_items = None
|
||||
self.maximum_stacks = 0
|
||||
@@ -233,4 +397,5 @@ class GrabSuppliesStates:
|
||||
self.wait_time = 0
|
||||
|
||||
def run(self):
|
||||
self._refresh_useless_chests()
|
||||
self.state()
|
||||
|
||||
@@ -39,9 +39,13 @@ class PlantTreeStates:
|
||||
|
||||
def select_sapling(self):
|
||||
p = utils.pint(self.g.pos)
|
||||
sapling_type = self.g.chopped_tree + '_sapling'
|
||||
sapling_item = items.get_id(sapling_type)
|
||||
sapling_item = items.get_sapling_id(self.g.chopped_tree)
|
||||
if sapling_item is None:
|
||||
print('Aborting planting, no sapling for', self.g.chopped_tree)
|
||||
self.state = self.cleanup
|
||||
return
|
||||
|
||||
sapling_type = items.get_name(sapling_item)
|
||||
if self.g.game.select_item([sapling_item]):
|
||||
self.g.look_at = utils.padd(p, path.BLOCK_BELOW)
|
||||
self.state = self.wait_select
|
||||
@@ -76,6 +80,8 @@ class PlantTreeStates:
|
||||
p = utils.pint(self.g.pos)
|
||||
|
||||
for opening in w.find_tree_openings(p)[::-1]:
|
||||
if not w.work_position_allowed(opening):
|
||||
continue
|
||||
print('trying sapling opening', opening)
|
||||
navpath = w.path_to_place(p, opening)
|
||||
if navpath:
|
||||
|
||||
@@ -21,25 +21,79 @@ class SleepWithBedStates:
|
||||
return None
|
||||
|
||||
def init(self):
|
||||
if self.g.time < 12000:
|
||||
self.sleep_confirmed = False
|
||||
self.my_bed = False
|
||||
self.area = None
|
||||
self.opening = None
|
||||
self.bed_head = 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')
|
||||
self.sleep_attempt_started_at = current_time
|
||||
if current_time is None or current_time < 12000:
|
||||
print('Aborting sleep, not night')
|
||||
self.state = self.cleanup
|
||||
return
|
||||
|
||||
if self.g.dimension != 'overworld':
|
||||
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 find_beds(self):
|
||||
print('Finding beds...')
|
||||
w = self.g.world
|
||||
p = utils.pint(self.g.pos)
|
||||
|
||||
result = w.find_blocks_indexed(p, blocks.BED_IDS, 80)
|
||||
if 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))
|
||||
self.beds = []
|
||||
for bed in result:
|
||||
if bed in self.bad_beds:
|
||||
@@ -57,38 +111,55 @@ class SleepWithBedStates:
|
||||
print('Choosing a bed...')
|
||||
w = self.g.world
|
||||
p = utils.pint(self.g.pos)
|
||||
c = self.g.chunks
|
||||
|
||||
if not len(self.beds):
|
||||
print('No beds')
|
||||
self.state = self.select_bed
|
||||
return
|
||||
while self.beds:
|
||||
bed = self.beds.pop(0)
|
||||
print('Chose:', bed)
|
||||
navpath = w.path_to_place_faked(p, bed)
|
||||
print('navpath:', navpath)
|
||||
if navpath is None:
|
||||
self.bad_beds.append(bed)
|
||||
print('Cant get to bed, blacklisting')
|
||||
continue
|
||||
|
||||
bed = self.beds[0]
|
||||
print('Chose:', bed)
|
||||
|
||||
navpath = w.path_to_place_faked(p, bed)
|
||||
print('navpath:', navpath)
|
||||
|
||||
if navpath:
|
||||
self.g.path = navpath[:-1]
|
||||
self.opening = self.g.path[-1]
|
||||
self.g.look_at = self.opening
|
||||
self.area = bed
|
||||
self.bed_head = self._bed_head(bed)
|
||||
self.opening = navpath[-2] if len(navpath) > 1 else p
|
||||
self.g.path = navpath[:-1]
|
||||
self.opening_deadline = time.monotonic() + max(
|
||||
8.0, len(navpath) * 0.75)
|
||||
self.g.look_at = None
|
||||
self.state = self.going_to_bed
|
||||
return
|
||||
else:
|
||||
self.beds.pop(0)
|
||||
self.bad_beds.append(bed)
|
||||
print('Cant get to bed, blacklisting')
|
||||
time.sleep(0.1)
|
||||
self.state = self.select_bed
|
||||
|
||||
print('No reachable beds; trying to place one')
|
||||
self.state = self.select_bed
|
||||
|
||||
def _at_opening(self):
|
||||
position = utils.pint(self.g.pos)
|
||||
return utils.phyp(position, self.opening) <= 1.25
|
||||
|
||||
def going_to_bed(self):
|
||||
if utils.pint(self.g.pos) == self.opening:
|
||||
if self._at_opening():
|
||||
print('At existing bed')
|
||||
self.g.path = []
|
||||
self.my_bed = False
|
||||
self.g.look_at = utils.padd(self.area, path.BLOCK_BELOW)
|
||||
self.g.look_at = self.area
|
||||
self.wait_time = 0.5
|
||||
self.state = self.turn_to_bed
|
||||
elif time.monotonic() >= self.opening_deadline:
|
||||
print('Could not reach bed opening', self.opening,
|
||||
'; trying another bed')
|
||||
self.bad_beds.append(self.area)
|
||||
self.g.look_at = None
|
||||
self.state = self.choose_bed
|
||||
else:
|
||||
self.g.look_at = None
|
||||
|
||||
def turn_to_bed(self):
|
||||
self.g.look_at = self.area
|
||||
self.wait_time -= utils.TICK
|
||||
if self.wait_time <= 0:
|
||||
self.state = self.use_bed
|
||||
|
||||
def select_bed(self):
|
||||
@@ -116,9 +187,24 @@ class SleepWithBedStates:
|
||||
openings = w.find_bed_openings(self.area)
|
||||
|
||||
for o in openings:
|
||||
toward_player = (o[0] - self.area[0], 0,
|
||||
o[2] - self.area[2])
|
||||
# The bed head points away from the player when placing from this
|
||||
# opening, so require that footprint and its support to be clear.
|
||||
head = (self.area[0] - toward_player[0], self.area[1],
|
||||
self.area[2] - toward_player[2])
|
||||
if (w.block_at(*head) != blocks.AIR or
|
||||
w.block_at(*utils.padd(head, path.BLOCK_ABOVE)) != blocks.AIR):
|
||||
continue
|
||||
head_support = w.block_at(*utils.padd(head, path.BLOCK_BELOW))
|
||||
if (head_support is None or
|
||||
head_support in blocks.NON_SOLID_IDS or
|
||||
head_support in blocks.AVOID_IDS):
|
||||
continue
|
||||
navpath = w.path_to_place(p, o)
|
||||
self.opening = o
|
||||
if navpath: break
|
||||
if navpath is not None:
|
||||
break
|
||||
else: # for
|
||||
print('Unable to get to bed area', self.area)
|
||||
self.bad_areas.append(self.area)
|
||||
@@ -126,42 +212,96 @@ class SleepWithBedStates:
|
||||
return
|
||||
|
||||
self.g.path = navpath
|
||||
self.g.look_at = self.opening
|
||||
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:
|
||||
if self._at_opening():
|
||||
print('At bed area')
|
||||
self.g.look_at = utils.padd(self.area, path.BLOCK_BELOW)
|
||||
self.g.path = []
|
||||
self.g.look_at = self.area
|
||||
self.wait_time = 0.5
|
||||
self.state = self.turn_to_bed_area
|
||||
elif time.monotonic() >= self.opening_deadline:
|
||||
print('Could not reach bed placement opening', self.opening)
|
||||
self.bad_areas.append(self.area)
|
||||
self.g.look_at = None
|
||||
self.state = self.cleanup
|
||||
else:
|
||||
self.g.look_at = None
|
||||
|
||||
def turn_to_bed_area(self):
|
||||
self.g.look_at = self.area
|
||||
self.wait_time -= utils.TICK
|
||||
if self.wait_time <= 0:
|
||||
self.state = self.place_bed
|
||||
|
||||
def place_bed(self):
|
||||
print('Placing bed')
|
||||
self.g.game.place_block(self.area, BlockFace.TOP)
|
||||
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.wait_time = 0.5
|
||||
self.bed_place_deadline = time.monotonic() + 5.0
|
||||
self.state = self.wait_use
|
||||
|
||||
def wait_use(self):
|
||||
# wait to use the bed
|
||||
if self.wait_time > 0:
|
||||
self.wait_time -= utils.TICK
|
||||
else:
|
||||
# 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.state = self.use_bed
|
||||
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.state = self.cleanup
|
||||
|
||||
def use_bed(self):
|
||||
w = self.g.world
|
||||
current_time = self.g.get('time')
|
||||
|
||||
if self.g.time < 12550:
|
||||
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 w.check_bed_occupied(self.area):
|
||||
print('Bed occupied, aborting.')
|
||||
self.state = self.cleanup
|
||||
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 < 12550:
|
||||
if (self.sleep_attempt_started_at is not None and
|
||||
self.sleep_attempt_started_at >= 12000 and
|
||||
current_time < 12000):
|
||||
print('Night ended before bed use; resuming the job')
|
||||
self.state = self.cleanup
|
||||
return
|
||||
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
|
||||
|
||||
print('Using bed')
|
||||
self.g.game.place_block(self.area, BlockFace.TOP)
|
||||
# Beds are only 9/16 block tall. Aim inside their collision shape;
|
||||
# the near-top cursor used for placing a new block misses them.
|
||||
self.g.game.place_block(
|
||||
self.area, BlockFace.TOP, cursor_y=0.5)
|
||||
self.sleep_deadline = time.monotonic() + 5.0
|
||||
self.sleep_retry_at = time.monotonic() + 1.5
|
||||
self.sleep_use_attempts = 1
|
||||
self.sleep_confirmed = False
|
||||
if not self.silent:
|
||||
self.g.chat.send('zzz')
|
||||
self.state = self.sleep_bed
|
||||
@@ -169,43 +309,83 @@ class SleepWithBedStates:
|
||||
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)
|
||||
|
||||
if w.check_bed_occupied(self.area):
|
||||
self.sleep_confirmed = True
|
||||
|
||||
if threats:
|
||||
print('Waking up due to threats:')
|
||||
print(threats)
|
||||
self.g.game.leave_bed()
|
||||
if self.sleep_confirmed:
|
||||
self.g.game.leave_bed()
|
||||
self.state = self.cleanup
|
||||
elif self.g.time < 100:
|
||||
elif current_time is not None and current_time < 100:
|
||||
print('Woke up time')
|
||||
self.state = self.break_bed
|
||||
elif self.g.correction_count:
|
||||
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
|
||||
time.monotonic() >= self.sleep_retry_at):
|
||||
print('Bed use not confirmed on foot; trying head block',
|
||||
self.bed_head)
|
||||
self.g.game.place_block(
|
||||
self.bed_head, BlockFace.TOP, cursor_y=0.5)
|
||||
self.sleep_use_attempts += 1
|
||||
self.sleep_retry_at = time.monotonic() + 1.5
|
||||
elif (not self.sleep_confirmed and
|
||||
time.monotonic() >= self.sleep_deadline):
|
||||
print('Bed use was not confirmed; blacklisting', self.area)
|
||||
self.bad_beds.append(self.area)
|
||||
self.state = self.cleanup
|
||||
|
||||
def break_bed(self):
|
||||
if self.my_bed:
|
||||
self.g.game.break_block(self.area)
|
||||
self.state = self.collect_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.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):
|
||||
# wait to pick up bed
|
||||
# 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
|
||||
self.g.look_at = None
|
||||
self.g.path = []
|
||||
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
|
||||
@@ -222,8 +402,15 @@ class SleepWithBedStates:
|
||||
self.bad_beds = []
|
||||
self.area = None
|
||||
self.opening = None
|
||||
self.bed_head = 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.sleep_deadline = 0
|
||||
self.sleep_attempt_started_at = None
|
||||
|
||||
def run(self):
|
||||
self.state()
|
||||
|
||||
@@ -121,11 +121,17 @@ class Pathfinder(AStar):
|
||||
def __init__(self, g):
|
||||
self.g = g
|
||||
self.chunks = g.chunks
|
||||
self.start_time = time.time()
|
||||
self.start_time = time.monotonic()
|
||||
|
||||
@functools.lru_cache(maxsize=BLOCK_CACHE_SIZE)
|
||||
def bair(self, p):
|
||||
return self.chunks.get_block_at(*p) in blocks.NON_SOLID_IDS
|
||||
state_id = self.chunks.get_block_at(*p)
|
||||
if state_id in blocks.DOOR_IDS:
|
||||
if blocks.PROPS.get(state_id, {}).get('open') == 'true':
|
||||
return True
|
||||
if state_id in blocks.OPENABLE_DOOR_IDS:
|
||||
return tuple(p) not in self.g.get('unopenable_doors', set())
|
||||
return state_id in blocks.NON_SOLID_IDS
|
||||
|
||||
@functools.lru_cache(maxsize=BLOCK_CACHE_SIZE)
|
||||
def bavoid(self, p):
|
||||
@@ -267,6 +273,9 @@ class Pathfinder(AStar):
|
||||
return True
|
||||
|
||||
def neighbors(self, node):
|
||||
if time.monotonic() - self.start_time > 2.0:
|
||||
raise AStarTimeout
|
||||
|
||||
results = []
|
||||
|
||||
if self.g.crawling:
|
||||
@@ -296,10 +305,6 @@ class Pathfinder(AStar):
|
||||
if self.check_parkour(node, offset):
|
||||
results.append(utils.padd(node, offset))
|
||||
|
||||
if not results:
|
||||
if time.time() - self.start_time > 2.0:
|
||||
raise(AStarTimeout)
|
||||
|
||||
return results
|
||||
|
||||
def distance_between(self, n1, n2):
|
||||
|
||||
@@ -1,42 +1,37 @@
|
||||
import os
|
||||
from math import floor
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
from math import floor
|
||||
from munch import Munch
|
||||
|
||||
from minecraft.networking.packets import clientbound, serverbound
|
||||
from minecraft.networking.modern import (
|
||||
AddEntityPacket, BlockEntityDataPacket, BlockEventPacket, ContainerOpenPacket,
|
||||
ContainerSetContentPacket, ContainerSetSlotPacket, SetEntityDataPacket,
|
||||
nbt_plain,
|
||||
PaletteSection,
|
||||
EntityPositionSyncPacket, MoveEntityPositionPacket,
|
||||
MoveEntityPositionRotationPacket, MoveEntityRotationPacket,
|
||||
PlayerInfoRemovePacket, PlayerInfoUpdatePacket, RemoveEntitiesPacket,
|
||||
SetCursorItemPacket,
|
||||
)
|
||||
from mosfet.protocol import packets
|
||||
from mosfet.protocol.types import Slot
|
||||
from mosfet.info import blocks, mcdata, mobs
|
||||
|
||||
from mosfet import utils
|
||||
from mosfet.info import blocks
|
||||
|
||||
class DataManager:
|
||||
def __init__(self, directory):
|
||||
self.blocks = {}
|
||||
self.blocks_states = {}
|
||||
self.blocks_properties = {}
|
||||
"""Compatibility facade over the checked-in Minecraft 26.3 data."""
|
||||
def __init__(self, directory=None):
|
||||
self.blocks = mcdata.mcd.blocks
|
||||
self.blocks_states = dict(blocks.BLOCKS)
|
||||
self.blocks_properties = dict(blocks.PROPS)
|
||||
self.registries = {}
|
||||
self.biomes = {}
|
||||
self.entity_type = {}
|
||||
|
||||
if not os.path.isdir(directory):
|
||||
raise FileNotFoundError("%s is not a valid directory")
|
||||
|
||||
if not os.path.isfile("%s/registries.json"%(directory)):
|
||||
raise FileNotFoundError("%s is not a valid minecraft data directory")
|
||||
|
||||
with open("%s/blocks.json"%(directory)) as f:
|
||||
blocks = json.loads(f.read())
|
||||
for x in blocks:
|
||||
for s in blocks[x]['states']:
|
||||
self.blocks_states[s['id']] = x
|
||||
self.blocks_properties[s['id']] = s.get('properties', {})
|
||||
|
||||
with open("%s/registries.json"%(directory)) as f:
|
||||
registries = json.loads(f.read())
|
||||
#for x in registries["minecraft:biome"]["entries"]:
|
||||
# self.biomes[registries["minecraft:biome"]["entries"][x]["protocol_id"]] = x
|
||||
for x in registries["minecraft:entity_type"]["entries"]:
|
||||
self.entity_type[registries["minecraft:entity_type"]["entries"][x]["protocol_id"]] = x
|
||||
self.entity_type = {
|
||||
data['protocol_id']: name
|
||||
for name, data in mobs.MOBS.items()
|
||||
}
|
||||
|
||||
|
||||
class ChunksManager:
|
||||
@@ -191,3 +186,496 @@ class ChatManager:
|
||||
packet = serverbound.play.ChatPacket()
|
||||
packet.message = text
|
||||
self.g.connection.write_packet(packet)
|
||||
|
||||
|
||||
class ChunkColumn:
|
||||
def __init__(self, x, z, sections, min_section):
|
||||
self.x = x
|
||||
self.z = z
|
||||
self.sections = {
|
||||
min_section + offset: section
|
||||
for offset, section in enumerate(sections)
|
||||
}
|
||||
|
||||
def get_block_at(self, x, y, z):
|
||||
section = self.sections.get(y // 16)
|
||||
if section is None:
|
||||
return None
|
||||
index = ((y & 15) * 16 + (z & 15)) * 16 + (x & 15)
|
||||
return section['blocks'].get(index)
|
||||
|
||||
def set_block_at(self, x, y, z, block_state_id):
|
||||
section = self.sections.get(y // 16)
|
||||
if section is None:
|
||||
return None
|
||||
index = ((y & 15) * 16 + (z & 15)) * 16 + (x & 15)
|
||||
previous = section['blocks'].get(index)
|
||||
section['blocks'].set(index, block_state_id)
|
||||
return previous
|
||||
|
||||
|
||||
class WorldState:
|
||||
"""Sparse 26.3 chunk/block-state cache used by world and navigation."""
|
||||
def __init__(self, min_y=-64):
|
||||
self.min_y = min_y
|
||||
self.min_section = min_y // 16
|
||||
self.lock = threading.RLock()
|
||||
self.chunks = {}
|
||||
self.index = {}
|
||||
self.block_entities = {}
|
||||
from mosfet.info import blocks
|
||||
self.indexed_ids = blocks.INDEXED_IDS
|
||||
self.center = None
|
||||
self.radius = None
|
||||
self.dimension = 'minecraft:overworld'
|
||||
self.player_id = None
|
||||
|
||||
def set_dimension(self, dimension, dimension_type=None):
|
||||
with self.lock:
|
||||
if dimension:
|
||||
self.dimension = dimension
|
||||
if dimension_type:
|
||||
min_y = dimension_type.get('min_y', self.min_y)
|
||||
if isinstance(min_y, int):
|
||||
self.min_y = min_y
|
||||
self.min_section = min_y // 16
|
||||
|
||||
def load_chunk(self, packet):
|
||||
with self.lock:
|
||||
# Refresh selectors in case block metadata was reloaded before login.
|
||||
from mosfet.info import blocks
|
||||
self.indexed_ids = blocks.INDEXED_IDS
|
||||
self.unload_chunk(packet.x, packet.z)
|
||||
chunk = ChunkColumn(packet.x, packet.z, packet.sections,
|
||||
self.min_section)
|
||||
self.chunks[(packet.x, packet.z)] = chunk
|
||||
for entity in getattr(packet, 'block_entities', []):
|
||||
pos = (entity['x'], entity['y'], entity['z'])
|
||||
self.set_block_entity(
|
||||
pos, entity['type'], entity.get('data'))
|
||||
for section_y, section in chunk.sections.items():
|
||||
palette = section['blocks']
|
||||
if not self.indexed_ids.intersection(
|
||||
palette.palette or [palette.get(i)
|
||||
for i in range(palette.size)]):
|
||||
continue
|
||||
for index in range(palette.size):
|
||||
state_id = palette.get(index)
|
||||
if state_id not in self.indexed_ids:
|
||||
continue
|
||||
local_x = index & 0xF
|
||||
local_z = (index >> 4) & 0xF
|
||||
local_y = (index >> 8) & 0xF
|
||||
pos = (packet.x * 16 + local_x,
|
||||
section_y * 16 + local_y,
|
||||
packet.z * 16 + local_z)
|
||||
self.index.setdefault(state_id, set()).add(pos)
|
||||
|
||||
def handle_block_update(self, packet):
|
||||
self.set_block_at(packet.x, packet.y, packet.z, packet.block_state_id)
|
||||
|
||||
def handle_section_update(self, packet):
|
||||
with self.lock:
|
||||
for x, y, z, state_id in packet.changes:
|
||||
self.set_block_at(x, y, z, state_id)
|
||||
|
||||
def get_chunk(self, x, z):
|
||||
with self.lock:
|
||||
return self.chunks.get((x, z))
|
||||
|
||||
def get_block_at(self, x, y, z):
|
||||
with self.lock:
|
||||
chunk = self.chunks.get((floor(x / 16), floor(z / 16)))
|
||||
if chunk is None:
|
||||
return None
|
||||
return chunk.get_block_at(floor(x), floor(y), floor(z))
|
||||
|
||||
def indexed_positions(self, block_ids):
|
||||
with self.lock:
|
||||
return [position for block_id in block_ids
|
||||
for position in tuple(self.index.get(block_id, ()))]
|
||||
|
||||
def block_entities_snapshot(self):
|
||||
with self.lock:
|
||||
return dict(self.block_entities)
|
||||
|
||||
def set_block_entity(self, position, entity_type, data):
|
||||
position = tuple(position)
|
||||
with self.lock:
|
||||
if data is None:
|
||||
self.block_entities.pop(position, None)
|
||||
return
|
||||
self.block_entities[position] = {
|
||||
'type': entity_type,
|
||||
'data': nbt_plain(data),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _is_sign_state(block_state_id):
|
||||
from mosfet.info import blocks
|
||||
name = blocks.BLOCKS.get(block_state_id)
|
||||
return name is not None and name.endswith('_sign')
|
||||
|
||||
def set_block_at(self, x, y, z, block_state_id):
|
||||
x, y, z = floor(x), floor(y), floor(z)
|
||||
with self.lock:
|
||||
chunk = self.chunks.get((floor(x / 16), floor(z / 16)))
|
||||
if chunk is None:
|
||||
return False
|
||||
previous = chunk.set_block_at(x, y, z, block_state_id)
|
||||
pos = (x, y, z)
|
||||
if previous in self.indexed_ids:
|
||||
self.index.get(previous, set()).discard(pos)
|
||||
if (self._is_sign_state(previous) and
|
||||
not self._is_sign_state(block_state_id)):
|
||||
self.block_entities.pop(pos, None)
|
||||
if block_state_id in self.indexed_ids:
|
||||
self.index.setdefault(block_state_id, set()).add(pos)
|
||||
return True
|
||||
|
||||
def unload_chunk(self, x, z):
|
||||
with self.lock:
|
||||
chunk = self.chunks.pop((x, z), None)
|
||||
if chunk is None:
|
||||
return
|
||||
x0, z0 = x * 16, z * 16
|
||||
for state_id, locations in list(self.index.items()):
|
||||
remaining = {
|
||||
pos for pos in locations.copy()
|
||||
if not (x0 <= pos[0] < x0 + 16 and
|
||||
z0 <= pos[2] < z0 + 16)
|
||||
}
|
||||
if remaining:
|
||||
self.index[state_id] = remaining
|
||||
else:
|
||||
self.index.pop(state_id, None)
|
||||
self.block_entities = {
|
||||
pos: entity for pos, entity in self.block_entities.items()
|
||||
if not (x0 <= pos[0] < x0 + 16 and
|
||||
z0 <= pos[2] < z0 + 16)
|
||||
}
|
||||
|
||||
def unload_all_chunks(self):
|
||||
with self.lock:
|
||||
self.chunks.clear()
|
||||
self.index.clear()
|
||||
self.block_entities.clear()
|
||||
|
||||
def get_loaded_area(self, ignore_empty=False):
|
||||
with self.lock:
|
||||
if not self.chunks:
|
||||
return None
|
||||
xs = [pos[0] for pos in self.chunks]
|
||||
zs = [pos[1] for pos in self.chunks]
|
||||
ys = [section_y for chunk in self.chunks.values()
|
||||
for section_y in chunk.sections]
|
||||
return ((min(xs), min(ys), min(zs)),
|
||||
(max(xs), max(ys), max(zs)))
|
||||
|
||||
def check_loaded(self, chunk_distance=None):
|
||||
with self.lock:
|
||||
if self.center is None:
|
||||
return bool(self.chunks)
|
||||
radius = self.radius if chunk_distance is None else chunk_distance
|
||||
if radius is None:
|
||||
return bool(self.chunks)
|
||||
cx, cz = self.center
|
||||
return all((x, z) in self.chunks
|
||||
for x in range(cx - radius, cx + radius + 1)
|
||||
for z in range(cz - radius, cz + radius + 1))
|
||||
|
||||
@property
|
||||
def loaded_chunk_count(self):
|
||||
with self.lock:
|
||||
return len(self.chunks)
|
||||
|
||||
def __repr__(self):
|
||||
return ('WorldState(dimension={!r}, chunks={}, min_y={}, center={!r}, '
|
||||
'radius={!r})').format(
|
||||
self.dimension, len(self.chunks), self.min_y,
|
||||
self.center, self.radius)
|
||||
|
||||
|
||||
class ChestOpenManager:
|
||||
"""Track chest viewer-count events and report openings by other players."""
|
||||
OWN_OPEN_TIMEOUT = 3.0
|
||||
|
||||
def __init__(self, global_state):
|
||||
self.g = global_state
|
||||
self.g.chest_viewers = self.g.get('chest_viewers') or {}
|
||||
self.g.chest_open_events = self.g.get('chest_open_events') or []
|
||||
self.g.last_chest_opened_by_other = None
|
||||
self._own_open_suppressions = {}
|
||||
self.g.connection.register_packet_listener(
|
||||
self.handle_block_event, BlockEventPacket)
|
||||
|
||||
def _block_name(self, packet):
|
||||
registry = getattr(self.g.connection, 'registry_ids', {}).get(
|
||||
'minecraft:block', {})
|
||||
name = next((name for name, block_id in registry.items()
|
||||
if block_id == packet.block_id), None)
|
||||
if name is not None:
|
||||
return name.removeprefix('minecraft:')
|
||||
location = packet.location
|
||||
state_id = self.g.chunks.get_block_at(
|
||||
location.x, location.y, location.z)
|
||||
return blocks.BLOCKS.get(state_id)
|
||||
|
||||
def handle_block_event(self, packet):
|
||||
block_name = self._block_name(packet)
|
||||
if (block_name is None or block_name == 'ender_chest' or
|
||||
not (block_name == 'chest' or block_name.endswith('_chest')) or
|
||||
packet.action != 1):
|
||||
return
|
||||
|
||||
location = packet.location
|
||||
position = (location.x, location.y, location.z)
|
||||
viewers = packet.parameter
|
||||
previous_viewers = self.g.chest_viewers.get(position, 0)
|
||||
if viewers:
|
||||
self.g.chest_viewers[position] = viewers
|
||||
else:
|
||||
self.g.chest_viewers.pop(position, None)
|
||||
|
||||
now = time.monotonic()
|
||||
self._own_open_suppressions = {
|
||||
pos: expires for pos, expires in self._own_open_suppressions.items()
|
||||
if expires > now
|
||||
}
|
||||
pending = self.g.get('pending_chest_open')
|
||||
pending_age = (now - pending.get('requested_at', 0)
|
||||
if pending is not None else None)
|
||||
pending_is_fresh = (pending_age is not None and
|
||||
0 <= pending_age <= self.OWN_OPEN_TIMEOUT)
|
||||
pending_positions = (
|
||||
pending.get('positions') or (pending.get('position', ()),)
|
||||
if pending is not None else ()
|
||||
)
|
||||
pending_positions = {tuple(pos) for pos in pending_positions}
|
||||
is_bot_opening = (
|
||||
pending_is_fresh and position in pending_positions
|
||||
)
|
||||
if pending is not None and not pending_is_fresh:
|
||||
self.g.pending_chest_open = None
|
||||
if is_bot_opening:
|
||||
for own_position in pending_positions:
|
||||
self._own_open_suppressions[own_position] = now + 0.5
|
||||
is_bot_opening = (is_bot_opening or
|
||||
position in self._own_open_suppressions)
|
||||
|
||||
if (viewers <= previous_viewers or
|
||||
(is_bot_opening and
|
||||
viewers <= max(1, previous_viewers))):
|
||||
return
|
||||
|
||||
event = {
|
||||
'position': position,
|
||||
'block': block_name,
|
||||
'viewers': viewers,
|
||||
'previous_viewers': previous_viewers,
|
||||
'timestamp': time.time(),
|
||||
}
|
||||
self.g.last_chest_opened_by_other = event
|
||||
self.g.chest_open_events.append(event)
|
||||
del self.g.chest_open_events[:-100]
|
||||
print('[chest] another player opened {} at {} ({} viewer{})'.format(
|
||||
block_name, position, viewers, '' if viewers == 1 else 's'),
|
||||
flush=True)
|
||||
|
||||
|
||||
class EntityManager:
|
||||
def __init__(self, global_state):
|
||||
self.g = global_state
|
||||
self.g.mobs = self.g.get('mobs') or {}
|
||||
self.g.players = self.g.get('players') or {}
|
||||
self.g.objects = self.g.get('objects') or {}
|
||||
self.g.player_names = self.g.get('player_names') or {}
|
||||
register = self.g.connection.register_packet_listener
|
||||
for packet_type, handler in (
|
||||
(AddEntityPacket, self.handle_add_entity),
|
||||
(SetEntityDataPacket, self.handle_entity_data),
|
||||
(BlockEntityDataPacket, self.handle_block_entity_data),
|
||||
(RemoveEntitiesPacket, self.handle_remove_entities),
|
||||
(MoveEntityPositionPacket, self.handle_move),
|
||||
(MoveEntityPositionRotationPacket, self.handle_move),
|
||||
(MoveEntityRotationPacket, self.handle_rotation),
|
||||
(EntityPositionSyncPacket, self.handle_position_sync),
|
||||
(PlayerInfoUpdatePacket, self.handle_player_info),
|
||||
(PlayerInfoRemovePacket, self.handle_player_info_remove),
|
||||
):
|
||||
register(handler, packet_type)
|
||||
|
||||
def handle_add_entity(self, packet):
|
||||
name = mobs.MOB_NAMES.get(packet.entity_type_id, 'unknown')
|
||||
common = dict(entity_id=packet.entity_id, x=packet.x,
|
||||
y=packet.y, z=packet.z)
|
||||
if name == 'player':
|
||||
player_uuid = str(packet.entity_uuid)
|
||||
self.g.players[packet.entity_id] = Munch(
|
||||
**common, player_uuid=player_uuid,
|
||||
yaw=packet.yaw, pitch=packet.pitch)
|
||||
elif name == 'item':
|
||||
self.g.objects[packet.entity_id] = Munch(
|
||||
**common, entity_uuid=str(packet.entity_uuid),
|
||||
velocity_x=packet.velocity_x * 8000,
|
||||
velocity_y=packet.velocity_y * 8000,
|
||||
velocity_z=packet.velocity_z * 8000)
|
||||
else:
|
||||
self.g.mobs[packet.entity_id] = Munch(
|
||||
**common, entity_uuid=str(packet.entity_uuid),
|
||||
type=packet.entity_type_id, yaw=packet.yaw,
|
||||
pitch=packet.pitch)
|
||||
|
||||
def handle_block_entity_data(self, packet):
|
||||
location = packet.location
|
||||
self.g.chunks.set_block_entity(
|
||||
(location.x, location.y, location.z),
|
||||
packet.block_entity_type, packet.data)
|
||||
|
||||
def handle_entity_data(self, packet):
|
||||
obj = self.g.objects.get(packet.entity_id)
|
||||
if obj is None or not packet.item_stacks:
|
||||
return
|
||||
stack = packet.item_stacks[-1]
|
||||
obj.item_id = stack.item_id if stack.present else None
|
||||
obj.item_count = stack.item_count if stack.present else 0
|
||||
|
||||
def _entity(self, entity_id):
|
||||
for collection in (self.g.players, self.g.mobs, self.g.objects):
|
||||
entity = collection.get(entity_id)
|
||||
if entity is not None:
|
||||
return entity
|
||||
return None
|
||||
|
||||
def handle_move(self, packet):
|
||||
entity = self._entity(packet.entity_id)
|
||||
if entity is None:
|
||||
return
|
||||
entity.x += packet.delta_x
|
||||
entity.y += packet.delta_y
|
||||
entity.z += packet.delta_z
|
||||
if hasattr(packet, 'yaw'):
|
||||
entity.yaw = packet.yaw
|
||||
entity.pitch = packet.pitch
|
||||
|
||||
def handle_rotation(self, packet):
|
||||
entity = self._entity(packet.entity_id)
|
||||
if entity is not None:
|
||||
entity.yaw = packet.yaw
|
||||
entity.pitch = packet.pitch
|
||||
|
||||
def handle_position_sync(self, packet):
|
||||
entity = self._entity(packet.entity_id)
|
||||
if entity is not None:
|
||||
entity.x, entity.y, entity.z = packet.x, packet.y, packet.z
|
||||
entity.yaw = packet.yaw
|
||||
entity.pitch = packet.pitch
|
||||
|
||||
def handle_remove_entities(self, packet):
|
||||
for entity_id in packet.entity_ids:
|
||||
self.g.players.pop(entity_id, None)
|
||||
self.g.mobs.pop(entity_id, None)
|
||||
self.g.objects.pop(entity_id, None)
|
||||
|
||||
def handle_player_info(self, packet):
|
||||
for profile_uuid, name in packet.entries:
|
||||
if name:
|
||||
uuid_text = str(profile_uuid)
|
||||
self.g.player_names[uuid_text] = name
|
||||
self.g.player_names[name] = profile_uuid
|
||||
self.g.player_names[name.lower()] = profile_uuid
|
||||
|
||||
def handle_player_info_remove(self, packet):
|
||||
removed = {str(uuid) for uuid in packet.uuids}
|
||||
for key, value in list(self.g.player_names.items()):
|
||||
if str(value) in removed or str(key) in removed:
|
||||
del self.g.player_names[key]
|
||||
|
||||
|
||||
class InventoryManager:
|
||||
def __init__(self, global_state):
|
||||
self.g = global_state
|
||||
self.g.inv = self.g.get('inv') or {}
|
||||
self.g.window = self.g.get('window')
|
||||
self.g.item_lock = self.g.get('item_lock', False)
|
||||
self.g.inventory_state_ids = self.g.get('inventory_state_ids') or {}
|
||||
self.g.inventory_partial = False
|
||||
self.g.cursor = Slot(present=False)
|
||||
register = self.g.connection.register_packet_listener
|
||||
register(self.handle_open, ContainerOpenPacket)
|
||||
register(self.handle_content, ContainerSetContentPacket)
|
||||
register(self.handle_slot, ContainerSetSlotPacket)
|
||||
register(self.handle_cursor, SetCursorItemPacket)
|
||||
|
||||
@staticmethod
|
||||
def to_slot(item):
|
||||
return Slot(item.present, item.item_id, item.item_count,
|
||||
components=item.components,
|
||||
component_ids=item.component_ids,
|
||||
removed_components=item.removed_components,
|
||||
components_unknown=item.components_unknown)
|
||||
|
||||
def handle_open(self, packet):
|
||||
self.g.window = Munch(
|
||||
window_id=packet.window_id,
|
||||
inventory_type=packet.inventory_type,
|
||||
title=packet.title,
|
||||
contents={},
|
||||
container_slots=0,
|
||||
state_id=self.g.inventory_state_ids.get(packet.window_id, 0),
|
||||
)
|
||||
|
||||
def handle_content(self, packet):
|
||||
slots = {index: self.to_slot(item)
|
||||
for index, item in enumerate(packet.items)}
|
||||
self.g.inventory_state_ids[packet.container_id] = packet.state_id
|
||||
if packet.container_id == 0:
|
||||
self.g.inv = slots
|
||||
self.g.inventory_partial = packet.partial
|
||||
self.g.cursor = self.to_slot(packet.carried_item)
|
||||
self._sync_held_item()
|
||||
elif (self.g.get('window') and
|
||||
packet.container_id == self.g.window.window_id):
|
||||
self.g.window.contents = slots
|
||||
# Player inventory contributes 36 slots to chest menus.
|
||||
self.g.window.container_slots = max(0, len(slots) - 36)
|
||||
self.g.window.state_id = packet.state_id
|
||||
self.g.cursor = self.to_slot(packet.carried_item)
|
||||
self.g.item_lock = False
|
||||
|
||||
def handle_slot(self, packet):
|
||||
self.g.inventory_state_ids[packet.container_id] = packet.state_id
|
||||
item = self.to_slot(packet.item)
|
||||
if packet.item.components_unknown:
|
||||
self.g.inventory_partial = True
|
||||
if packet.container_id == 0:
|
||||
self.g.inv[packet.slot] = item
|
||||
self.g.item_lock = False
|
||||
if (self.g.get('holding_hand', 0) == 0 and
|
||||
packet.slot == 36 + self.g.get('holding_slot', 0)):
|
||||
self.g.holding = item.item_id if item.present else 0
|
||||
elif packet.container_id == -1 and packet.slot == -1:
|
||||
self.g.cursor = item
|
||||
elif (self.g.get('window') and
|
||||
packet.container_id == self.g.window.window_id):
|
||||
self.g.window.contents[packet.slot] = item
|
||||
self.g.window.state_id = packet.state_id
|
||||
offset = packet.slot - self.g.window.container_slots
|
||||
if 0 <= offset < 27:
|
||||
self.g.inv[9 + offset] = item
|
||||
elif 27 <= offset < 36:
|
||||
self.g.inv[36 + offset - 27] = item
|
||||
self.g.item_lock = False
|
||||
|
||||
def _sync_held_item(self):
|
||||
if self.g.get('holding_hand', 0) != 0:
|
||||
return
|
||||
hotbar_slot = int(self.g.get('holding_slot', 0) or 0)
|
||||
item = self.g.inv.get(36 + hotbar_slot)
|
||||
self.g.holding = (item.item_id if item and
|
||||
getattr(item, 'present', False) else 0)
|
||||
|
||||
def handle_cursor(self, packet):
|
||||
if packet.item.components_unknown:
|
||||
self.g.inventory_partial = True
|
||||
self.g.cursor = self.to_slot(packet.item)
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
"""Chat adapter for the Minecraft 26.3 play protocol."""
|
||||
import re
|
||||
import time
|
||||
from contextlib import nullcontext
|
||||
|
||||
from minecraft.networking.packets import Packet
|
||||
from minecraft.networking.types import (
|
||||
Float, Long, UnsignedByte, VarInt, VarLong,
|
||||
)
|
||||
from minecraft.networking.modern import (
|
||||
ChatCommand, ClientboundPlayerChatPacket, ServerboundChatPacket, SystemChat,
|
||||
)
|
||||
|
||||
|
||||
class UpdateTimePacket(Packet):
|
||||
"""26.3 update-time packet with registry-indexed world clocks."""
|
||||
# The 26.1 Prismarine schema defines this payload; protocol 777's 26.3
|
||||
# clientbound table places it at 0x73 (0x71 is a different short packet).
|
||||
id = 0x73
|
||||
packet_name = 'update time'
|
||||
|
||||
def read(self, file_object):
|
||||
self.age = Long.read(file_object)
|
||||
self.clock_updates = []
|
||||
for _ in range(VarInt.read(file_object)):
|
||||
self.clock_updates.append({
|
||||
'clock_id': VarInt.read(file_object),
|
||||
'total_ticks': VarLong.read(file_object),
|
||||
'partial_tick': Float.read(file_object),
|
||||
'rate': Float.read(file_object),
|
||||
})
|
||||
|
||||
|
||||
class PlayerInputPacket(Packet):
|
||||
"""Serverbound key state, including sneak for container-safe placement."""
|
||||
id = 0x2B
|
||||
packet_name = 'player input'
|
||||
definition = [{'flags': UnsignedByte}]
|
||||
|
||||
|
||||
class PlayerCommandPacket(Packet):
|
||||
"""Client player-command packet; action 0 stops sleeping (protocol 777)."""
|
||||
id = 0x2A
|
||||
packet_name = 'player command'
|
||||
definition = [
|
||||
{'entity_id': VarInt}, {'action_id': VarInt}, {'jump_boost': VarInt},
|
||||
]
|
||||
|
||||
|
||||
class UseItemPacket(Packet):
|
||||
"""Use the selected hand, including the 26.3 interaction sequence."""
|
||||
id = 0x43
|
||||
packet_name = 'use item'
|
||||
definition = [
|
||||
{'hand': VarInt}, {'sequence': VarInt},
|
||||
{'yaw': Float}, {'pitch': Float},
|
||||
]
|
||||
|
||||
|
||||
class ClientCommandPacket(Packet):
|
||||
"""Client command; action 0 asks the server to respawn this player."""
|
||||
id = 0x0C
|
||||
packet_name = 'client command'
|
||||
definition = [{'action_id': VarInt}]
|
||||
|
||||
|
||||
def parse_incoming_private_message(message):
|
||||
"""Return (sender_name, body) for common Minecraft incoming-DM forms."""
|
||||
patterns = (
|
||||
r'^([A-Za-z0-9_]{1,16}) whispers(?: to you)?:\s*(.*)$',
|
||||
r'^([A-Za-z0-9_]{1,16})\s*->\s*me:\s*(.*)$',
|
||||
r'^From ([A-Za-z0-9_]{1,16}):\s*(.*)$',
|
||||
)
|
||||
for pattern in patterns:
|
||||
match = re.match(pattern, message, re.DOTALL)
|
||||
if match:
|
||||
return match.group(1), match.group(2)
|
||||
return None
|
||||
|
||||
|
||||
class ModernChatManager:
|
||||
def __init__(self, global_state):
|
||||
self.g = global_state
|
||||
self.handler = None
|
||||
self.g.connection.register_packet_listener(
|
||||
self.handle_player_chat, ClientboundPlayerChatPacket)
|
||||
|
||||
def set_handler(self, callback):
|
||||
self.handler = callback
|
||||
|
||||
def handle_player_chat(self, packet):
|
||||
sender = str(packet.sender)
|
||||
sender_name = self.g.get('player_names', {}).get(sender, sender)
|
||||
registry = getattr(self.g.connection, 'registry_ids', {})
|
||||
chat_types = registry.get('minecraft:chat_type', {})
|
||||
chat_type_id = getattr(packet, 'chat_type_id', None)
|
||||
chat_type = next((name for name, index in chat_types.items()
|
||||
if index == chat_type_id), None)
|
||||
is_dm = (
|
||||
getattr(packet, 'network_target_name_present', False) or
|
||||
chat_type in (
|
||||
'minecraft:msg_command_incoming',
|
||||
'minecraft:msg_command_outgoing',
|
||||
'minecraft:team_msg_command_incoming',
|
||||
'minecraft:team_msg_command_outgoing',
|
||||
)
|
||||
)
|
||||
label = '[DM] ' if is_dm else ''
|
||||
print('[chat] {}{}: {}'.format(label, sender_name, packet.message),
|
||||
flush=True)
|
||||
if self.handler:
|
||||
with self.g.get('reload_lock') or nullcontext():
|
||||
if is_dm:
|
||||
text = '{} -> me: {}'.format(sender_name, packet.message)
|
||||
self.handler(('DM', sender, text, sender_name))
|
||||
else:
|
||||
text = '{}: {}'.format(sender_name, packet.message)
|
||||
self.handler(('CHAT', sender, text))
|
||||
|
||||
def handle_system_chat(self, packet, message):
|
||||
incoming = parse_incoming_private_message(message)
|
||||
if incoming:
|
||||
sender_name, body = incoming
|
||||
print('[chat] [DM] {}: {}'.format(sender_name, body), flush=True)
|
||||
if self.handler:
|
||||
text = '{} -> me: {}'.format(sender_name, body)
|
||||
with self.g.get('reload_lock') or nullcontext():
|
||||
self.handler(('DM', sender_name, text, sender_name))
|
||||
return True
|
||||
|
||||
if self.handler:
|
||||
with self.g.get('reload_lock') or nullcontext():
|
||||
self.handler(('SYSTEM', None, message))
|
||||
return False
|
||||
|
||||
def send(self, message):
|
||||
if not message:
|
||||
return
|
||||
if message.startswith('/'):
|
||||
self.g.connection.write_packet(
|
||||
ChatCommand(command=message[1:]), force=True)
|
||||
else:
|
||||
packet = ServerboundChatPacket(
|
||||
message=message, timestamp=int(time.time() * 1000))
|
||||
self.g.connection.write_packet(packet, force=True)
|
||||
@@ -13,6 +13,17 @@ from .types import Nbt, Slot, Entry, Trade
|
||||
from mosfet.info import blocks
|
||||
|
||||
|
||||
class SetHealthPacket(Packet):
|
||||
"""Minecraft 26.3 (protocol 777) clientbound health/food update."""
|
||||
id = 0x6A
|
||||
packet_name = 'set health'
|
||||
definition = [
|
||||
{'health': Float},
|
||||
{'food': VarInt},
|
||||
{'food_saturation': Float},
|
||||
]
|
||||
|
||||
|
||||
class ChunkDataPacket(Packet):
|
||||
id = 0x20
|
||||
packet_name = 'chunk data'
|
||||
|
||||
@@ -103,11 +103,17 @@ class Nbt(Type):
|
||||
|
||||
|
||||
class Slot(Type):
|
||||
def __init__(self, present, item_id=None, item_count=None, nbt=None):
|
||||
def __init__(self, present, item_id=None, item_count=None, nbt=None,
|
||||
components=None, component_ids=None,
|
||||
removed_components=None, components_unknown=False):
|
||||
self.present = present
|
||||
self.item_id = item_id
|
||||
self.item_count = item_count
|
||||
self.nbt = nbt
|
||||
self.components = components or {}
|
||||
self.component_ids = component_ids or []
|
||||
self.removed_components = removed_components or []
|
||||
self.components_unknown = components_unknown
|
||||
|
||||
def __str__(self):
|
||||
return str(self.__dict__)
|
||||
|
||||
@@ -82,33 +82,48 @@ def diffrange(n):
|
||||
sign = 1 if n >= 0 else -1
|
||||
return range(0, n+sign, sign)
|
||||
|
||||
def break_time(block_id, held_item=0, in_water=False, on_ground=True, enchantments=[], effects={}):
|
||||
# from PrismarineJS/prismarine-block
|
||||
def break_time(block_id, held_item=0, in_water=False, on_ground=True,
|
||||
enchantments=None, effects=None):
|
||||
"""Return vanilla block-breaking duration rounded to whole game ticks."""
|
||||
held_item = str(held_item)
|
||||
block_data = blocks.get(block_id)
|
||||
hardness = block_data.get('hardness', 0)
|
||||
if hardness < 0:
|
||||
return float('inf')
|
||||
|
||||
can_harvest = 'harvestTools' not in block_data or str(held_item) in block_data['harvestTools']
|
||||
can_harvest = (
|
||||
'harvestTools' not in block_data or
|
||||
held_item in block_data['harvestTools'])
|
||||
material = block_data.get('material', 'n/a')
|
||||
tool_multipliers = mcdata.mcd.materials.get(material, [])
|
||||
is_best_tool = held_item in tool_multipliers
|
||||
time = block_data['hardness']
|
||||
tool_multipliers = mcdata.mcd.materials.get(material, {})
|
||||
speed = tool_multipliers.get(held_item, 1.0)
|
||||
|
||||
if can_harvest:
|
||||
time *= 1.5
|
||||
else:
|
||||
time *= 5.0
|
||||
enchantments = enchantments or {}
|
||||
if speed > 1:
|
||||
efficiency = int(enchantments.get(
|
||||
'efficiency', enchantments.get('minecraft:efficiency', 0)) or 0)
|
||||
if efficiency > 0:
|
||||
speed += efficiency * efficiency + 1
|
||||
|
||||
if is_best_tool:
|
||||
speed_multiplier = tool_multipliers[held_item]
|
||||
# TODO: calc efficiency, haste, mining fatigue
|
||||
else:
|
||||
speed_multiplier = 1.0
|
||||
effects = effects or {}
|
||||
haste = int(effects.get('haste', effects.get('minecraft:haste', 0)) or 0)
|
||||
if haste >= 0 and ('haste' in effects or 'minecraft:haste' in effects):
|
||||
speed *= 1 + 0.2 * (haste + 1)
|
||||
fatigue = int(effects.get(
|
||||
'mining_fatigue', effects.get('minecraft:mining_fatigue', -1)))
|
||||
if fatigue >= 0:
|
||||
speed *= (0.3, 0.09, 0.0027, 0.00081, 0.000243)[min(fatigue, 4)]
|
||||
|
||||
time /= speed_multiplier
|
||||
if in_water: time *= 5.0
|
||||
if not on_ground: time *= 5.0
|
||||
duration = hardness * (1.5 if can_harvest else 5.0) / speed
|
||||
if in_water:
|
||||
duration *= 5.0
|
||||
if not on_ground:
|
||||
duration *= 5.0
|
||||
|
||||
return time
|
||||
# Vanilla advances breaking progress in 1/20-second ticks; clients cannot
|
||||
# finish between ticks. Round up, while avoiding floating-point over-round.
|
||||
ticks = max(1, ceil(duration / TICK - 1e-9))
|
||||
return ticks * TICK
|
||||
|
||||
def search_2d(distance=0):
|
||||
def get_neighbors(x,y,z):
|
||||
|
||||
@@ -1,22 +1,325 @@
|
||||
import collections
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
import random
|
||||
from math import floor
|
||||
from itertools import count
|
||||
from copy import copy
|
||||
|
||||
from mosfet import utils
|
||||
from mosfet import path
|
||||
from mosfet.info import blocks
|
||||
from mosfet.info import items
|
||||
from mosfet.info import mobs
|
||||
from minecraft.networking.types import BlockFace
|
||||
|
||||
CHEST_OPENING_RADIUS = 3
|
||||
|
||||
|
||||
class World:
|
||||
def __init__(self, global_state):
|
||||
self.g = global_state
|
||||
self._bed_occupancy_states = {}
|
||||
|
||||
def block_at(self, x, y, z):
|
||||
return self.g.chunks.get_block_at(x, y, z)
|
||||
|
||||
@staticmethod
|
||||
def _is_sign_state(state_id):
|
||||
name = blocks.BLOCKS.get(state_id)
|
||||
return name is not None and name.endswith('_sign')
|
||||
|
||||
@staticmethod
|
||||
def _sign_component_text(value):
|
||||
if value is None:
|
||||
return ''
|
||||
if isinstance(value, str):
|
||||
stripped = value.strip()
|
||||
if stripped.startswith(('{', '[')):
|
||||
try:
|
||||
parsed = json.loads(stripped)
|
||||
except ValueError:
|
||||
return value
|
||||
if parsed != value:
|
||||
return World._sign_component_text(parsed)
|
||||
return value
|
||||
if isinstance(value, (list, tuple)):
|
||||
return ''.join(World._sign_component_text(part) for part in value)
|
||||
if isinstance(value, dict):
|
||||
text = value.get('text', '')
|
||||
if not text and value.get('translate'):
|
||||
text = value['translate']
|
||||
if isinstance(text, (dict, list)):
|
||||
text = World._sign_component_text(text)
|
||||
return (str(text) +
|
||||
World._sign_component_text(value.get('with', [])) +
|
||||
World._sign_component_text(value.get('extra', [])))
|
||||
return str(value)
|
||||
|
||||
def find_signs(self, center, distance=16):
|
||||
"""Return nearby loaded signs as position/side/four-lines records."""
|
||||
result = []
|
||||
chunks = self.g.chunks
|
||||
entities = (chunks.block_entities_snapshot()
|
||||
if hasattr(chunks, 'block_entities_snapshot') else
|
||||
dict(chunks.block_entities))
|
||||
for position, entity in entities.items():
|
||||
if utils.phyp(center, position) > distance:
|
||||
continue
|
||||
get_block_at = getattr(self.g.chunks, 'get_block_at', None)
|
||||
if callable(get_block_at):
|
||||
state_id = get_block_at(*position)
|
||||
if (state_id is not None and
|
||||
not self._is_sign_state(state_id)):
|
||||
continue
|
||||
data = entity.get('data') or {}
|
||||
for side in ('front', 'back'):
|
||||
text_data = data.get(side + '_text')
|
||||
if not isinstance(text_data, dict):
|
||||
continue
|
||||
messages = text_data.get('messages', [])
|
||||
lines = tuple(self._sign_component_text(line)
|
||||
for line in messages[:4])
|
||||
lines += ('',) * (4 - len(lines))
|
||||
if any(line.strip() for line in lines):
|
||||
result.append({
|
||||
'position': position, 'side': side, 'lines': lines,
|
||||
})
|
||||
if not any(key in data for key in ('front_text', 'back_text')):
|
||||
old_lines = tuple(self._sign_component_text(data.get(
|
||||
'Text{}'.format(index), '')) for index in range(1, 5))
|
||||
if any(line.strip() for line in old_lines):
|
||||
result.append({
|
||||
'position': position, 'side': 'front',
|
||||
'lines': old_lines,
|
||||
})
|
||||
result.sort(key=lambda sign: utils.phyp(center, sign['position']))
|
||||
return result
|
||||
|
||||
def _double_chest_positions(self, chest):
|
||||
state_id = self.block_at(*chest)
|
||||
properties = blocks.PROPS.get(state_id, {})
|
||||
chest_type = properties.get('type')
|
||||
if chest_type not in ('left', 'right'):
|
||||
return (tuple(chest),)
|
||||
|
||||
other_type = 'right' if chest_type == 'left' else 'left'
|
||||
for offset in ((1, 0, 0), (-1, 0, 0), (0, 0, 1), (0, 0, -1)):
|
||||
partner = utils.padd(chest, offset)
|
||||
other = blocks.PROPS.get(self.block_at(*partner), {})
|
||||
if (other.get('type') == other_type and
|
||||
other.get('facing') == properties.get('facing')):
|
||||
return tuple(sorted((tuple(chest), partner)))
|
||||
return (tuple(chest),)
|
||||
|
||||
def find_labeled_chests(self, center, distance=80):
|
||||
"""Find single/double chests assigned item categories by nearby signs."""
|
||||
grouped = {}
|
||||
sign_offsets = (
|
||||
(0, 0, 0), (0, -1, 0),
|
||||
(1, 0, 0), (-1, 0, 0), (0, 0, 1), (0, 0, -1),
|
||||
)
|
||||
for sign in self.find_signs(center, distance):
|
||||
categories = set()
|
||||
labels = set()
|
||||
for line in sign['lines']:
|
||||
item_ids = items.storage_item_ids_for_label(line)
|
||||
if item_ids:
|
||||
categories.update(item_ids)
|
||||
labels.add(line.strip())
|
||||
if not categories:
|
||||
continue
|
||||
|
||||
sign_pos = sign['position']
|
||||
adjacent = {
|
||||
utils.padd(sign_pos, offset)
|
||||
for offset in sign_offsets
|
||||
if self.block_at(*utils.padd(sign_pos, offset)) in blocks.CHEST_IDS
|
||||
}
|
||||
if not adjacent:
|
||||
nearby = self.find_blocks_indexed(
|
||||
sign_pos, blocks.CHEST_IDS, 2)
|
||||
if nearby:
|
||||
nearest = min(utils.phyp(sign_pos, chest)
|
||||
for chest in nearby)
|
||||
adjacent = {chest for chest in nearby
|
||||
if utils.phyp(sign_pos, chest) == nearest}
|
||||
|
||||
for chest in adjacent:
|
||||
positions = self._double_chest_positions(chest)
|
||||
record = grouped.setdefault(positions, {
|
||||
'position': tuple(chest),
|
||||
'positions': positions,
|
||||
'item_ids': set(),
|
||||
'labels': set(),
|
||||
'sign_positions': set(),
|
||||
})
|
||||
record['item_ids'].update(categories)
|
||||
record['labels'].update(labels)
|
||||
record['sign_positions'].add(sign_pos)
|
||||
|
||||
result = list(grouped.values())
|
||||
result.sort(key=lambda chest: utils.phyp(center, chest['position']))
|
||||
return result
|
||||
|
||||
def find_supply_chests(self, center, bot_name, distance=80):
|
||||
"""Find chests whose sign is addressed to this bot's supplies."""
|
||||
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)
|
||||
|
||||
grouped = {}
|
||||
sign_offsets = (
|
||||
(0, 0, 0), (0, -1, 0),
|
||||
(1, 0, 0), (-1, 0, 0), (0, 0, 1), (0, 0, -1),
|
||||
)
|
||||
for sign in self.find_signs(center, distance):
|
||||
text = ' '.join(line for line in sign['lines'] if line.strip())
|
||||
tokens = re.findall(r'[a-z0-9_]+', text.casefold())
|
||||
if (len(tokens) < 2 or tokens[0] not in addresses or
|
||||
'supplies' not in tokens[1:]):
|
||||
continue
|
||||
|
||||
sign_pos = sign['position']
|
||||
candidates = {
|
||||
utils.padd(sign_pos, offset)
|
||||
for offset in sign_offsets
|
||||
if self.block_at(*utils.padd(sign_pos, offset)) in blocks.CHEST_IDS
|
||||
}
|
||||
if not candidates:
|
||||
nearby = self.find_blocks_indexed(
|
||||
sign_pos, blocks.CHEST_IDS, 2)
|
||||
if nearby:
|
||||
nearest = min(utils.phyp(sign_pos, chest) for chest in nearby)
|
||||
candidates = {chest for chest in nearby
|
||||
if utils.phyp(sign_pos, chest) == nearest}
|
||||
|
||||
for chest in candidates:
|
||||
positions = self._double_chest_positions(chest)
|
||||
record = grouped.setdefault(positions, {
|
||||
'position': tuple(chest),
|
||||
'positions': positions,
|
||||
'labels': set(),
|
||||
'sign_positions': set(),
|
||||
})
|
||||
record['labels'].update(tokens[1:])
|
||||
record['sign_positions'].add(sign_pos)
|
||||
|
||||
result = list(grouped.values())
|
||||
result.sort(key=lambda chest: utils.phyp(center, chest['position']))
|
||||
return result
|
||||
|
||||
def sign_policies(self, bot_name, distance=64):
|
||||
"""Parse sign policies addressed to this bot or its numbered group."""
|
||||
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)
|
||||
|
||||
center = utils.pint(self.g.pos)
|
||||
policies = []
|
||||
active_sign_position = None
|
||||
for sign in self.find_signs(center, distance):
|
||||
lines = [line.strip() for line in sign['lines'] if line.strip()]
|
||||
if not lines:
|
||||
continue
|
||||
first = lines[0].split(maxsplit=1)
|
||||
address = first[0].rstrip(':,').casefold()
|
||||
if address not in addresses:
|
||||
continue
|
||||
directives = ([first[1]] if len(first) > 1 else []) + lines[1:]
|
||||
text = ' '.join(directives).casefold()
|
||||
sign_policies = []
|
||||
for match in re.finditer(
|
||||
r'\bstay\s+within\s*(\d+)(?:\s+(squares?|circle))?\b',
|
||||
text):
|
||||
shape = match.group(2) or 'circle'
|
||||
if shape == 'squares':
|
||||
shape = 'square'
|
||||
sign_policies.append({
|
||||
'position': sign['position'],
|
||||
'distance': int(match.group(1)),
|
||||
'shape': shape,
|
||||
'side': sign['side'],
|
||||
})
|
||||
if not sign_policies:
|
||||
continue
|
||||
if active_sign_position is None:
|
||||
# The nearest addressed policy sign overrides farther signs.
|
||||
active_sign_position = sign['position']
|
||||
if sign['position'] == active_sign_position:
|
||||
policies.extend(sign_policies)
|
||||
return policies
|
||||
|
||||
def _active_work_policies(self):
|
||||
job = self.g.get('job')
|
||||
machine = getattr(job, 'active_machine', None) if job else None
|
||||
if machine is None:
|
||||
return []
|
||||
support_machines = (
|
||||
'grab_supplies_states', 'sleep_with_bed_states',
|
||||
'eat_food_states', 'cache_items_states',
|
||||
'check_threats_states',
|
||||
)
|
||||
if any(machine is getattr(job, name, None)
|
||||
for name in support_machines):
|
||||
return []
|
||||
return self.sign_policies(self.g.get('name', ''))
|
||||
|
||||
@staticmethod
|
||||
def _sign_policy_distance(position, policy):
|
||||
# Work zones are horizontal; crop height or terrain elevation does not
|
||||
# consume the sign's radius.
|
||||
dx = abs(position[0] - policy['position'][0])
|
||||
dz = abs(position[2] - policy['position'][2])
|
||||
if policy['shape'] == 'square':
|
||||
return max(dx, dz)
|
||||
return utils.hypot(dx, dz)
|
||||
|
||||
@classmethod
|
||||
def _inside_sign_policy(cls, position, policy):
|
||||
return cls._sign_policy_distance(position, policy) <= policy['distance']
|
||||
|
||||
def work_position_allowed(self, position):
|
||||
"""Whether a work target satisfies all currently active sign rules."""
|
||||
return all(self._inside_sign_policy(position, policy)
|
||||
for policy in self._active_work_policies())
|
||||
|
||||
def filter_work_positions(self, positions):
|
||||
"""Filter a candidate set once against the active sign policies."""
|
||||
policies = self._active_work_policies()
|
||||
positions = list(positions)
|
||||
if not policies:
|
||||
return positions
|
||||
return [position for position in positions
|
||||
if all(self._inside_sign_policy(position, policy)
|
||||
for policy in policies)]
|
||||
|
||||
@classmethod
|
||||
def _path_allowed_by_sign(cls, points, policy):
|
||||
distances = [cls._sign_policy_distance(point, policy)
|
||||
for point in points]
|
||||
radius = policy['distance']
|
||||
if distances[0] <= radius:
|
||||
return all(distance <= radius for distance in distances)
|
||||
|
||||
# If the bot starts just outside a newly read boundary, let it return
|
||||
# without allowing it to travel farther away from that sign.
|
||||
start_distance = distances[0]
|
||||
entered = False
|
||||
for distance in distances[1:]:
|
||||
if distance > start_distance or (entered and distance > radius):
|
||||
return False
|
||||
if distance <= radius:
|
||||
entered = True
|
||||
return entered
|
||||
|
||||
def check_air_column(self, pos, distance):
|
||||
for i in range(distance):
|
||||
check = utils.padd(pos, (0, i, 0))
|
||||
@@ -49,12 +352,13 @@ class World:
|
||||
yield check
|
||||
|
||||
def find_blocks_indexed(self, center, block_ids, distance=0):
|
||||
print('finding', block_ids)
|
||||
index = []
|
||||
for bid in block_ids:
|
||||
index.extend(self.g.chunks.index.get(bid, []))
|
||||
|
||||
print('index', index)
|
||||
chunks = self.g.chunks
|
||||
if hasattr(chunks, 'indexed_positions'):
|
||||
index = chunks.indexed_positions(block_ids)
|
||||
else:
|
||||
index = []
|
||||
for bid in block_ids:
|
||||
index.extend(chunks.index.get(bid, []))
|
||||
|
||||
result = []
|
||||
for block in index:
|
||||
@@ -83,9 +387,14 @@ class World:
|
||||
return result
|
||||
|
||||
def find_trees(self, center, distance):
|
||||
found_trees = []
|
||||
for log in self.find_blocks_3d(center, blocks.LOG_IDS, distance, 15):
|
||||
# crawl to the bottom log
|
||||
found_trees = set()
|
||||
# 26.3 block-state caches keep an index of tree logs. Searching a
|
||||
# three-dimensional radius voxel-by-voxel is prohibitively expensive
|
||||
# and can walk through unloaded space, so use loaded indexed states.
|
||||
for candidate in self.find_blocks_indexed(
|
||||
center, blocks.LOG_IDS, distance):
|
||||
# Crawl to the bottom log of this trunk.
|
||||
log = candidate
|
||||
while self.block_at(*utils.padd(log, path.BLOCK_BELOW)) in blocks.LOG_IDS:
|
||||
log = utils.padd(log, path.BLOCK_BELOW)
|
||||
base = log
|
||||
@@ -93,27 +402,25 @@ class World:
|
||||
if base in found_trees:
|
||||
continue
|
||||
|
||||
# make sure we are on the ground
|
||||
if self.block_at(*utils.padd(base, path.BLOCK_BELOW)) in blocks.NON_SOLID_IDS:
|
||||
# Only classify trees when their supporting block is known.
|
||||
support = self.block_at(*utils.padd(base, path.BLOCK_BELOW))
|
||||
if support is None or support in blocks.NON_SOLID_IDS:
|
||||
continue
|
||||
|
||||
# crawl to the top log to count and check leaves
|
||||
# Crawl to the top log to count trunk blocks and check for leaves.
|
||||
log_count = 1
|
||||
good_leaves = False
|
||||
while self.block_at(*utils.padd(log, path.BLOCK_ABOVE)) in blocks.LOG_IDS:
|
||||
log = utils.padd(log, path.BLOCK_ABOVE)
|
||||
log_count += 1
|
||||
|
||||
for offset in path.CHECK_DIRECTIONS:
|
||||
if self.block_at(*utils.padd(log, offset)) in blocks.LEAF_IDS:
|
||||
good_leaves = True
|
||||
|
||||
# make sure it's a good tree
|
||||
if not good_leaves or log_count < 3:
|
||||
continue
|
||||
|
||||
found_trees.append(base)
|
||||
|
||||
found_trees.add(base)
|
||||
yield base
|
||||
|
||||
def find_tree_openings(self, tree):
|
||||
@@ -135,11 +442,23 @@ class World:
|
||||
maze_solver = path.Pathfinder(self.g)
|
||||
|
||||
try:
|
||||
s = maze_solver.astar(start, place)
|
||||
return list(s) if s else None
|
||||
solution = maze_solver.astar(start, place)
|
||||
if not solution:
|
||||
return None
|
||||
navpath = list(solution)
|
||||
except path.AStarTimeout:
|
||||
return None
|
||||
|
||||
policies = self._active_work_policies()
|
||||
points = [tuple(start)] + [tuple(point) for point in navpath]
|
||||
for policy in policies:
|
||||
if not self._path_allowed_by_sign(points, policy):
|
||||
print('[sign policy] rejected work path outside {}-block {} '
|
||||
'around {}'.format(policy['distance'], policy['shape'],
|
||||
policy['position']), flush=True)
|
||||
return None
|
||||
return navpath
|
||||
|
||||
def path_to_place_faked(self, start, place):
|
||||
# same as above, but adds a fake block below and air before pathfinding
|
||||
# so that the pathfinder can actually make it to the block
|
||||
@@ -161,31 +480,71 @@ class World:
|
||||
return navpath
|
||||
|
||||
def find_bed_areas(self, center, distance):
|
||||
bed_clearance = 9 # 5x5 area
|
||||
clear_distance = 2
|
||||
|
||||
for a in self.find_blocks_3d(center, [0], distance, 50):
|
||||
# check for air around the area
|
||||
if len(self.find_blocks(a, clear_distance, [0], bed_clearance)) < bed_clearance:
|
||||
"""Yield nearby two-block bed footprints on solid, safe ground."""
|
||||
# Only search loaded-neighborhood distance. The old 3-D flood fill
|
||||
# explored millions of air blocks and used overly broad 5x5 clearance.
|
||||
distance = min(distance, 32)
|
||||
headroom = path.BLOCK_ABOVE
|
||||
support = path.BLOCK_BELOW
|
||||
for offset in utils.search_2d(distance):
|
||||
if utils.hypot(offset[0], offset[2]) > distance:
|
||||
continue
|
||||
for dy in (0, 1, -1, 2, -2):
|
||||
area = (center[0] + offset[0], center[1] + dy,
|
||||
center[2] + offset[2])
|
||||
if area == center:
|
||||
continue
|
||||
if self.block_at(*area) != blocks.AIR:
|
||||
continue
|
||||
if self.block_at(*utils.padd(area, headroom)) != blocks.AIR:
|
||||
continue
|
||||
support_block = self.block_at(*utils.padd(area, support))
|
||||
if (support_block is None or
|
||||
support_block in blocks.NON_SOLID_IDS or
|
||||
support_block in blocks.AVOID_IDS):
|
||||
continue
|
||||
|
||||
# check for ground around the area
|
||||
if len(self.find_blocks(utils.padd(a, path.BLOCK_BELOW), clear_distance, blocks.NON_SOLID_IDS, bed_clearance)):
|
||||
continue
|
||||
footprint_found = False
|
||||
for direction in path.CHECK_DIRECTIONS:
|
||||
head = utils.padd(area, direction)
|
||||
if (self.block_at(*head) != blocks.AIR or
|
||||
self.block_at(*utils.padd(head, headroom)) != blocks.AIR):
|
||||
continue
|
||||
head_support = self.block_at(*utils.padd(head, support))
|
||||
if (head_support is None or
|
||||
head_support in blocks.NON_SOLID_IDS or
|
||||
head_support in blocks.AVOID_IDS):
|
||||
continue
|
||||
footprint_found = True
|
||||
break
|
||||
if not footprint_found:
|
||||
continue
|
||||
|
||||
# check for air above the area
|
||||
if len(self.find_blocks(utils.padd(a, path.BLOCK_ABOVE), clear_distance, [0], bed_clearance)) < bed_clearance:
|
||||
continue
|
||||
|
||||
# ensure there's no monsters within 20 blocks
|
||||
# can't sleep if they are within 10, good to have a buffer
|
||||
if self.find_monsters(a, 20):
|
||||
continue
|
||||
|
||||
yield a
|
||||
# Avoid placing a bed within range of nearby monsters.
|
||||
if self.find_monsters(area, 20):
|
||||
continue
|
||||
yield area
|
||||
|
||||
def find_cache_areas(self, center, distance):
|
||||
return self.find_bed_areas(center, distance)
|
||||
"""Yield nearby, supported air blocks suitable for placing a chest."""
|
||||
center = tuple(center)
|
||||
for offset in utils.search_2d(distance):
|
||||
if utils.hypot(offset[0], offset[2]) > distance:
|
||||
continue
|
||||
for dy in (0, 1, -1, 2, -2):
|
||||
area = (center[0] + offset[0], center[1] + dy,
|
||||
center[2] + offset[2])
|
||||
if area == center:
|
||||
continue
|
||||
if self.block_at(*area) != blocks.AIR:
|
||||
continue
|
||||
if self.block_at(*utils.padd(area, path.BLOCK_ABOVE)) != blocks.AIR:
|
||||
continue
|
||||
support = self.block_at(*utils.padd(area, path.BLOCK_BELOW))
|
||||
if (support is None or support in blocks.NON_SOLID_IDS or
|
||||
support in blocks.AVOID_IDS):
|
||||
continue
|
||||
yield area
|
||||
|
||||
def sand_adjacent_safe(self, sand):
|
||||
for direction in path.CHECK_DIRECTIONS:
|
||||
@@ -279,17 +638,202 @@ class World:
|
||||
return result
|
||||
|
||||
def check_bed_occupied(self, bed):
|
||||
# returns true if the bed is occupied by a player
|
||||
"""Return occupancy, logging only the first observation or a change."""
|
||||
bed = tuple(bed)
|
||||
bid = self.g.chunks.get_block_at(*bed)
|
||||
if blocks.PROPS[bid]['occupied'] == 'true':
|
||||
print('Checking bed occupancy:', bed, '-> occupied')
|
||||
return True
|
||||
else:
|
||||
print('Checking bed occupancy:', bed, '-> free')
|
||||
return False
|
||||
occupied = blocks.PROPS.get(bid, {}).get('occupied') == 'true'
|
||||
previous = self._bed_occupancy_states.get(bed)
|
||||
if previous is None or previous != occupied:
|
||||
print('Checking bed occupancy:', bed, '->',
|
||||
'occupied' if occupied else 'free')
|
||||
self._bed_occupancy_states[bed] = occupied
|
||||
return occupied
|
||||
|
||||
def find_cache_openings(self, area):
|
||||
return self.find_bed_openings(area)
|
||||
@staticmethod
|
||||
def _is_chest_state(state_id):
|
||||
name = blocks.BLOCKS.get(state_id)
|
||||
return (name is not None and name != 'ender_chest' and
|
||||
(name == 'chest' or name.endswith('_chest')))
|
||||
|
||||
def _cache_opening_standable(self, position):
|
||||
at_feet = self.block_at(*position)
|
||||
above = self.block_at(*utils.padd(position, path.BLOCK_ABOVE))
|
||||
below = self.block_at(*utils.padd(position, path.BLOCK_BELOW))
|
||||
return (at_feet in blocks.NON_SOLID_IDS and
|
||||
at_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)
|
||||
|
||||
@staticmethod
|
||||
def _segment_intersects_aabb(start, end, minimum, maximum):
|
||||
lower, upper = 0.0, 1.0
|
||||
for axis in range(3):
|
||||
origin = start[axis]
|
||||
delta = end[axis] - origin
|
||||
if abs(delta) < 1e-9:
|
||||
if origin < minimum[axis] or origin > maximum[axis]:
|
||||
return False
|
||||
continue
|
||||
first = (minimum[axis] - origin) / delta
|
||||
second = (maximum[axis] - origin) / delta
|
||||
if first > second:
|
||||
first, second = second, first
|
||||
lower = max(lower, first)
|
||||
upper = min(upper, second)
|
||||
if lower > upper:
|
||||
return False
|
||||
return upper >= 0.0 and lower <= 1.0
|
||||
|
||||
def _has_cache_line_of_sight(self, start, end, target):
|
||||
first = tuple(floor(min(start[i], end[i])) for i in range(3))
|
||||
last = tuple(floor(max(start[i], end[i])) for i in range(3))
|
||||
for x in range(first[0], last[0] + 1):
|
||||
for y in range(first[1], last[1] + 1):
|
||||
for z in range(first[2], last[2] + 1):
|
||||
position = (x, y, z)
|
||||
if position == target:
|
||||
continue
|
||||
if not self._segment_intersects_aabb(
|
||||
start, end, position, utils.padd(position, (1, 1, 1))):
|
||||
continue
|
||||
state_id = self.block_at(*position)
|
||||
if state_id is None:
|
||||
return False
|
||||
for box in blocks.COLLISION_BOXES.get(state_id, ()):
|
||||
minimum = (x + box[0], y + box[1], z + box[2])
|
||||
maximum = (x + box[3], y + box[4], z + box[5])
|
||||
if self._segment_intersects_aabb(
|
||||
start, end, minimum, maximum):
|
||||
return False
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def _chest_interaction_points(target, boxes):
|
||||
points = []
|
||||
for box in boxes:
|
||||
x0, y0, z0, x1, y1, z1 = box
|
||||
xm, zm = (x0 + x1) / 2, (z0 + z1) / 2
|
||||
for fraction in (0.2, 0.5, 0.8):
|
||||
y = y0 + (y1 - y0) * fraction
|
||||
points.extend((
|
||||
(target[0] + xm, target[1] + y, target[2] + z0),
|
||||
(target[0] + xm, target[1] + y, target[2] + z1),
|
||||
(target[0] + x0, target[1] + y, target[2] + zm),
|
||||
(target[0] + x1, target[1] + y, target[2] + zm),
|
||||
))
|
||||
for x_fraction, z_fraction in (
|
||||
(0.25, 0.25), (0.25, 0.75),
|
||||
(0.75, 0.25), (0.75, 0.75), (0.5, 0.5)):
|
||||
points.append((
|
||||
target[0] + x0 + (x1 - x0) * x_fraction,
|
||||
target[1] + y1,
|
||||
target[2] + z0 + (z1 - z0) * z_fraction,
|
||||
))
|
||||
return points
|
||||
|
||||
@staticmethod
|
||||
def _ray_chest_surface_hit(start, end, target, boxes):
|
||||
negative_faces = (BlockFace.WEST, BlockFace.BOTTOM, BlockFace.NORTH)
|
||||
positive_faces = (BlockFace.EAST, BlockFace.TOP, BlockFace.SOUTH)
|
||||
delta = tuple(end[i] - start[i] for i in range(3))
|
||||
hits = []
|
||||
for box in boxes:
|
||||
minimum = tuple(target[i] + box[i] for i in range(3))
|
||||
maximum = tuple(target[i] + box[i + 3] for i in range(3))
|
||||
enter, leave = float('-inf'), float('inf')
|
||||
entering_face = None
|
||||
for axis in range(3):
|
||||
if abs(delta[axis]) < 1e-9:
|
||||
if (start[axis] < minimum[axis] or
|
||||
start[axis] > maximum[axis]):
|
||||
break
|
||||
continue
|
||||
near = (minimum[axis] - start[axis]) / delta[axis]
|
||||
far = (maximum[axis] - start[axis]) / delta[axis]
|
||||
face = negative_faces[axis]
|
||||
if near > far:
|
||||
near, far = far, near
|
||||
face = positive_faces[axis]
|
||||
if near > enter:
|
||||
enter = near
|
||||
entering_face = face
|
||||
leave = min(leave, far)
|
||||
if enter > leave:
|
||||
break
|
||||
else:
|
||||
if entering_face is None or enter < 0 or enter > 1:
|
||||
continue
|
||||
hit_point = tuple(start[i] + delta[i] * enter
|
||||
for i in range(3))
|
||||
cursor = tuple(hit_point[i] - target[i] for i in range(3))
|
||||
hits.append((enter, entering_face, cursor, hit_point))
|
||||
if not hits:
|
||||
return None
|
||||
_distance, face, cursor, hit_point = min(hits, key=lambda hit: hit[0])
|
||||
return face, cursor, hit_point
|
||||
|
||||
def find_cache_openings(self, area, center=None, radius=None):
|
||||
"""Find standable nearby spots with a clear ray to a chest surface."""
|
||||
area = tuple(area)
|
||||
center = tuple(center if center is not None else area)
|
||||
radius = CHEST_OPENING_RADIUS if radius is None else radius
|
||||
state_id = self.block_at(*area)
|
||||
targets = (self._double_chest_positions(area)
|
||||
if self._is_chest_state(state_id) else (area,))
|
||||
default_chest = min(blocks.CHEST_IDS)
|
||||
interactions = {}
|
||||
|
||||
for target in targets:
|
||||
target_state = self.block_at(*target)
|
||||
boxes = blocks.COLLISION_BOXES.get(target_state) or \
|
||||
blocks.COLLISION_BOXES[default_chest]
|
||||
hit_points = self._chest_interaction_points(target, boxes)
|
||||
for horizontal in utils.search_2d(radius + 1):
|
||||
for dy in range(-radius - 1, radius + 2):
|
||||
offset = (horizontal[0], dy, horizontal[2])
|
||||
opening = utils.padd(target, offset)
|
||||
if (opening in targets or
|
||||
not self._cache_opening_standable(opening)):
|
||||
continue
|
||||
eye = (opening[0] + 0.5, opening[1] + 1.62,
|
||||
opening[2] + 0.5)
|
||||
for aim_point in hit_points:
|
||||
if not self._has_cache_line_of_sight(
|
||||
eye, aim_point, target):
|
||||
continue
|
||||
hit = self._ray_chest_surface_hit(
|
||||
eye, aim_point, target, boxes)
|
||||
if hit is None:
|
||||
continue
|
||||
face, cursor, hit_point = hit
|
||||
hit_distance = utils.phyp(eye, hit_point)
|
||||
if hit_distance > radius:
|
||||
continue
|
||||
interaction = {
|
||||
'position': opening,
|
||||
'target': target,
|
||||
'face': face,
|
||||
'cursor': cursor,
|
||||
'hit_point': hit_point,
|
||||
'look_at': tuple(value - 0.5
|
||||
for value in hit_point),
|
||||
}
|
||||
distance = utils.phyp(center, opening)
|
||||
interaction['distance'] = distance
|
||||
interaction['hit_distance'] = hit_distance
|
||||
previous = interactions.get(opening)
|
||||
if (previous is None or
|
||||
interaction['hit_distance'] <
|
||||
previous['hit_distance']):
|
||||
interactions[opening] = interaction
|
||||
break
|
||||
|
||||
return sorted(interactions.values(),
|
||||
key=lambda result: (result['distance'],
|
||||
result['position']))
|
||||
|
||||
def find_objects(self, object_ids):
|
||||
result = []
|
||||
|
||||
@@ -29,7 +29,7 @@ pep517==0.10.0
|
||||
pkg-resources==0.0.0
|
||||
progress==1.5
|
||||
pycparser==2.20
|
||||
git+https://github.com/ammaraskar/pyCraft.git@2813d02ae7fb8182c3e5227a73de2240b09878d9
|
||||
-e ../pyCraft
|
||||
PyNBT==3.1.0
|
||||
pyparsing==2.4.7
|
||||
pytoml==0.1.21
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -eu
|
||||
|
||||
if [ ! -d "mosfet" ]
|
||||
then
|
||||
echo "You must run this from the mosfet-minecraft-bot directory."
|
||||
exit
|
||||
fi
|
||||
|
||||
if ! command -v virtualenv &> /dev/null
|
||||
then
|
||||
echo "virtualenv could not be found, please install with:"
|
||||
echo "sudo apt install virtualenv"
|
||||
exit
|
||||
fi
|
||||
|
||||
if ! command -v wget &> /dev/null
|
||||
then
|
||||
echo "wget could not be found, please install with:"
|
||||
echo "sudo apt install wget"
|
||||
exit
|
||||
fi
|
||||
|
||||
if ! command -v unzip &> /dev/null
|
||||
then
|
||||
echo "unzip could not be found, please install with:"
|
||||
echo "sudo apt install unzip"
|
||||
exit
|
||||
fi
|
||||
|
||||
if ! command -v python3 &> /dev/null
|
||||
then
|
||||
echo "python3 could not be found, please install with:"
|
||||
echo "sudo apt install python3"
|
||||
exit
|
||||
fi
|
||||
|
||||
if ! command -v pip3 &> /dev/null
|
||||
then
|
||||
echo "pip3 could not be found, please install with:"
|
||||
echo "sudo apt install pip3"
|
||||
exit
|
||||
fi
|
||||
|
||||
|
||||
# download minecraft data
|
||||
|
||||
if [ ! -d "minecraft_data" ]
|
||||
then
|
||||
echo "Grabbing minecraft data..."
|
||||
|
||||
VERSION="1.16.4"
|
||||
|
||||
wget -Omcdata.zip "https://apimon.de/mcdata/$VERSION/$VERSION.zip"
|
||||
mkdir minecraft_data
|
||||
unzip mcdata.zip -d minecraft_data
|
||||
rm mcdata.zip
|
||||
fi
|
||||
|
||||
# https://github.com/pypa/virtualenv/issues/1029
|
||||
PS1=${PS1:-}
|
||||
|
||||
# create virtual environment
|
||||
|
||||
if [ ! -d "env" ]
|
||||
then
|
||||
echo "Installing Python requirements..."
|
||||
|
||||
virtualenv -p python3 env
|
||||
source env/bin/activate
|
||||
pip install -r requirements.txt
|
||||
else
|
||||
source env/bin/activate
|
||||
fi
|
||||
|
||||
echo "Running bot..."
|
||||
|
||||
python main.py
|
||||
@@ -0,0 +1,78 @@
|
||||
import io
|
||||
import time
|
||||
import unittest
|
||||
from munch import Munch
|
||||
|
||||
from minecraft.networking.modern import (
|
||||
ClientTickEnd, EntityAnimationPacket, EntitySwingAnimationPacket,
|
||||
PunchPacket,
|
||||
)
|
||||
from mosfet.game import Game
|
||||
|
||||
|
||||
class RecordingConnection:
|
||||
def __init__(self):
|
||||
self.packets = []
|
||||
|
||||
def write_packet(self, packet, force=False):
|
||||
self.packets.append((packet, force))
|
||||
|
||||
|
||||
class BlockBreakAnimationTests(unittest.TestCase):
|
||||
def make_game(self):
|
||||
connection = RecordingConnection()
|
||||
game = object.__new__(Game)
|
||||
game.g = Munch(connection=connection, inv={}, inventory_state_ids={})
|
||||
game.sequence = 0
|
||||
game.break_deadline = None
|
||||
game.breaking_state = None
|
||||
game.next_swing_at = 0.0
|
||||
return game, connection
|
||||
|
||||
def test_26_3_punch_packet_is_the_empty_serverbound_packet(self):
|
||||
self.assertEqual(PunchPacket.id, 0x2E)
|
||||
self.assertEqual(PunchPacket.definition, [])
|
||||
|
||||
def test_observer_packet_decodes_entity_id_and_swing_kind(self):
|
||||
packet = EntityAnimationPacket()
|
||||
packet.read(io.BytesIO(bytes((0x85, 0x01, 0))))
|
||||
self.assertEqual(packet.entity_id, 133)
|
||||
self.assertEqual(packet.animation, 0)
|
||||
|
||||
def test_26_3_observer_swing_packet_decodes_animation_details(self):
|
||||
packet = EntitySwingAnimationPacket()
|
||||
packet.read(io.BytesIO(bytes((0x85, 0x01, 0, 1, 6))))
|
||||
self.assertEqual(EntitySwingAnimationPacket.id, 0x7B)
|
||||
self.assertEqual((packet.entity_id, packet.hand,
|
||||
packet.animation_type, packet.duration),
|
||||
(133, 0, 1, 6))
|
||||
|
||||
def test_animate_sends_punch_before_client_tick_end(self):
|
||||
game, connection = self.make_game()
|
||||
game.animate()
|
||||
self.assertEqual([type(packet) for packet, _ in connection.packets],
|
||||
[PunchPacket, ClientTickEnd])
|
||||
self.assertTrue(all(force for _, force in connection.packets))
|
||||
|
||||
def test_breaking_sends_initial_and_periodic_punches(self):
|
||||
game, connection = self.make_game()
|
||||
game.g.breaking = (1, 2, 3)
|
||||
game.break_deadline = time.monotonic() + 5
|
||||
game.breaking_state = 10
|
||||
game.next_swing_at = 0
|
||||
|
||||
game.tick()
|
||||
self.assertEqual(sum(isinstance(packet, PunchPacket)
|
||||
for packet, _ in connection.packets), 1)
|
||||
sent = len(connection.packets)
|
||||
game.tick()
|
||||
self.assertEqual(len(connection.packets), sent)
|
||||
|
||||
game.next_swing_at = 0
|
||||
game.tick()
|
||||
self.assertEqual(sum(isinstance(packet, PunchPacket)
|
||||
for packet, _ in connection.packets), 2)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,69 @@
|
||||
import math
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
from munch import Munch
|
||||
|
||||
from mosfet import utils
|
||||
from mosfet.game import Game
|
||||
from mosfet.info import blocks, items
|
||||
|
||||
|
||||
class BlockBreakTimingTests(unittest.TestCase):
|
||||
def test_leaf_time_uses_actual_tool_speed_and_game_ticks(self):
|
||||
oak_leaves = blocks.MCD_BLOCKS['oak_leaves']['minStateId']
|
||||
oak_log = items.get_id('oak_log')
|
||||
wooden_hoe = items.get_id('wooden_hoe')
|
||||
|
||||
self.assertAlmostEqual(utils.break_time(oak_leaves, oak_log), 0.3)
|
||||
self.assertAlmostEqual(utils.break_time(oak_leaves, wooden_hoe), 0.15)
|
||||
self.assertAlmostEqual(
|
||||
utils.break_time(oak_leaves, oak_log, in_water=True), 1.5)
|
||||
self.assertAlmostEqual(
|
||||
utils.break_time(oak_leaves, oak_log, on_ground=False), 1.5)
|
||||
|
||||
def test_efficiency_haste_and_fatigue_affect_break_ticks(self):
|
||||
oak_leaves = blocks.MCD_BLOCKS['oak_leaves']['minStateId']
|
||||
wooden_hoe = items.get_id('wooden_hoe')
|
||||
self.assertAlmostEqual(utils.break_time(
|
||||
oak_leaves, wooden_hoe, enchantments={'efficiency': 1}), 0.1)
|
||||
self.assertAlmostEqual(utils.break_time(
|
||||
oak_leaves, wooden_hoe, effects={'haste': 0}), 0.15)
|
||||
self.assertAlmostEqual(utils.break_time(
|
||||
oak_leaves, wooden_hoe,
|
||||
effects={'mining_fatigue': 0}), 0.5)
|
||||
|
||||
def test_unbreakable_blocks_have_no_completion_deadline(self):
|
||||
bedrock = blocks.MCD_BLOCKS['bedrock']['minStateId']
|
||||
self.assertTrue(math.isinf(utils.break_time(bedrock)))
|
||||
|
||||
def test_game_sends_finish_after_calculated_tick_duration(self):
|
||||
class RecordingConnection:
|
||||
def __init__(self):
|
||||
self.packets = []
|
||||
|
||||
def write_packet(self, packet, force=False):
|
||||
self.packets.append(packet)
|
||||
|
||||
class FakeChunks:
|
||||
@staticmethod
|
||||
def get_block_at(*_position):
|
||||
return blocks.MCD_BLOCKS['oak_leaves']['minStateId']
|
||||
|
||||
connection = RecordingConnection()
|
||||
game = object.__new__(Game)
|
||||
game.g = Munch(
|
||||
connection=connection, chunks=FakeChunks(), inv={},
|
||||
holding=items.get_id('oak_log'), holding_hand=0,
|
||||
holding_slot=0)
|
||||
game.sequence = 0
|
||||
game.break_deadline = None
|
||||
game.breaking_state = None
|
||||
game.next_swing_at = 0.0
|
||||
|
||||
with patch('mosfet.game.time.monotonic', return_value=100.0):
|
||||
self.assertTrue(game.break_block((0, 64, 0)))
|
||||
self.assertAlmostEqual(game.break_deadline, 100.3)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,316 @@
|
||||
import io
|
||||
import unittest
|
||||
from contextlib import redirect_stdout
|
||||
from munch import Munch
|
||||
|
||||
from minecraft.networking.types import BlockFace
|
||||
|
||||
from mosfet.info import items
|
||||
from mosfet.jobs.cache_items import CacheItemsStates
|
||||
|
||||
|
||||
class CacheItemsTests(unittest.TestCase):
|
||||
def test_chest_search_log_distinguishes_labeled_and_trapped_counts(self):
|
||||
class FakeWorld:
|
||||
@staticmethod
|
||||
def find_labeled_chests(*_args):
|
||||
return [{} for _ in range(11)]
|
||||
|
||||
@staticmethod
|
||||
def find_blocks_indexed(*_args):
|
||||
return []
|
||||
|
||||
state = CacheItemsStates(Munch(
|
||||
world=FakeWorld(), pos=(0, 64, 0)))
|
||||
output = io.StringIO()
|
||||
with redirect_stdout(output):
|
||||
state.find_trapped_chests()
|
||||
|
||||
self.assertIn(
|
||||
'Found 11 labeled chests; found 0 trapped chests: []',
|
||||
output.getvalue())
|
||||
|
||||
def test_wanted_single_stack_is_not_considered_transferable(self):
|
||||
wanted_id = items.WHEAT_SEEDS_ID
|
||||
old_wanted = items.WANTED_ITEMS
|
||||
items.WANTED_ITEMS = set(old_wanted) | {wanted_id}
|
||||
try:
|
||||
state = CacheItemsStates(Munch(inv={
|
||||
9: Munch(present=True, item_id=wanted_id, item_count=56),
|
||||
}))
|
||||
self.assertFalse(state._has_transferable_item({wanted_id}))
|
||||
|
||||
state.g.inv[10] = Munch(
|
||||
present=True, item_id=wanted_id, item_count=12)
|
||||
self.assertTrue(state._has_transferable_item({wanted_id}))
|
||||
finally:
|
||||
items.WANTED_ITEMS = old_wanted
|
||||
|
||||
def test_post_sleep_halves_threshold_only_with_compatible_nearby_chest(self):
|
||||
bed = (0, 64, 0)
|
||||
chest_position = (5, 64, 0)
|
||||
item_id = items.get_id('stone')
|
||||
|
||||
class FakeGame:
|
||||
@staticmethod
|
||||
def count_inventory_slots():
|
||||
return 14
|
||||
|
||||
class NearbyWorld:
|
||||
@staticmethod
|
||||
def find_labeled_chests(_center, _distance):
|
||||
return [{
|
||||
'position': chest_position,
|
||||
'positions': (chest_position,),
|
||||
'item_ids': {item_id},
|
||||
}]
|
||||
|
||||
g = Munch(
|
||||
game=FakeGame(), world=NearbyWorld(),
|
||||
minimum_cache_slots=27, post_sleep_cache_bed=bed,
|
||||
inv={9: Munch(present=True, item_id=item_id, item_count=64)})
|
||||
state = CacheItemsStates(g)
|
||||
|
||||
state.init()
|
||||
|
||||
self.assertIs(state.state.__func__, state.find_trapped_chests.__func__)
|
||||
self.assertNotIn('post_sleep_cache_bed', g)
|
||||
|
||||
def test_post_sleep_threshold_rounds_27_up_to_14(self):
|
||||
bed = (0, 64, 0)
|
||||
item_id = items.get_id('stone')
|
||||
|
||||
class FakeGame:
|
||||
@staticmethod
|
||||
def count_inventory_slots():
|
||||
return 13
|
||||
|
||||
class NearbyWorld:
|
||||
@staticmethod
|
||||
def find_labeled_chests(_center, _distance):
|
||||
return [{
|
||||
'position': (5, 64, 0),
|
||||
'positions': ((5, 64, 0),),
|
||||
'item_ids': {item_id},
|
||||
}]
|
||||
|
||||
g = Munch(
|
||||
game=FakeGame(), world=NearbyWorld(), minimum_cache_slots=27,
|
||||
post_sleep_cache_bed=bed,
|
||||
inv={9: Munch(present=True, item_id=item_id, item_count=64)})
|
||||
state = CacheItemsStates(g)
|
||||
|
||||
state.init()
|
||||
|
||||
self.assertIs(state.state.__func__, state.cleanup.__func__)
|
||||
|
||||
def test_post_sleep_does_not_lower_threshold_without_compatible_nearby_chest(self):
|
||||
class FakeGame:
|
||||
@staticmethod
|
||||
def count_inventory_slots():
|
||||
return 14
|
||||
|
||||
class EmptyWorld:
|
||||
@staticmethod
|
||||
def find_labeled_chests(_center, _distance):
|
||||
return []
|
||||
|
||||
g = Munch(
|
||||
game=FakeGame(), world=EmptyWorld(), minimum_cache_slots=27,
|
||||
post_sleep_cache_bed=(0, 64, 0), inv={})
|
||||
state = CacheItemsStates(g)
|
||||
|
||||
state.init()
|
||||
|
||||
self.assertIs(state.state.__func__, state.cleanup.__func__)
|
||||
self.assertNotIn('post_sleep_cache_bed', g)
|
||||
|
||||
def test_post_sleep_ignores_compatible_chest_beyond_16_blocks(self):
|
||||
item_id = items.get_id('stone')
|
||||
|
||||
class FakeGame:
|
||||
@staticmethod
|
||||
def count_inventory_slots():
|
||||
return 14
|
||||
|
||||
class FarWorld:
|
||||
@staticmethod
|
||||
def find_labeled_chests(_center, _distance):
|
||||
position = (17, 64, 0)
|
||||
return [{
|
||||
'position': position,
|
||||
'positions': (position,),
|
||||
'item_ids': {item_id},
|
||||
}]
|
||||
|
||||
state = CacheItemsStates(Munch(
|
||||
game=FakeGame(), world=FarWorld(), minimum_cache_slots=27,
|
||||
post_sleep_cache_bed=(0, 64, 0),
|
||||
inv={9: Munch(present=True, item_id=item_id, item_count=64)}))
|
||||
|
||||
state.init()
|
||||
|
||||
self.assertIs(state.state.__func__, state.cleanup.__func__)
|
||||
|
||||
def test_manual_cache_threshold_override_is_consumed_once(self):
|
||||
class FakeGame:
|
||||
@staticmethod
|
||||
def count_inventory_slots():
|
||||
return 5
|
||||
|
||||
state = CacheItemsStates(Munch(
|
||||
game=FakeGame(), minimum_cache_slots=27))
|
||||
state.minimum = 0
|
||||
|
||||
state.init()
|
||||
self.assertIs(state.state.__func__, state.find_trapped_chests.__func__)
|
||||
self.assertNotIn('minimum', state.__dict__)
|
||||
|
||||
state.init()
|
||||
self.assertIs(state.state.__func__, state.cleanup.__func__)
|
||||
|
||||
def test_successful_labeled_transfer_skips_placing_another_cache_chest(self):
|
||||
item_id = items.get_id('stone')
|
||||
stack = Munch(present=True, item_id=item_id, item_count=16)
|
||||
window = Munch(container_slots=27, contents={
|
||||
**dict.fromkeys(range(27)), 27: stack,
|
||||
})
|
||||
clicks = []
|
||||
|
||||
class FakeGame:
|
||||
@staticmethod
|
||||
def count_window_slots():
|
||||
return 0
|
||||
|
||||
@staticmethod
|
||||
def click_window(*args):
|
||||
clicks.append(args)
|
||||
|
||||
class FakeWorld:
|
||||
@staticmethod
|
||||
def find_blocks_indexed(*_args):
|
||||
return []
|
||||
|
||||
@staticmethod
|
||||
def find_labeled_chests(*_args):
|
||||
return []
|
||||
|
||||
g = Munch(
|
||||
game=FakeGame(), world=FakeWorld(), pos=(0, 64, 0),
|
||||
inv={}, window=window, item_lock=False)
|
||||
state = CacheItemsStates(g)
|
||||
state.is_labeled_container = True
|
||||
state.container_item_ids = {item_id}
|
||||
|
||||
state.move_items()
|
||||
self.assertEqual(len(clicks), 1)
|
||||
self.assertFalse(state.transferred_to_labeled_chest)
|
||||
|
||||
window.contents[27] = Munch(present=False, item_id=0, item_count=0)
|
||||
g.item_lock = False
|
||||
state.pending_transfer['confirm_after'] = 0
|
||||
state.move_items()
|
||||
self.assertTrue(state.transferred_to_labeled_chest)
|
||||
|
||||
state.labeled_chests = []
|
||||
state.trapped_chests = []
|
||||
state.choose_trapped_chest()
|
||||
self.assertIs(state.state.__func__, state.cleanup.__func__)
|
||||
|
||||
def test_mutually_reachable_opening_is_skipped_after_path_failure(self):
|
||||
start = (0, 64, 0)
|
||||
first = (4, 64, 0)
|
||||
nearby = (4, 64, 1)
|
||||
item_id = items.get_id('stone')
|
||||
calls = []
|
||||
|
||||
class FakeWorld:
|
||||
@staticmethod
|
||||
def find_cache_openings(area, _center):
|
||||
position = first if area == (10, 64, 0) else nearby
|
||||
return [{'position': position}]
|
||||
|
||||
def path_to_place(self, origin, target):
|
||||
origin, target = tuple(origin), tuple(target)
|
||||
calls.append((origin, target))
|
||||
if origin == start and target == first:
|
||||
return None
|
||||
if (origin, target) in ((nearby, first), (first, nearby)):
|
||||
return [origin, target]
|
||||
return None
|
||||
|
||||
state = CacheItemsStates(Munch(
|
||||
world=FakeWorld(), pos=start,
|
||||
inv={9: Munch(present=True, item_id=item_id)}))
|
||||
state.labeled_chests = [
|
||||
{'position': (10, 64, 0), 'positions': ((10, 64, 0),),
|
||||
'item_ids': {item_id}, 'labels': {'Stone'}},
|
||||
{'position': (11, 64, 0), 'positions': ((11, 64, 0),),
|
||||
'item_ids': {item_id}, 'labels': {'Stone'}},
|
||||
]
|
||||
state.trapped_chests = []
|
||||
state.choose_trapped_chest()
|
||||
|
||||
self.assertEqual(calls, [
|
||||
(start, first), (nearby, first), (first, nearby),
|
||||
])
|
||||
self.assertIn(first, state.bad_openings)
|
||||
self.assertIn(nearby, state.bad_openings)
|
||||
|
||||
def test_one_way_reachability_does_not_blacklist_opening(self):
|
||||
bad = (1, 64, 0)
|
||||
candidate = (2, 64, 0)
|
||||
|
||||
class FakeWorld:
|
||||
@staticmethod
|
||||
def path_to_place(start, target):
|
||||
return [start, target] if tuple(start) == candidate else None
|
||||
|
||||
state = CacheItemsStates(Munch())
|
||||
state.bad_openings = {bad}
|
||||
|
||||
self.assertFalse(state._opening_in_bad_region(FakeWorld(), candidate))
|
||||
self.assertNotIn(candidate, state.bad_openings)
|
||||
|
||||
def test_cache_travel_looks_along_path_then_turns_to_chest(self):
|
||||
opening = (5, 64, 8)
|
||||
chest_look = (4.9, 64.1, 7.8)
|
||||
state = CacheItemsStates(Munch(
|
||||
pos=(2.5, 64, 2.5), look_at=(1, 64, 1)))
|
||||
state.opening = opening
|
||||
state.open_interaction = {'look_at': chest_look}
|
||||
|
||||
state.going_to_trapped_chest()
|
||||
self.assertIsNone(state.g.look_at)
|
||||
|
||||
state.g.pos = opening
|
||||
state.going_to_trapped_chest()
|
||||
self.assertEqual(state.g.look_at, chest_look)
|
||||
self.assertIs(state.state.__func__, state.turn_to_trapped_chest.__func__)
|
||||
|
||||
state.g.pos = (2.5, 64, 2.5)
|
||||
state.g.look_at = (1, 64, 1)
|
||||
state.going_to_area()
|
||||
self.assertIsNone(state.g.look_at)
|
||||
|
||||
def test_cache_chest_placement_sneaks_to_avoid_opening_support_container(self):
|
||||
calls = []
|
||||
|
||||
class FakeGame:
|
||||
@staticmethod
|
||||
def place_block(*args, **kwargs):
|
||||
calls.append((args, kwargs))
|
||||
|
||||
state = CacheItemsStates(Munch(game=FakeGame()))
|
||||
state.area = (3, 65, 7)
|
||||
|
||||
state.place_chest()
|
||||
|
||||
self.assertEqual(calls, [(
|
||||
((3, 64, 7), BlockFace.TOP), {'sneaking': True},
|
||||
)])
|
||||
self.assertIs(state.state.__func__, state.open_chest.__func__)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,88 @@
|
||||
import unittest
|
||||
from munch import Munch
|
||||
|
||||
from minecraft.networking.types import BlockFace
|
||||
|
||||
from mosfet.info import blocks
|
||||
from mosfet.world import CHEST_OPENING_RADIUS, World
|
||||
|
||||
|
||||
class FakeChunks:
|
||||
def __init__(self, states):
|
||||
self.states = states
|
||||
|
||||
def get_block_at(self, x, y, z):
|
||||
return self.states.get((x, y, z), blocks.AIR)
|
||||
|
||||
|
||||
class CacheOpeningTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.chest = (0, 64, 0)
|
||||
chest_state = min(blocks.CHEST_IDS)
|
||||
stone = blocks.STONE
|
||||
states = {self.chest: chest_state}
|
||||
for x in range(-4, 5):
|
||||
for z in range(-4, 5):
|
||||
states[(x, 63, z)] = stone
|
||||
self.world = World(Munch(chunks=FakeChunks(states)))
|
||||
|
||||
def test_openings_include_visible_positions_up_to_configured_radius(self):
|
||||
opening = (3, 64, 0)
|
||||
openings = self.world.find_cache_openings(
|
||||
self.chest, center=(3, 64, 0))
|
||||
by_position = {tuple(candidate['position']): candidate
|
||||
for candidate in openings}
|
||||
|
||||
self.assertEqual(CHEST_OPENING_RADIUS, 3)
|
||||
self.assertIn(opening, by_position)
|
||||
self.assertTrue(all(candidate['hit_distance'] <= CHEST_OPENING_RADIUS
|
||||
for candidate in openings))
|
||||
self.assertIn(by_position[opening]['face'], (
|
||||
BlockFace.NORTH, BlockFace.SOUTH, BlockFace.WEST,
|
||||
BlockFace.EAST, BlockFace.TOP,
|
||||
))
|
||||
self.assertEqual(len(by_position[opening]['cursor']), 3)
|
||||
|
||||
def test_range_is_measured_from_eye_to_interaction_surface(self):
|
||||
opening = (3, 63, 0)
|
||||
self.world.g.chunks.states[opening] = blocks.AIR
|
||||
self.world.g.chunks.states[(3, 62, 0)] = blocks.STONE
|
||||
|
||||
openings = self.world.find_cache_openings(
|
||||
self.chest, center=opening)
|
||||
by_position = {tuple(candidate['position']): candidate
|
||||
for candidate in openings}
|
||||
|
||||
self.assertIn(opening, by_position)
|
||||
self.assertLessEqual(by_position[opening]['hit_distance'], 3)
|
||||
|
||||
def test_sign_collision_shape_does_not_block_sight_but_solid_block_does(self):
|
||||
start = (3.5, 65.62, 0.5)
|
||||
target = (0.5, 64.875, 0.5)
|
||||
sign_state = blocks.MCD_BLOCKS['oak_sign']['minStateId']
|
||||
obstruction = (1, 65, 0)
|
||||
self.world.g.chunks.states[obstruction] = sign_state
|
||||
|
||||
self.assertTrue(self.world._has_cache_line_of_sight(
|
||||
start, target, self.chest))
|
||||
|
||||
self.world.g.chunks.states[obstruction] = blocks.STONE
|
||||
self.assertFalse(self.world._has_cache_line_of_sight(
|
||||
start, target, self.chest))
|
||||
|
||||
def test_virtual_chest_openings_are_found_before_placement(self):
|
||||
target = (0, 65, 0)
|
||||
for x in range(-3, 4):
|
||||
for z in range(-3, 4):
|
||||
self.world.g.chunks.states[(x, 64, z)] = blocks.STONE
|
||||
|
||||
openings = self.world.find_cache_openings(
|
||||
target, center=(3, 65, 0))
|
||||
|
||||
self.assertTrue(openings)
|
||||
self.assertTrue(all(candidate['target'] == target
|
||||
for candidate in openings))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,109 @@
|
||||
import time
|
||||
import unittest
|
||||
from munch import Munch
|
||||
|
||||
from minecraft.networking.modern import BlockEventPacket
|
||||
from mosfet.game import Game
|
||||
from mosfet.protocol.managers import ChestOpenManager
|
||||
|
||||
|
||||
class FakeConnection:
|
||||
def __init__(self):
|
||||
self.registry_ids = {'minecraft:block': {
|
||||
'minecraft:stone': 1,
|
||||
'minecraft:chest': 2,
|
||||
'minecraft:trapped_chest': 3,
|
||||
}}
|
||||
self.listeners = []
|
||||
|
||||
def register_packet_listener(self, handler, packet_type):
|
||||
self.listeners.append((handler, packet_type))
|
||||
|
||||
|
||||
class ChestDetectionTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.connection = FakeConnection()
|
||||
self.g = Munch(connection=self.connection)
|
||||
self.manager = ChestOpenManager(self.g)
|
||||
self.position = (12, 64, -7)
|
||||
|
||||
def event(self, block_id=2, action=1, viewers=1, position=None):
|
||||
x, y, z = position or self.position
|
||||
return Munch(
|
||||
location=Munch(x=x, y=y, z=z),
|
||||
block_id=block_id, action=action, parameter=viewers,
|
||||
)
|
||||
|
||||
def test_registers_block_event_packet_and_records_other_player_open(self):
|
||||
self.assertIn((self.manager.handle_block_event, BlockEventPacket),
|
||||
self.connection.listeners)
|
||||
|
||||
self.manager.handle_block_event(self.event(viewers=1))
|
||||
|
||||
self.assertEqual(self.g.chest_viewers[self.position], 1)
|
||||
self.assertEqual(self.g.last_chest_opened_by_other['position'],
|
||||
self.position)
|
||||
self.assertEqual(self.g.last_chest_opened_by_other['block'], 'chest')
|
||||
self.assertEqual(len(self.g.chest_open_events), 1)
|
||||
|
||||
def test_bot_open_is_not_misreported_but_later_viewer_is(self):
|
||||
self.g.pending_chest_open = {
|
||||
'position': self.position,
|
||||
'requested_at': time.monotonic(),
|
||||
}
|
||||
self.manager.handle_block_event(self.event(viewers=1))
|
||||
|
||||
self.assertIsNone(self.g.last_chest_opened_by_other)
|
||||
self.assertIsNotNone(self.g.pending_chest_open)
|
||||
|
||||
self.manager.handle_block_event(self.event(viewers=2))
|
||||
self.assertEqual(self.g.last_chest_opened_by_other['viewers'], 2)
|
||||
self.assertEqual(self.g.last_chest_opened_by_other['previous_viewers'], 1)
|
||||
|
||||
def test_bot_open_of_either_double_chest_half_is_not_misreported(self):
|
||||
other_half = (13, 64, -7)
|
||||
self.g.pending_chest_open = {
|
||||
'position': self.position,
|
||||
'positions': (self.position, other_half),
|
||||
'requested_at': time.monotonic(),
|
||||
}
|
||||
|
||||
self.manager.handle_block_event(
|
||||
self.event(position=other_half, viewers=1))
|
||||
|
||||
self.assertIsNone(self.g.last_chest_opened_by_other)
|
||||
self.assertIsNotNone(self.g.pending_chest_open)
|
||||
self.assertEqual(self.g.chest_viewers[other_half], 1)
|
||||
|
||||
def test_ignores_non_chests_and_tracks_close(self):
|
||||
self.manager.handle_block_event(self.event(block_id=1, viewers=1))
|
||||
self.assertIsNone(self.g.last_chest_opened_by_other)
|
||||
|
||||
self.manager.handle_block_event(self.event(viewers=1))
|
||||
self.manager.handle_block_event(self.event(viewers=0))
|
||||
|
||||
self.assertNotIn(self.position, self.g.chest_viewers)
|
||||
self.assertEqual(len(self.g.chest_open_events), 1)
|
||||
|
||||
def test_open_container_marks_bot_initiated_chest_open(self):
|
||||
sent = []
|
||||
game = Game.__new__(Game)
|
||||
other_half = (12, 64, -8)
|
||||
game.g = Munch(
|
||||
chunks=Munch(get_block_at=lambda *_position: None),
|
||||
world=Munch(_double_chest_positions=lambda _position:
|
||||
(self.position,)))
|
||||
game.place_block = lambda location, face, **kwargs: sent.append(
|
||||
(location, face, kwargs))
|
||||
|
||||
game.open_container(self.position)
|
||||
|
||||
self.assertEqual(sent[0][0], self.position)
|
||||
self.assertEqual(game.g.pending_chest_open['position'], self.position)
|
||||
self.assertIn(self.position, game.g.pending_chest_open['positions'])
|
||||
self.assertIn(other_half, game.g.pending_chest_open['positions'])
|
||||
self.assertIsInstance(game.g.pending_chest_open['requested_at'], float)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,37 @@
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
from munch import Munch
|
||||
|
||||
from mosfet.jobs.clear_leaves import ClearLeavesStates
|
||||
|
||||
|
||||
class ClearLeavesTests(unittest.TestCase):
|
||||
def test_spaces_leaf_breaks_at_configured_interval(self):
|
||||
class FakeGame:
|
||||
def __init__(self):
|
||||
self.broken = []
|
||||
|
||||
def break_block(self, location):
|
||||
self.broken.append(location)
|
||||
return True
|
||||
|
||||
game = FakeGame()
|
||||
state = ClearLeavesStates(Munch(
|
||||
breaking=False, game=game, look_at=None))
|
||||
state.leaves = [(0, 64, 0), (1, 64, 0)]
|
||||
|
||||
with patch('mosfet.jobs.clear_leaves.time.monotonic', return_value=10):
|
||||
state.break_leaves()
|
||||
self.assertEqual(game.broken, [(0, 64, 0)])
|
||||
|
||||
with patch('mosfet.jobs.clear_leaves.time.monotonic', return_value=10.59):
|
||||
state.break_leaves()
|
||||
self.assertEqual(game.broken, [(0, 64, 0)])
|
||||
|
||||
with patch('mosfet.jobs.clear_leaves.time.monotonic', return_value=10.6):
|
||||
state.break_leaves()
|
||||
self.assertEqual(game.broken, [(0, 64, 0), (1, 64, 0)])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,52 @@
|
||||
import unittest
|
||||
from munch import Munch
|
||||
|
||||
from mosfet.info import blocks
|
||||
from mosfet.jobs.gather_crop import GatherCropStates
|
||||
|
||||
|
||||
class CropBatchTests(unittest.TestCase):
|
||||
def test_navigation_looks_at_the_crop_target(self):
|
||||
crop = (5, 64, 8)
|
||||
|
||||
class FakeWorld:
|
||||
@staticmethod
|
||||
def path_to_place(_start, _target):
|
||||
return [(1, 64, 1), crop]
|
||||
|
||||
g = Munch(world=FakeWorld(), pos=(1, 64, 1), path=[], look_at=None)
|
||||
state = GatherCropStates(g)
|
||||
state.crop = crop
|
||||
|
||||
state.nav_to_crop()
|
||||
|
||||
self.assertEqual(g.look_at, crop)
|
||||
self.assertEqual(g.path[-1], crop)
|
||||
|
||||
def test_gather_crop_finishes_after_sixteen_successful_replants(self):
|
||||
unripe_wheat = blocks.MCD_BLOCKS['wheat']['minStateId']
|
||||
mature_wheat = blocks.MATURE_WHEAT_ID
|
||||
self.assertNotEqual(unripe_wheat, mature_wheat)
|
||||
|
||||
class FakeWorld:
|
||||
@staticmethod
|
||||
def block_at(*_position):
|
||||
return unripe_wheat
|
||||
|
||||
state = GatherCropStates(Munch(world=FakeWorld()))
|
||||
state.crop = (1, 64, 1)
|
||||
state.type_id = mature_wheat
|
||||
|
||||
for completed in range(1, state.CROPS_PER_BATCH):
|
||||
state.wait_place()
|
||||
self.assertEqual(state.completed_crops, completed)
|
||||
self.assertIs(state.state.__func__, state.find_new_crop.__func__)
|
||||
state.state = state.wait_place
|
||||
|
||||
state.wait_place()
|
||||
self.assertEqual(state.completed_crops, 0)
|
||||
self.assertIs(state.state.__func__, state.cleanup.__func__)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,40 @@
|
||||
import unittest
|
||||
|
||||
from munch import Munch
|
||||
|
||||
from mosfet.info import items
|
||||
from mosfet.job import JobStates
|
||||
|
||||
|
||||
class TestCropCaching(unittest.TestCase):
|
||||
def test_crop_farm_runs_silent_cache_machine_and_keeps_seeds(self):
|
||||
old_wanted = items.WANTED_ITEMS
|
||||
supply_state = object()
|
||||
crop_state = object()
|
||||
cache_state = Munch(silent=False)
|
||||
sleep_state = Munch(silent=False)
|
||||
eat_state = object()
|
||||
jobs = JobStates.__new__(JobStates)
|
||||
jobs.grab_supplies_states = supply_state
|
||||
jobs.gather_crop_states = crop_state
|
||||
jobs.cache_items_states = cache_state
|
||||
jobs.sleep_with_bed_states = sleep_state
|
||||
jobs.eat_food_states = eat_state
|
||||
|
||||
try:
|
||||
machines = JobStates.farm_crop(jobs)
|
||||
self.assertEqual(
|
||||
machines, [supply_state, crop_state, sleep_state,
|
||||
eat_state, cache_state])
|
||||
self.assertTrue(cache_state.silent)
|
||||
self.assertTrue(sleep_state.silent)
|
||||
self.assertTrue({
|
||||
items.CARROT_ID, items.POTATO_ID,
|
||||
items.WHEAT_SEEDS_ID, items.BEETROOT_SEEDS_ID,
|
||||
}.issubset(items.WANTED_ITEMS))
|
||||
finally:
|
||||
items.WANTED_ITEMS = old_wanted
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,85 @@
|
||||
import unittest
|
||||
|
||||
from munch import Munch
|
||||
|
||||
from mosfet.jobs.gather_crop import GatherCropStates
|
||||
|
||||
|
||||
class TestCropSectionPriority(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.job = GatherCropStates(Munch())
|
||||
self.job.bad_crops = []
|
||||
|
||||
def test_stays_in_active_patch_before_switching(self):
|
||||
wheat_a = (0, 64, 0)
|
||||
wheat_b = (1, 64, 0)
|
||||
carrot_a = (10, 64, 0)
|
||||
crop_types = {
|
||||
wheat_a: 'wheat',
|
||||
wheat_b: 'wheat',
|
||||
carrot_a: 'carrots',
|
||||
(10, 64, 1): 'carrots',
|
||||
(10, 64, -1): 'carrots',
|
||||
(11, 64, 0): 'carrots',
|
||||
}
|
||||
|
||||
first, first_size = self.job._select_crop(
|
||||
[wheat_a, carrot_a], crop_types, (0, 64, 0))
|
||||
self.assertEqual(first, wheat_a)
|
||||
self.assertEqual(first_size, 2)
|
||||
self.job.init()
|
||||
self.assertEqual(self.job.active_section_anchor, wheat_a)
|
||||
|
||||
# The carrot patch is now closer, but the bot should finish the wheat
|
||||
# patch it already selected first.
|
||||
next_crop, next_size = self.job._select_crop(
|
||||
[wheat_b, carrot_a], crop_types, (10, 64, 0))
|
||||
self.assertEqual(next_crop, wheat_b)
|
||||
self.assertEqual(next_size, 2)
|
||||
|
||||
# Once the active patch has no mature candidates, move to the next one.
|
||||
next_patch, next_patch_size = self.job._select_crop(
|
||||
[carrot_a], crop_types, (10, 64, 0))
|
||||
self.assertEqual(next_patch, carrot_a)
|
||||
self.assertEqual(next_patch_size, 4)
|
||||
|
||||
def test_farther_section_wins_when_much_more_mature(self):
|
||||
near_patch = {
|
||||
(3, 64, 0), (2, 64, 0), (1, 64, 0), (0, 64, 0),
|
||||
(3, 64, 1), (2, 64, 1), (1, 64, 1), (0, 64, 1),
|
||||
(3, 64, 2), (2, 64, 2),
|
||||
}
|
||||
near_mature = (3, 64, 0)
|
||||
far_patch = {
|
||||
(4, 64, 0), (5, 64, 0), (4, 64, 1), (5, 64, 1),
|
||||
}
|
||||
crop_types = {position: 'wheat' for position in near_patch}
|
||||
crop_types.update({position: 'carrots' for position in far_patch})
|
||||
|
||||
crop, size = self.job._select_crop(
|
||||
[near_mature, *far_patch], crop_types, (0, 64, 0))
|
||||
|
||||
self.assertEqual(crop, (4, 64, 0))
|
||||
self.assertEqual(size, len(far_patch))
|
||||
self.assertEqual(self.job.active_section_maturity, (4, 4))
|
||||
|
||||
def test_unripe_same_species_blocks_keep_patch_connected(self):
|
||||
mature = (0, 64, 0)
|
||||
replanted = (1, 64, 0)
|
||||
isolated = (4, 64, 0)
|
||||
crop_types = {
|
||||
mature: 'wheat',
|
||||
replanted: 'wheat',
|
||||
isolated: 'wheat',
|
||||
}
|
||||
|
||||
crop, size = self.job._select_crop([mature, isolated], crop_types,
|
||||
(0, 64, 0))
|
||||
|
||||
self.assertEqual(crop, mature)
|
||||
self.assertEqual(size, 2)
|
||||
self.assertEqual(self.job.active_section_anchor, mature)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,184 @@
|
||||
import unittest
|
||||
from munch import Munch
|
||||
|
||||
from mosfet.game import Game
|
||||
from mosfet.info import blocks
|
||||
from mosfet.path import Pathfinder
|
||||
|
||||
|
||||
class FakeChunks:
|
||||
def __init__(self, states):
|
||||
self.states = states
|
||||
|
||||
def get_block_at(self, *position):
|
||||
return self.states.get(tuple(position))
|
||||
|
||||
|
||||
class DoorNavigationTests(unittest.TestCase):
|
||||
@staticmethod
|
||||
def door_state(name, half='lower', opened=False, powered=False):
|
||||
data = blocks.MCD_BLOCKS[name]
|
||||
return next(
|
||||
state for state in range(data['minStateId'], data['maxStateId'] + 1)
|
||||
if blocks.PROPS[state].get('half') == half and
|
||||
blocks.PROPS[state].get('open') == str(opened).lower() and
|
||||
blocks.PROPS[state].get('powered') == str(powered).lower())
|
||||
|
||||
def test_pathfinder_treats_openable_doors_as_passable_but_not_iron(self):
|
||||
wooden = self.door_state('oak_door')
|
||||
iron = self.door_state('iron_door')
|
||||
opened_iron = self.door_state('iron_door', opened=True)
|
||||
positions = {(1, 64, 0): wooden, (2, 64, 0): iron,
|
||||
(3, 64, 0): opened_iron}
|
||||
g = Munch(chunks=FakeChunks(positions), crawling=False,
|
||||
unopenable_doors=set())
|
||||
finder = Pathfinder(g)
|
||||
|
||||
self.assertTrue(finder.bair((1, 64, 0)))
|
||||
self.assertFalse(finder.bair((2, 64, 0)))
|
||||
self.assertTrue(finder.bair((3, 64, 0)))
|
||||
|
||||
g.unopenable_doors.add((1, 64, 0))
|
||||
finder = Pathfinder(g)
|
||||
self.assertFalse(finder.bair((1, 64, 0)))
|
||||
|
||||
def test_pressure_plate_opened_door_is_not_toggled_or_closed(self):
|
||||
door = (1, 64, 0)
|
||||
after = (2, 64, 0)
|
||||
closed = self.door_state('oak_door', powered=True)
|
||||
opened = self.door_state('oak_door', opened=True, powered=True)
|
||||
states = {door: closed}
|
||||
|
||||
class FakeWorld:
|
||||
@staticmethod
|
||||
def block_at(*position):
|
||||
return states.get(tuple(position))
|
||||
|
||||
toggles = []
|
||||
game = Game.__new__(Game)
|
||||
game.g = Munch(
|
||||
world=FakeWorld(), pos=(0.5, 64, 0.5), yaw=-90.0,
|
||||
path=[door, after], unopenable_doors=set(), look_at=None)
|
||||
game.door_navigation = None
|
||||
game._toggle_door = lambda position, state: toggles.append(
|
||||
(position, state))
|
||||
|
||||
self.assertTrue(game.handle_path_doors())
|
||||
states[door] = opened # the bot steps on a pressure plate
|
||||
self.assertFalse(game.handle_path_doors())
|
||||
self.assertEqual(game.door_navigation['phase'], 'crossing')
|
||||
self.assertFalse(game.door_navigation['opened_by_bot'])
|
||||
|
||||
game.g.pos = (2.5, 64, 0.5)
|
||||
self.assertTrue(game.handle_path_doors())
|
||||
self.assertEqual(game.door_navigation['phase'], 'turning_to_close')
|
||||
game.door_navigation['deadline'] = 0
|
||||
self.assertTrue(game.handle_path_doors())
|
||||
self.assertEqual(game.door_navigation['phase'], 'turning_back')
|
||||
self.assertEqual(toggles, [])
|
||||
|
||||
states[door] = closed
|
||||
game.door_navigation['deadline'] = 0
|
||||
self.assertFalse(game.handle_path_doors())
|
||||
self.assertIsNone(game.door_navigation)
|
||||
|
||||
def test_powered_door_is_left_to_pressure_plate_after_crossing(self):
|
||||
door = (1, 64, 0)
|
||||
after = (2, 64, 0)
|
||||
closed = self.door_state('oak_door', powered=False)
|
||||
powered_open = self.door_state('oak_door', opened=True, powered=True)
|
||||
released_closed = self.door_state('oak_door', powered=False)
|
||||
states = {door: closed}
|
||||
|
||||
class FakeWorld:
|
||||
@staticmethod
|
||||
def block_at(*position):
|
||||
return states.get(tuple(position))
|
||||
|
||||
toggles = []
|
||||
game = Game.__new__(Game)
|
||||
game.g = Munch(
|
||||
world=FakeWorld(), pos=(0.5, 64, 0.5), yaw=-90.0,
|
||||
path=[door, after], unopenable_doors=set(), look_at=None)
|
||||
game.door_navigation = None
|
||||
game._toggle_door = lambda position, state: toggles.append(
|
||||
(position, state))
|
||||
|
||||
game.handle_path_doors()
|
||||
game.door_navigation['deadline'] = 0
|
||||
game.handle_path_doors()
|
||||
states[door] = powered_open
|
||||
game.handle_path_doors()
|
||||
game.g.pos = (2.5, 64, 0.5)
|
||||
self.assertTrue(game.handle_path_doors())
|
||||
self.assertEqual(game.door_navigation['phase'], 'turning_to_close')
|
||||
game.door_navigation['deadline'] = 0
|
||||
self.assertTrue(game.handle_path_doors())
|
||||
self.assertEqual(game.door_navigation['phase'], 'turning_back')
|
||||
self.assertEqual(toggles, [(door, closed)])
|
||||
|
||||
states[door] = released_closed
|
||||
game.door_navigation['deadline'] = 0
|
||||
self.assertFalse(game.handle_path_doors())
|
||||
self.assertIsNone(game.door_navigation)
|
||||
|
||||
def test_opens_door_before_crossing_and_closes_it_after(self):
|
||||
door = (1, 64, 0)
|
||||
after = (2, 64, 0)
|
||||
closed = self.door_state('oak_door', powered=False)
|
||||
opened = self.door_state('oak_door', opened=True, powered=False)
|
||||
states = {door: closed}
|
||||
|
||||
class FakeWorld:
|
||||
@staticmethod
|
||||
def block_at(*position):
|
||||
return states.get(tuple(position))
|
||||
|
||||
@staticmethod
|
||||
def path_to_place(_start, _goal):
|
||||
return None
|
||||
|
||||
toggles = []
|
||||
game = Game.__new__(Game)
|
||||
game.g = Munch(
|
||||
world=FakeWorld(), pos=(0.5, 64, 0.5), yaw=-90.0,
|
||||
path=[door, after], unopenable_doors=set(), look_at=None)
|
||||
game.door_navigation = None
|
||||
game._toggle_door = lambda position, state: toggles.append(
|
||||
(position, state))
|
||||
|
||||
self.assertTrue(game.handle_path_doors())
|
||||
self.assertEqual(game.door_navigation['phase'], 'checking')
|
||||
self.assertEqual(toggles, [])
|
||||
|
||||
game.door_navigation['deadline'] = 0
|
||||
self.assertTrue(game.handle_path_doors())
|
||||
self.assertEqual(game.door_navigation['phase'], 'opening')
|
||||
self.assertEqual(toggles, [(door, closed)])
|
||||
|
||||
states[door] = opened
|
||||
self.assertFalse(game.handle_path_doors())
|
||||
self.assertEqual(game.door_navigation['phase'], 'crossing')
|
||||
|
||||
game.g.pos = (2.5, 64, 0.5)
|
||||
self.assertTrue(game.handle_path_doors())
|
||||
self.assertEqual(game.door_navigation['phase'], 'turning_to_close')
|
||||
self.assertEqual(game.g.look_at, door)
|
||||
self.assertEqual(len(toggles), 1)
|
||||
|
||||
game.door_navigation['deadline'] = 0
|
||||
self.assertTrue(game.handle_path_doors())
|
||||
self.assertEqual(game.door_navigation['phase'], 'closing')
|
||||
self.assertEqual(toggles[-1], (door, opened))
|
||||
|
||||
states[door] = closed
|
||||
self.assertTrue(game.handle_path_doors())
|
||||
self.assertEqual(game.door_navigation['phase'], 'turning_back')
|
||||
self.assertEqual(game.g.look_at, (4, 64, 0))
|
||||
game.door_navigation['deadline'] = 0
|
||||
self.assertFalse(game.handle_path_doors())
|
||||
self.assertIsNone(game.door_navigation)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,99 @@
|
||||
import unittest
|
||||
|
||||
from munch import Munch
|
||||
from minecraft.networking.modern import ClientTickEnd
|
||||
from minecraft.networking.packets import PacketBuffer
|
||||
|
||||
from mosfet.game import Game
|
||||
from mosfet.info import items
|
||||
from mosfet.jobs.eat_food import EatFoodStates
|
||||
from mosfet.protocol.modern import UseItemPacket
|
||||
from mosfet.protocol.types import Slot
|
||||
|
||||
|
||||
class FakeConnection:
|
||||
def __init__(self):
|
||||
self.packets = []
|
||||
|
||||
def write_packet(self, packet, force=False):
|
||||
self.packets.append((packet, force))
|
||||
|
||||
|
||||
class FakeGame:
|
||||
def __init__(self, state):
|
||||
self.state = state
|
||||
self.used_hands = []
|
||||
|
||||
def select_item(self, item_ids):
|
||||
for slot, item in self.state.g.inv.items():
|
||||
if item.present and item.item_id in item_ids:
|
||||
self.state.g.holding = item.item_id
|
||||
self.state.g.holding_hand = 0
|
||||
self.state.g.holding_slot = slot - 36
|
||||
return True
|
||||
return False
|
||||
|
||||
def use_item(self, hand=0):
|
||||
self.used_hands.append(hand)
|
||||
|
||||
|
||||
class TestEatFood(unittest.TestCase):
|
||||
def test_use_item_packet_encodes_hand_sequence_and_rotation(self):
|
||||
packet = UseItemPacket(hand=1, sequence=300, yaw=90.0, pitch=-30.0)
|
||||
buffer = PacketBuffer()
|
||||
packet.write_fields(buffer)
|
||||
self.assertEqual(packet.id, 0x43)
|
||||
self.assertEqual(buffer.get_writable(), bytes.fromhex(
|
||||
'01ac0242b40000c1f00000'))
|
||||
|
||||
def test_game_use_item_sends_packet_and_tick_end(self):
|
||||
connection = FakeConnection()
|
||||
game = Game.__new__(Game)
|
||||
game.g = Munch(connection=connection, yaw=45.0, pitch=-5.0)
|
||||
game.sequence = 0
|
||||
|
||||
game.use_item(1)
|
||||
|
||||
packet, forced = connection.packets[0]
|
||||
self.assertIsInstance(packet, UseItemPacket)
|
||||
self.assertEqual((packet.hand, packet.sequence,
|
||||
packet.yaw, packet.pitch), (1, 1, 45.0, -5.0))
|
||||
self.assertTrue(forced)
|
||||
self.assertIsInstance(connection.packets[1][0], ClientTickEnd)
|
||||
|
||||
def test_eat_uses_authoritative_hunger_and_waits_for_confirmation(self):
|
||||
food_id = next(iter(items.FOOD_IDS))
|
||||
state = EatFoodStates(Munch(
|
||||
food=8, health=20.0, food_saturation=0.0,
|
||||
inv={36: Slot(True, food_id, 3)}, holding_hand=0,
|
||||
holding_slot=0, job=None))
|
||||
fake_game = FakeGame(state)
|
||||
state.g.game = fake_game
|
||||
|
||||
state.init()
|
||||
self.assertEqual(state.state, state.select_food)
|
||||
state.select_food()
|
||||
self.assertEqual(state.state, state.wait_for_selection)
|
||||
state.wait_for_selection()
|
||||
self.assertEqual(state.state, state.eat_food)
|
||||
state.eat_food()
|
||||
self.assertEqual(fake_game.used_hands, [0])
|
||||
self.assertEqual(state.state, state.wait)
|
||||
|
||||
# Don't declare success until the server sends a hunger/saturation
|
||||
# update or confirms that it consumed the selected stack.
|
||||
state.wait()
|
||||
self.assertEqual(state.state, state.wait)
|
||||
state.g.food = 16
|
||||
state.g.food_saturation = 4.0
|
||||
state.wait()
|
||||
self.assertEqual(state.state, state.cleanup)
|
||||
|
||||
def test_no_hunger_packet_does_not_eat(self):
|
||||
state = EatFoodStates(Munch(food=None, health=None))
|
||||
state.init()
|
||||
self.assertEqual(state.state, state.cleanup)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,90 @@
|
||||
import unittest
|
||||
|
||||
from munch import Munch
|
||||
|
||||
from mosfet.bot import (
|
||||
look_direction_from_eye, navigation_look_target, update_pitch,
|
||||
update_yaw,
|
||||
)
|
||||
from mosfet.vector import Point3D, Vector3D
|
||||
|
||||
|
||||
class LookDirection:
|
||||
def __init__(self, angle):
|
||||
self.angle = angle
|
||||
|
||||
def length(self):
|
||||
return 2.0
|
||||
|
||||
def normalized(self):
|
||||
return self
|
||||
|
||||
def angleDeg(self, _direction):
|
||||
return self.angle
|
||||
|
||||
|
||||
class TestFarmingPitch(unittest.TestCase):
|
||||
def test_aiming_at_a_same_level_crop_uses_eye_height_and_looks_down(self):
|
||||
player = Point3D((0.5, 64.0, 0.5))
|
||||
crop_center = Point3D((1.5, 64.5, 1.5))
|
||||
direction = look_direction_from_eye(player, crop_center)
|
||||
|
||||
self.assertGreater(direction.y, 0)
|
||||
state = Munch(pitch=0.0)
|
||||
update_pitch(state, direction)
|
||||
self.assertGreater(state.pitch, 0.0)
|
||||
|
||||
def test_pitch_never_looks_more_than_45_degrees_down(self):
|
||||
state = Munch(pitch=0.0)
|
||||
directly_below = LookDirection(0.0)
|
||||
for _ in range(8):
|
||||
update_pitch(state, directly_below)
|
||||
self.assertEqual(state.pitch, 45.0)
|
||||
|
||||
def test_fixed_yaw_turn_returns_over_the_same_180_degree_arc(self):
|
||||
state = Munch(yaw=-90.0)
|
||||
no_look_direction = Vector3D((0.0, 0.0, 0.0))
|
||||
|
||||
for _ in range(6):
|
||||
update_yaw(state, no_look_direction, fixed_target=-270.0)
|
||||
self.assertEqual(state.yaw, -270.0)
|
||||
|
||||
for _ in range(6):
|
||||
update_yaw(state, no_look_direction, fixed_target=-90.0)
|
||||
self.assertEqual(state.yaw, -90.0)
|
||||
|
||||
def test_yaw_turns_across_wrap_without_unbounded_rotation(self):
|
||||
state = Munch(yaw=630.0)
|
||||
update_yaw(state, Vector3D((0, 0, -1)))
|
||||
|
||||
self.assertEqual(state.yaw, -60.0)
|
||||
self.assertGreaterEqual(state.yaw, -180.0)
|
||||
self.assertLess(state.yaw, 180.0)
|
||||
|
||||
def test_path_navigation_looks_at_the_block_above_its_waypoint(self):
|
||||
path = [(index, 64, 0) for index in range(6)]
|
||||
|
||||
target = navigation_look_target(path)
|
||||
|
||||
self.assertEqual(target.tuple(), (4, 65, 0))
|
||||
self.assertEqual(navigation_look_target([(1, 64, 2)]).tuple(),
|
||||
(1, 65, 2))
|
||||
self.assertIsNone(navigation_look_target([]))
|
||||
|
||||
def test_pitch_tracks_look_target_instead_of_a_fixed_farming_angle(self):
|
||||
state = Munch(pitch=0.0)
|
||||
direction_to_crop = LookDirection(45.0)
|
||||
for _ in range(5):
|
||||
update_pitch(state, direction_to_crop)
|
||||
self.assertEqual(state.pitch, 45.0)
|
||||
|
||||
# Looking level at another target pulls the pitch back toward zero.
|
||||
update_pitch(state, LookDirection(90.0))
|
||||
self.assertEqual(state.pitch, 35.0)
|
||||
|
||||
update_pitch(state, None)
|
||||
self.assertEqual(state.pitch, 25.0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,183 @@
|
||||
import unittest
|
||||
from munch import Munch
|
||||
|
||||
from mosfet.commands import Commands
|
||||
from mosfet.info import blocks, items
|
||||
from mosfet.job import JobStates
|
||||
from mosfet.jobs.gather_wart import GatherWartStates
|
||||
|
||||
|
||||
class GatherWartTests(unittest.TestCase):
|
||||
def test_nether_wart_states_are_indexed_for_patch_search(self):
|
||||
self.assertTrue(blocks.NETHERWART_IDS.issubset(blocks.INDEXED_IDS))
|
||||
|
||||
def test_farm_wart_command_is_enabled_and_keeps_job_sequence(self):
|
||||
old_wanted = items.WANTED_ITEMS
|
||||
job = JobStates(Munch())
|
||||
|
||||
class FakeChat:
|
||||
def __init__(self):
|
||||
self.sent = []
|
||||
|
||||
def set_handler(self, _handler):
|
||||
pass
|
||||
|
||||
def send(self, message):
|
||||
self.sent.append(message)
|
||||
|
||||
chat = FakeChat()
|
||||
g = Munch(name='mosfet1', chat=chat, job=job,
|
||||
inv={0: Munch(item_id=next(iter(items.BED_IDS)))})
|
||||
try:
|
||||
Commands(g).handle_chat(('CHAT', 'tester',
|
||||
'tester: 1farm wart'))
|
||||
self.assertEqual(chat.sent, ['ok'])
|
||||
self.assertIs(job.state.__func__, job.farm_wart.__func__)
|
||||
self.assertIs(job.farm_wart()[0], job.gather_wart_states)
|
||||
self.assertIn(items.NETHERWART_ID, items.WANTED_ITEMS)
|
||||
finally:
|
||||
items.WANTED_ITEMS = old_wanted
|
||||
|
||||
def test_finds_only_indexed_mature_wart_allowed_by_work_signs(self):
|
||||
position = (5, 64, 8)
|
||||
mature = max(blocks.NETHERWART_IDS)
|
||||
|
||||
class FakeWorld:
|
||||
def __init__(self):
|
||||
self.search = None
|
||||
self.filter_input = None
|
||||
|
||||
def find_blocks_indexed(self, center, block_ids, distance):
|
||||
self.search = (center, block_ids, distance)
|
||||
return [position]
|
||||
|
||||
def filter_work_positions(self, positions):
|
||||
self.filter_input = list(positions)
|
||||
return list(positions)
|
||||
|
||||
world = FakeWorld()
|
||||
state = GatherWartStates(Munch(world=world, pos=(1.5, 64, 1.5)))
|
||||
|
||||
state.find_new_wart()
|
||||
|
||||
self.assertEqual(world.search, ((1, 64, 1), {mature}, 50))
|
||||
self.assertEqual(world.filter_input, [position])
|
||||
self.assertEqual(state.wart, position)
|
||||
self.assertIs(state.state.__func__, state.nav_to_wart.__func__)
|
||||
|
||||
def test_harvests_confirms_replant_on_soul_sand_below_wart(self):
|
||||
position = (5, 64, 8)
|
||||
mature = max(blocks.NETHERWART_IDS)
|
||||
unripe = min(blocks.NETHERWART_IDS)
|
||||
|
||||
class FakeWorld:
|
||||
def __init__(self):
|
||||
self.state_id = mature
|
||||
|
||||
def block_at(self, *_position):
|
||||
return self.state_id
|
||||
|
||||
class FakeGame:
|
||||
def __init__(self, global_state):
|
||||
self.g = global_state
|
||||
self.break_calls = []
|
||||
self.place_calls = []
|
||||
|
||||
def break_block(self, target):
|
||||
self.break_calls.append(target)
|
||||
return True
|
||||
|
||||
def select_item(self, item_ids):
|
||||
self.g.holding = items.NETHERWART_ID
|
||||
return items.NETHERWART_ID in item_ids
|
||||
|
||||
def place_block(self, target, face):
|
||||
self.place_calls.append((target, face))
|
||||
|
||||
world = FakeWorld()
|
||||
g = Munch(world=world, pos=position, holding=0, look_at=None)
|
||||
game = FakeGame(g)
|
||||
g.game = game
|
||||
state = GatherWartStates(g)
|
||||
state.wart = position
|
||||
state.type_id = mature
|
||||
|
||||
state.break_wart()
|
||||
self.assertIs(state.state.__func__, state.wait_break.__func__)
|
||||
self.assertEqual(game.break_calls, [position])
|
||||
|
||||
world.state_id = blocks.AIR
|
||||
state.wait_break()
|
||||
self.assertIs(state.state.__func__, state.select_wart.__func__)
|
||||
state.select_wart()
|
||||
state.wait_select()
|
||||
self.assertIs(state.state.__func__, state.place_wart.__func__)
|
||||
|
||||
state.place_wart()
|
||||
support = (position[0], position[1] - 1, position[2])
|
||||
self.assertEqual(game.place_calls, [(support, 1)])
|
||||
world.state_id = unripe
|
||||
state.wait_place()
|
||||
self.assertEqual(state.completed_warts, 1)
|
||||
self.assertIs(state.state.__func__, state.find_new_wart.__func__)
|
||||
|
||||
def test_navigation_looks_at_the_wart_target(self):
|
||||
position = (5, 64, 8)
|
||||
|
||||
class FakeWorld:
|
||||
@staticmethod
|
||||
def path_to_place(_start, _target):
|
||||
return [(1, 64, 1), position]
|
||||
|
||||
g = Munch(world=FakeWorld(), pos=(1, 64, 1), path=[], look_at=None)
|
||||
state = GatherWartStates(g)
|
||||
state.wart = position
|
||||
|
||||
state.nav_to_wart()
|
||||
|
||||
self.assertEqual(g.look_at, position)
|
||||
self.assertEqual(g.path[-1], position)
|
||||
|
||||
def test_gather_wart_finishes_after_sixteen_successful_replants(self):
|
||||
mature = max(blocks.NETHERWART_IDS)
|
||||
unripe = min(blocks.NETHERWART_IDS)
|
||||
|
||||
class FakeWorld:
|
||||
@staticmethod
|
||||
def block_at(*_position):
|
||||
return unripe
|
||||
|
||||
state = GatherWartStates(Munch(world=FakeWorld()))
|
||||
state.wart = (5, 64, 8)
|
||||
state.type_id = mature
|
||||
|
||||
for completed in range(1, state.WARTS_PER_BATCH):
|
||||
state.wait_place()
|
||||
self.assertEqual(state.completed_warts, completed)
|
||||
self.assertIs(state.state.__func__, state.find_new_wart.__func__)
|
||||
state.state = state.wait_place
|
||||
|
||||
state.wait_place()
|
||||
self.assertEqual(state.completed_warts, 0)
|
||||
self.assertIs(state.state.__func__, state.cleanup.__func__)
|
||||
|
||||
def test_unreachable_wart_is_blacklisted_without_undefined_variable(self):
|
||||
position = (5, 64, 8)
|
||||
|
||||
class FakeWorld:
|
||||
@staticmethod
|
||||
def path_to_place(_start, _target):
|
||||
return None
|
||||
|
||||
state = GatherWartStates(Munch(
|
||||
world=FakeWorld(), pos=(1, 64, 1), path=[]))
|
||||
state.wart = position
|
||||
|
||||
state.nav_to_wart()
|
||||
|
||||
self.assertIn(position, state.bad_warts)
|
||||
self.assertIs(state.state.__func__, state.find_new_wart.__func__)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,190 @@
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from munch import Munch
|
||||
|
||||
from mosfet.bot import start_automation
|
||||
from mosfet.commands import Commands
|
||||
from mosfet.info import blocks, items
|
||||
from mosfet.job import JobStates
|
||||
from mosfet.jobs.gather_wood import GatherWoodStates
|
||||
from mosfet.jobs.grab_supplies import GrabSuppliesStates
|
||||
from mosfet.protocol.types import Slot
|
||||
from mosfet.world import World
|
||||
|
||||
|
||||
class FakeChunks:
|
||||
def __init__(self, states):
|
||||
self.states = states
|
||||
self.index = {}
|
||||
|
||||
def get_block_at(self, x, y, z):
|
||||
return self.states.get((x, y, z), blocks.AIR)
|
||||
|
||||
|
||||
class GatherWoodPortTests(unittest.TestCase):
|
||||
def test_log_states_are_indexed_for_modern_chunk_search(self):
|
||||
self.assertTrue(blocks.LOG_IDS)
|
||||
self.assertTrue(blocks.LOG_IDS.issubset(blocks.INDEXED_IDS))
|
||||
|
||||
def test_mangrove_uses_its_26_3_propagule_and_unplantable_logs_are_skipped(self):
|
||||
self.assertEqual(items.get_sapling_id('mangrove'),
|
||||
items.get_id('mangrove_propagule'))
|
||||
self.assertIsNone(items.get_sapling_id('crimson'))
|
||||
|
||||
class FakeWorld:
|
||||
def find_trees(self, _position, _distance):
|
||||
return [(0, 64, 0), (3, 64, 0)]
|
||||
|
||||
@staticmethod
|
||||
def work_position_allowed(_position):
|
||||
return True
|
||||
|
||||
def filter_work_positions(self, positions):
|
||||
return [position for position in positions
|
||||
if self.work_position_allowed(position)]
|
||||
|
||||
def block_at(self, x, y, z):
|
||||
return (blocks.MCD_BLOCKS['crimson_stem']['minStateId']
|
||||
if x == 0 else
|
||||
blocks.MCD_BLOCKS['mangrove_log']['minStateId'])
|
||||
|
||||
state = GatherWoodStates(
|
||||
Munch(world=FakeWorld(), pos=(0, 64, 0)))
|
||||
state.find_new_tree()
|
||||
self.assertEqual(state.tree, (3, 64, 0))
|
||||
self.assertEqual(state.type, 'mangrove')
|
||||
self.assertEqual(state.bad_trees, [(0, 64, 0)])
|
||||
|
||||
def test_tree_search_finds_indexed_26_3_log_states(self):
|
||||
oak_log = blocks.MCD_BLOCKS['oak_log']['minStateId']
|
||||
oak_leaves = blocks.MCD_BLOCKS['oak_leaves']['minStateId']
|
||||
stone = blocks.MCD_BLOCKS['stone']['minStateId']
|
||||
states = {
|
||||
(0, 63, 0): stone,
|
||||
(0, 64, 0): oak_log,
|
||||
(0, 65, 0): oak_log,
|
||||
(0, 66, 0): oak_log,
|
||||
(1, 66, 0): oak_leaves,
|
||||
}
|
||||
chunks = FakeChunks(states)
|
||||
chunks.index[oak_log] = {
|
||||
(0, 64, 0), (0, 65, 0), (0, 66, 0),
|
||||
}
|
||||
world = World(Munch(chunks=chunks))
|
||||
self.assertEqual(list(world.find_trees((0, 64, 0), 10)),
|
||||
[(0, 64, 0)])
|
||||
|
||||
def test_gather_wood_job_keeps_existing_machine_sequence(self):
|
||||
job = JobStates(Munch())
|
||||
self.assertIsNotNone(job.gather_wood_states)
|
||||
self.assertEqual(job.gather_wood(), [
|
||||
job.gather_wood_states,
|
||||
job.sleep_with_bed_states,
|
||||
job.eat_food_states,
|
||||
job.cache_items_states,
|
||||
])
|
||||
job.gather_wood_states.state = job.gather_wood_states.find_new_tree
|
||||
job.stop()
|
||||
self.assertIs(job.gather_wood_states.state.__func__,
|
||||
job.gather_wood_states.idle.__func__)
|
||||
|
||||
def test_grab_supplies_reads_protocol_777_container_shape(self):
|
||||
axe_id = next(iter(items.AXE_IDS))
|
||||
axe = Slot(present=True, item_id=axe_id, item_count=1)
|
||||
clicks = []
|
||||
|
||||
class FakeGame:
|
||||
def count_inventory_slots(self):
|
||||
return 10
|
||||
|
||||
def click_window(self, *args):
|
||||
clicks.append(args)
|
||||
|
||||
g = Munch(
|
||||
item_lock=False,
|
||||
window=Munch(container_slots=27, contents={0: axe}),
|
||||
maximum_supply_slots=33,
|
||||
game=FakeGame(),
|
||||
)
|
||||
state = GrabSuppliesStates(g)
|
||||
state.target_items = {axe_id}
|
||||
state.maximum_stacks = 9
|
||||
state.grab_items()
|
||||
|
||||
self.assertTrue(g.item_lock)
|
||||
self.assertEqual(state.count, 1)
|
||||
self.assertEqual(clicks, [(0, 0, 1, axe)])
|
||||
|
||||
def test_modern_automation_sets_supply_inventory_limit(self):
|
||||
g = Munch()
|
||||
with patch('mosfet.bot.threading.Thread') as thread:
|
||||
start_automation(g, initialize=False)
|
||||
self.assertEqual(g.maximum_supply_slots, 33)
|
||||
thread.return_value.start.assert_called_once()
|
||||
|
||||
def test_farm_wood_job_keeps_legacy_machine_sequence(self):
|
||||
job = JobStates(Munch())
|
||||
try:
|
||||
self.assertEqual(job.farm_wood(), [
|
||||
job.grab_supplies_states,
|
||||
job.gather_wood_states,
|
||||
job.clear_leaves_states,
|
||||
job.plant_tree_states,
|
||||
job.grab_sapling_states,
|
||||
job.sleep_with_bed_states,
|
||||
job.eat_food_states,
|
||||
job.cache_items_states,
|
||||
])
|
||||
self.assertEqual(job.grab_supplies_states.supplies, {
|
||||
tuple(items.AXE_IDS): (1, 9),
|
||||
tuple(items.BED_IDS): (1, 1),
|
||||
(items.CHEST_ID,): (1, 1),
|
||||
tuple(items.FOOD_IDS): (1, 1),
|
||||
})
|
||||
self.assertTrue(job.sleep_with_bed_states.silent)
|
||||
self.assertTrue(job.cache_items_states.silent)
|
||||
self.assertTrue(items.AXE_IDS.issubset(items.NEEDED_ITEMS))
|
||||
self.assertTrue(items.SAPLING_IDS.issubset(items.WANTED_ITEMS))
|
||||
|
||||
job.grab_supplies_states.state = job.grab_supplies_states.find_supply_chests
|
||||
job.clear_leaves_states.state = job.clear_leaves_states.find_leaves
|
||||
job.plant_tree_states.state = job.plant_tree_states.check_feet
|
||||
job.grab_sapling_states.state = job.grab_sapling_states.find_saplings
|
||||
job.stop()
|
||||
for machine in (job.grab_supplies_states,
|
||||
job.clear_leaves_states,
|
||||
job.plant_tree_states,
|
||||
job.grab_sapling_states):
|
||||
self.assertIs(machine.state.__func__, machine.idle.__func__)
|
||||
finally:
|
||||
items.set_needed(set())
|
||||
items.set_wanted(set())
|
||||
|
||||
def test_gather_and_farm_wood_commands_are_enabled(self):
|
||||
class FakeChat:
|
||||
def __init__(self):
|
||||
self.sent = []
|
||||
|
||||
def set_handler(self, handler):
|
||||
self.handler = handler
|
||||
|
||||
def send(self, message):
|
||||
self.sent.append(message)
|
||||
|
||||
job = JobStates(Munch())
|
||||
chat = FakeChat()
|
||||
g = Munch(name='mosfet1', chat=chat, job=job,
|
||||
inv={0: Munch(item_id=next(iter(items.BED_IDS)))})
|
||||
Commands(g).handle_chat(('CHAT', 'tester', 'tester: 1gather wood'))
|
||||
self.assertEqual(chat.sent, ['ok'])
|
||||
self.assertIs(job.state.__func__, job.gather_wood.__func__)
|
||||
|
||||
chat.sent.clear()
|
||||
Commands(g).handle_chat(('CHAT', 'tester', 'tester: 1farm wood'))
|
||||
self.assertEqual(chat.sent, ['ok'])
|
||||
self.assertIs(job.state.__func__, job.farm_wood.__func__)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,203 @@
|
||||
import unittest
|
||||
from munch import Munch
|
||||
|
||||
from mosfet.info import items
|
||||
from mosfet.jobs.grab_supplies import GrabSuppliesStates
|
||||
|
||||
|
||||
class GroundSupplyTests(unittest.TestCase):
|
||||
def test_default_needed_supplies_are_configured_by_constructor(self):
|
||||
state = GrabSuppliesStates(Munch())
|
||||
self.assertEqual(items.FOOD, [
|
||||
'cooked_porkchop', 'cooked_beef', 'bread', 'cooked_chicken',
|
||||
'cooked_cod', 'cooked_salmon',
|
||||
])
|
||||
self.assertEqual(items.FOOD_IDS, items.get_set({
|
||||
'cooked_porkchop', 'cooked_beef', 'bread', 'cooked_chicken',
|
||||
'cooked_cod', 'cooked_salmon',
|
||||
}))
|
||||
self.assertEqual(state.supplies, {
|
||||
tuple(items.BED_IDS): (1, 1),
|
||||
(items.CHEST_ID,): (1, 1),
|
||||
tuple(items.FOOD_IDS): (1, 1),
|
||||
})
|
||||
|
||||
def test_chest_drop_is_checked_even_when_bed_is_missing(self):
|
||||
chest = Munch(entity_id=8, item_id=items.CHEST_ID,
|
||||
x=2.0, y=64.0, z=0.0)
|
||||
|
||||
class FakeWorld:
|
||||
@staticmethod
|
||||
def find_objects(item_ids):
|
||||
return [chest] if items.CHEST_ID in item_ids else []
|
||||
|
||||
class FakeGame:
|
||||
@staticmethod
|
||||
def count_inventory_slots():
|
||||
return 0
|
||||
|
||||
@staticmethod
|
||||
def count_items(_item_ids):
|
||||
return 0
|
||||
|
||||
state = GrabSuppliesStates(Munch(
|
||||
pos=(0.5, 64.0, 0.5), world=FakeWorld(), game=FakeGame(),
|
||||
maximum_supply_slots=33))
|
||||
state.init()
|
||||
state.check_supplies()
|
||||
state.find_ground_items()
|
||||
self.assertIn(tuple(items.BED_IDS), state.checked_ground_groups)
|
||||
state.check_supplies()
|
||||
|
||||
self.assertEqual(state.target_items, (items.CHEST_ID,))
|
||||
self.assertIs(state.state.__func__, state.find_ground_items.__func__)
|
||||
|
||||
def test_supply_selection_uses_only_addressed_supply_chests(self):
|
||||
position = (4, 64, 0)
|
||||
chest_record = {
|
||||
'position': position,
|
||||
'positions': (position,),
|
||||
'labels': {'mosfet supplies'},
|
||||
'sign_positions': {(4, 64, 1)},
|
||||
}
|
||||
|
||||
class FakeWorld:
|
||||
@staticmethod
|
||||
def find_supply_chests(_center, _bot_name, _distance):
|
||||
return [chest_record]
|
||||
|
||||
@staticmethod
|
||||
def find_blocks_indexed(*_args):
|
||||
raise AssertionError('grab_supplies must not search barrels')
|
||||
|
||||
state = GrabSuppliesStates(Munch(
|
||||
name='mosfet1', pos=(0.5, 64.0, 0.5), world=FakeWorld()))
|
||||
state.find_supply_chests()
|
||||
state.choose_supply_chest()
|
||||
|
||||
self.assertEqual(state.chest, position)
|
||||
self.assertIs(state.state.__func__, state.path_to_supply_chest.__func__)
|
||||
|
||||
def test_empty_supply_chest_is_skipped_until_another_player_opens_it(self):
|
||||
position = (4, 64, 0)
|
||||
key = (position,)
|
||||
event = {'position': position, 'timestamp': 1.0}
|
||||
g = Munch(chest_open_events=[])
|
||||
state = GrabSuppliesStates(g)
|
||||
state.supplies = {(999999,): (1, 1)}
|
||||
state.current_supply_chest_key = key
|
||||
|
||||
class FakeGame:
|
||||
@staticmethod
|
||||
def count_items(_item_ids):
|
||||
return 1
|
||||
|
||||
state.g.game = FakeGame()
|
||||
state.choose_items()
|
||||
self.assertIn(key, state.useless_chests)
|
||||
self.assertIs(state.state.__func__, state.close_supply_chest.__func__)
|
||||
|
||||
second_position = (8, 64, 0)
|
||||
state.supply_chests = [
|
||||
{'position': position, 'positions': key},
|
||||
{'position': second_position, 'positions': (second_position,)},
|
||||
]
|
||||
state.checked_supply_chests = {key}
|
||||
state.choose_supply_chest()
|
||||
self.assertEqual(state.chest, second_position)
|
||||
|
||||
g.chest_open_events.append(event)
|
||||
state.state = state.idle
|
||||
state.run()
|
||||
self.assertNotIn(key, state.useless_chests)
|
||||
self.assertNotIn(key, state.checked_supply_chests)
|
||||
|
||||
state.supply_chests = [{'position': position, 'positions': key}]
|
||||
state.choose_supply_chest()
|
||||
self.assertEqual(state.chest, position)
|
||||
|
||||
def test_unreachable_supply_chest_ends_task_without_searching_barrels(self):
|
||||
class FakeWorld:
|
||||
@staticmethod
|
||||
def path_to_place_faked(_start, _chest):
|
||||
return None
|
||||
|
||||
position = (10, 64, 10)
|
||||
state = GrabSuppliesStates(Munch(
|
||||
pos=(0.5, 64.0, 0.5), world=FakeWorld(), chunks=Munch()))
|
||||
state.supply_chests = [{
|
||||
'position': position, 'positions': (position,),
|
||||
'labels': {'mosfet supplies'},
|
||||
}]
|
||||
state.choose_supply_chest()
|
||||
state.path_to_supply_chest()
|
||||
state.choose_supply_chest()
|
||||
|
||||
self.assertIs(state.state.__func__, state.cleanup.__func__)
|
||||
|
||||
def test_job_walks_to_and_picks_up_dropped_supply_before_barrels(self):
|
||||
axe_id = next(iter(items.AXE_IDS))
|
||||
dropped_axe = Munch(
|
||||
entity_id=7, item_id=axe_id, item_count=1,
|
||||
x=3.2, y=64.0, z=0.2)
|
||||
|
||||
class FakeWorld:
|
||||
def __init__(self):
|
||||
self.path_requests = []
|
||||
|
||||
def find_objects(self, item_ids):
|
||||
return ([dropped_axe] if axe_id in item_ids else [])
|
||||
|
||||
def path_to_place(self, start, target):
|
||||
self.path_requests.append((start, target))
|
||||
return [start, target]
|
||||
|
||||
class FakeGame:
|
||||
def __init__(self):
|
||||
self.item_count = 0
|
||||
|
||||
def count_inventory_slots(self):
|
||||
return 5
|
||||
|
||||
def count_items(self, item_ids):
|
||||
return self.item_count if axe_id in item_ids else 0
|
||||
|
||||
world = FakeWorld()
|
||||
game = FakeGame()
|
||||
g = Munch(
|
||||
pos=(0.5, 64.0, 0.5), world=world, game=game,
|
||||
chunks=Munch(), objects={7: dropped_axe}, path=[],
|
||||
maximum_supply_slots=33,
|
||||
)
|
||||
state = GrabSuppliesStates(g)
|
||||
state.supplies = {tuple(items.AXE_IDS): (1, 9)}
|
||||
|
||||
state.init()
|
||||
state.check_supplies()
|
||||
state.find_ground_items()
|
||||
self.assertIs(state.state.__func__, state.going_to_ground_item.__func__)
|
||||
self.assertEqual(g.path[-1], (3, 64, 0))
|
||||
self.assertEqual(world.path_requests, [((0, 64, 0), (3, 64, 0))])
|
||||
|
||||
g.pos = (3.5, 64.0, 0.5)
|
||||
state.going_to_ground_item()
|
||||
self.assertIs(state.state.__func__, state.wait_for_ground_item.__func__)
|
||||
|
||||
game.item_count = 1
|
||||
state.wait_for_ground_item()
|
||||
self.assertIs(state.state.__func__, state.check_supplies.__func__)
|
||||
state.check_supplies()
|
||||
self.assertIs(state.state.__func__, state.cleanup.__func__)
|
||||
|
||||
# Nearby dropped tools are collected even when inventory already meets
|
||||
# the minimum, so tossing an axe during setup still gets noticed.
|
||||
game.item_count = 1
|
||||
state.init()
|
||||
state.check_supplies()
|
||||
self.assertIs(state.state.__func__, state.find_ground_items.__func__)
|
||||
state.find_ground_items()
|
||||
self.assertEqual(state.ground_required_count, 2)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,48 @@
|
||||
import io
|
||||
import struct
|
||||
import unittest
|
||||
|
||||
from munch import Munch
|
||||
|
||||
from mosfet.game import Game
|
||||
from mosfet.protocol.packets import SetHealthPacket
|
||||
|
||||
|
||||
class TestSetHealthPacket(unittest.TestCase):
|
||||
def test_protocol_777_packet_decodes_all_status_values(self):
|
||||
payload = struct.pack('>f', 13.5) + bytes([14]) + struct.pack('>f', 5.25)
|
||||
packet = SetHealthPacket()
|
||||
packet.read(io.BytesIO(payload))
|
||||
|
||||
self.assertEqual(packet.id, 0x6A)
|
||||
self.assertEqual(packet.health, 13.5)
|
||||
self.assertEqual(packet.food, 14)
|
||||
self.assertEqual(packet.food_saturation, 5.25)
|
||||
|
||||
def test_game_state_tracks_health_hunger_and_saturation(self):
|
||||
game = Game.__new__(Game)
|
||||
game.g = Munch()
|
||||
game.handle_set_health(SetHealthPacket(
|
||||
health=7.5, food=9, food_saturation=2.25))
|
||||
|
||||
self.assertEqual(game.g.health, 7.5)
|
||||
self.assertEqual(game.g.food, 9)
|
||||
self.assertEqual(game.g.hunger, 9)
|
||||
self.assertEqual(game.g.food_saturation, 2.25)
|
||||
self.assertEqual(game.g.saturation, 2.25)
|
||||
self.assertTrue(game.g.health_update_received)
|
||||
self.assertFalse(game.g.dead)
|
||||
|
||||
def test_zero_health_marks_bot_dead_without_faking_values(self):
|
||||
game = Game.__new__(Game)
|
||||
game.g = Munch()
|
||||
game.handle_set_health(SetHealthPacket(
|
||||
health=0.0, food=0, food_saturation=0.0))
|
||||
|
||||
self.assertEqual(game.g.health, 0.0)
|
||||
self.assertEqual(game.g.food, 0)
|
||||
self.assertTrue(game.g.dead)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,51 @@
|
||||
import unittest
|
||||
|
||||
from munch import Munch
|
||||
|
||||
from mosfet.commands import Commands
|
||||
|
||||
|
||||
class FakeChat:
|
||||
def __init__(self):
|
||||
self.sent = []
|
||||
|
||||
def set_handler(self, handler):
|
||||
self.handler = handler
|
||||
|
||||
def send(self, text):
|
||||
self.sent.append(text)
|
||||
|
||||
|
||||
class FakeGame:
|
||||
def __init__(self):
|
||||
self.dump_result = 2
|
||||
self.drop_result = True
|
||||
self.dump_item = None
|
||||
|
||||
def drop_stack(self):
|
||||
return self.drop_result
|
||||
|
||||
def start_dump(self, item_id):
|
||||
self.dump_item = item_id
|
||||
return self.dump_result
|
||||
|
||||
|
||||
class TestInventoryCommands(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.chat = FakeChat()
|
||||
self.game = FakeGame()
|
||||
self.commands = Commands(Munch(
|
||||
name='mosfet1', chat=self.chat, game=self.game))
|
||||
|
||||
def test_drop_command_is_enabled_for_bot(self):
|
||||
self.commands.handle_chat(('CHAT', 'tester', 'mosfet1: 1drop'))
|
||||
self.assertEqual(self.chat.sent, ['ok'])
|
||||
|
||||
def test_dump_command_starts_dump_for_item_id(self):
|
||||
self.commands.handle_chat(('CHAT', 'tester', 'mosfet1: 1dump 62'))
|
||||
self.assertEqual(self.game.dump_item, 62)
|
||||
self.assertEqual(self.chat.sent, ['ok'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,185 @@
|
||||
import io
|
||||
import unittest
|
||||
|
||||
from munch import Munch
|
||||
from minecraft.networking.modern import ClientTickEnd, ContainerOpenPacket
|
||||
from minecraft.networking.packets import PacketBuffer
|
||||
|
||||
from mosfet.game import (
|
||||
ContainerClickDropPacket, ContainerClickQuickMovePacket, Game,
|
||||
)
|
||||
from mosfet.protocol.types import Slot
|
||||
|
||||
|
||||
class FakeConnection:
|
||||
def __init__(self):
|
||||
self.packets = []
|
||||
|
||||
def write_packet(self, packet, force=False):
|
||||
self.packets.append((packet, force))
|
||||
|
||||
|
||||
class TestInventoryDrain(unittest.TestCase):
|
||||
def test_drop_packet_encodes_throw_whole_stack(self):
|
||||
packet = ContainerClickDropPacket(
|
||||
container_id=0, state_id=7, slot=45)
|
||||
payload = PacketBuffer()
|
||||
packet.write_fields(payload)
|
||||
|
||||
self.assertEqual(packet.id, 0x12)
|
||||
self.assertEqual(payload.get_writable(), bytes.fromhex(
|
||||
'0007002d01040000'))
|
||||
|
||||
def test_server_held_slot_updates_drop_target(self):
|
||||
game = Game.__new__(Game)
|
||||
game.g = Munch(
|
||||
inv={38: Slot(True, 864, 1)}, holding_slot=0,
|
||||
holding_hand=1, holding=355,
|
||||
)
|
||||
|
||||
game.handle_set_held_slot(Munch(slot=2))
|
||||
|
||||
self.assertEqual(game.g.holding_slot, 2)
|
||||
self.assertEqual(game.g.holding_hand, 0)
|
||||
self.assertEqual(game.g.holding, 864)
|
||||
|
||||
def test_drop_packet_encodes_throw_one_item(self):
|
||||
packet = ContainerClickDropPacket(
|
||||
container_id=0, state_id=7, slot=45, button=0)
|
||||
payload = PacketBuffer()
|
||||
packet.write_fields(payload)
|
||||
|
||||
self.assertEqual(payload.get_writable(), bytes.fromhex(
|
||||
'0007002d00040000'))
|
||||
|
||||
def test_quick_move_packet_encodes_shift_click(self):
|
||||
packet = ContainerClickQuickMovePacket(
|
||||
container_id=3, state_id=7, slot=42)
|
||||
payload = PacketBuffer()
|
||||
packet.write_fields(payload)
|
||||
|
||||
self.assertEqual(packet.id, 0x12)
|
||||
self.assertEqual(payload.get_writable(), bytes.fromhex(
|
||||
'0307002a00010000'))
|
||||
|
||||
def test_open_window_packet_decodes_container_metadata(self):
|
||||
# window id, menu type, empty anonymous-NBT title
|
||||
packet = ContainerOpenPacket()
|
||||
packet.read(io.BytesIO(bytes.fromhex('010200')))
|
||||
self.assertEqual(packet.window_id, 1)
|
||||
self.assertEqual(packet.inventory_type, 2)
|
||||
self.assertIsNone(packet.title)
|
||||
|
||||
def test_drop_stack_targets_currently_held_slot(self):
|
||||
connection = FakeConnection()
|
||||
game = Game.__new__(Game)
|
||||
game.g = Munch(
|
||||
inv={38: Slot(True, 62, 3)},
|
||||
inventory_state_ids={0: 7},
|
||||
holding_hand=0, holding_slot=2,
|
||||
connection=connection, draining=False, dumping=None,
|
||||
drop_waiting=None,
|
||||
)
|
||||
|
||||
self.assertTrue(game.drop_stack())
|
||||
packet = connection.packets[0][0]
|
||||
self.assertIsInstance(packet, ContainerClickDropPacket)
|
||||
self.assertEqual((packet.container_id, packet.state_id, packet.slot),
|
||||
(0, 7, 38))
|
||||
self.assertIsInstance(connection.packets[1][0], ClientTickEnd)
|
||||
self.assertEqual(game.g.drop_waiting['slot'], 38)
|
||||
|
||||
def test_drop_stack_uses_offhand_when_that_is_the_held_hand(self):
|
||||
connection = FakeConnection()
|
||||
game = Game.__new__(Game)
|
||||
game.g = Munch(
|
||||
inv={45: Slot(True, 355, 1)},
|
||||
inventory_state_ids={0: 2},
|
||||
holding_hand=1, holding_slot=0,
|
||||
connection=connection, draining=False, dumping=None,
|
||||
drop_waiting=None,
|
||||
)
|
||||
|
||||
self.assertTrue(game.drop_stack())
|
||||
self.assertEqual(connection.packets[0][0].slot, 45)
|
||||
|
||||
def test_dump_drops_every_matching_stack_sequentially(self):
|
||||
connection = FakeConnection()
|
||||
game = Game.__new__(Game)
|
||||
game.g = Munch(
|
||||
inv={9: Slot(True, 62, 5), 36: Slot(True, 62, 2),
|
||||
37: Slot(True, 1, 1)},
|
||||
inventory_state_ids={0: 3}, connection=connection,
|
||||
draining=False, dumping=None, drop_waiting=None,
|
||||
)
|
||||
|
||||
self.assertEqual(game.start_dump(62), 2)
|
||||
game._tick_dump()
|
||||
self.assertEqual(connection.packets[0][0].slot, 9)
|
||||
|
||||
game.g.inventory_state_ids[0] = 4
|
||||
game.g.inv[9] = Slot(False)
|
||||
game._tick_dump()
|
||||
self.assertEqual(connection.packets[2][0].slot, 36)
|
||||
self.assertEqual(game.g.dump_dropped, 1)
|
||||
|
||||
game.g.inventory_state_ids[0] = 5
|
||||
game.g.inv[36] = Slot(False)
|
||||
game._tick_dump()
|
||||
self.assertIsNone(game.g.dumping)
|
||||
self.assertEqual(game.g.dump_dropped, 2)
|
||||
|
||||
def test_drop_one_waits_for_decreased_stack_count(self):
|
||||
connection = FakeConnection()
|
||||
game = Game.__new__(Game)
|
||||
game.g = Munch(
|
||||
inv={38: Slot(True, 62, 3)}, inventory_state_ids={0: 4},
|
||||
holding_hand=0, holding_slot=2, connection=connection,
|
||||
draining=False, dumping=None, drop_waiting=None, window=None,
|
||||
)
|
||||
|
||||
self.assertTrue(game.drop_inventory_slot(38, whole_stack=False))
|
||||
packet = connection.packets[0][0]
|
||||
self.assertEqual((packet.slot, packet.button), (38, 0))
|
||||
waiting = game.g.drop_waiting
|
||||
self.assertEqual(waiting['expected_count'], 2)
|
||||
game.g.inv[38] = Slot(True, 62, 2)
|
||||
game._tick_single_drop()
|
||||
self.assertIsNone(game.g.drop_waiting)
|
||||
|
||||
def test_dump_refuses_to_overlap_inventory_drain(self):
|
||||
game = Game.__new__(Game)
|
||||
game.g = Munch(inv={9: Slot(True, 62, 1)}, draining=True,
|
||||
dumping=None, drop_waiting=None)
|
||||
self.assertIsNone(game.start_dump(62))
|
||||
|
||||
def test_drain_waits_for_authoritative_slot_update(self):
|
||||
connection = FakeConnection()
|
||||
game = Game.__new__(Game)
|
||||
game.g = Munch(
|
||||
inv={36: Slot(True, 62, 3)},
|
||||
inventory_state_ids={0: 5},
|
||||
connection=connection,
|
||||
draining=False,
|
||||
)
|
||||
|
||||
self.assertEqual(game.start_drain(), 1)
|
||||
game._tick_drain()
|
||||
self.assertTrue(game.g.draining)
|
||||
self.assertEqual(game.g.drain_waiting['slot'], 36)
|
||||
self.assertIsInstance(connection.packets[0][0],
|
||||
ContainerClickDropPacket)
|
||||
self.assertEqual(connection.packets[0][0].state_id, 5)
|
||||
self.assertIsInstance(connection.packets[1][0], ClientTickEnd)
|
||||
|
||||
# InventoryManager updates the state id and slot from server packets.
|
||||
game.g.inventory_state_ids[0] = 6
|
||||
game.g.inv[36] = Slot(False)
|
||||
game._tick_drain()
|
||||
self.assertFalse(game.g.draining)
|
||||
self.assertEqual(game.g.drain_dropped, 1)
|
||||
self.assertIsNone(game.g.drain_error)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,77 @@
|
||||
import unittest
|
||||
from munch import Munch
|
||||
|
||||
from mosfet.info import blocks, items
|
||||
from mosfet.jobs.cache_items import CacheItemsStates
|
||||
from mosfet.world import World
|
||||
|
||||
|
||||
class LabeledStorageTests(unittest.TestCase):
|
||||
def test_labels_resolve_to_item_categories(self):
|
||||
seeds = items.storage_item_ids_for_label('Seeds')
|
||||
wheat = items.storage_item_ids_for_label('Wheat')
|
||||
|
||||
self.assertEqual(seeds, items.get_set({
|
||||
'beetroot', 'beetroot_seeds', 'carrot', 'melon_seeds',
|
||||
'nether_wart', 'pitcher_pod', 'potato', 'pumpkin_seeds',
|
||||
'torchflower_seeds', 'wheat_seeds',
|
||||
}))
|
||||
self.assertEqual(items.storage_item_ids_for_label('Dirt'), set())
|
||||
self.assertEqual(items.storage_item_ids_for_label('Stone'), set())
|
||||
self.assertIn(items.WHEAT_SEEDS_ID, seeds)
|
||||
self.assertEqual(wheat, {items.WHEAT_ID})
|
||||
self.assertNotIn(items.WHEAT_SEEDS_ID, wheat)
|
||||
|
||||
def test_sign_label_associates_with_adjacent_double_chest(self):
|
||||
sign_pos = (0, 64, 0)
|
||||
left_chest = (0, 64, 1)
|
||||
right_chest = (1, 64, 1)
|
||||
blocks_by_pos = {left_chest: 5552, right_chest: 5560}
|
||||
chunks = Munch(
|
||||
block_entities={sign_pos: {
|
||||
'type': 7,
|
||||
'data': {'front_text': {'messages': [
|
||||
'Seeds', '', '', '',
|
||||
]}},
|
||||
}},
|
||||
index={},
|
||||
get_block_at=lambda *pos: blocks_by_pos.get(tuple(pos)),
|
||||
)
|
||||
chests = World(Munch(chunks=chunks)).find_labeled_chests(
|
||||
sign_pos, 10)
|
||||
|
||||
self.assertEqual(len(chests), 1)
|
||||
self.assertEqual(chests[0]['positions'], (left_chest, right_chest))
|
||||
self.assertIn(items.WHEAT_SEEDS_ID, chests[0]['item_ids'])
|
||||
self.assertEqual(chests[0]['labels'], {'Seeds'})
|
||||
|
||||
def test_wheat_chest_does_not_cache_seeds(self):
|
||||
wheat = Munch(present=True, item_id=items.WHEAT_ID, item_count=64)
|
||||
seeds = Munch(present=True, item_id=items.WHEAT_SEEDS_ID, item_count=64)
|
||||
clicks = []
|
||||
|
||||
class FakeGame:
|
||||
@staticmethod
|
||||
def count_window_slots():
|
||||
return 0
|
||||
|
||||
@staticmethod
|
||||
def click_window(*args):
|
||||
clicks.append(args)
|
||||
|
||||
cache = CacheItemsStates(Munch(
|
||||
inv={9: wheat, 10: seeds}, item_lock=False,
|
||||
window=Munch(container_slots=27, contents={
|
||||
**dict.fromkeys(range(27)), 27: wheat, 28: seeds,
|
||||
}),
|
||||
game=FakeGame(),
|
||||
))
|
||||
cache.is_labeled_container = True
|
||||
cache.container_item_ids = items.storage_item_ids_for_label('Wheat')
|
||||
cache.move_items()
|
||||
|
||||
self.assertEqual(clicks, [(27, 0, 1, wheat)])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,188 @@
|
||||
import contextlib
|
||||
import io
|
||||
import struct
|
||||
import unittest
|
||||
import uuid
|
||||
|
||||
from munch import Munch
|
||||
from minecraft.networking.modern import ClientboundPlayerChatPacket
|
||||
|
||||
from mosfet.commands import Commands
|
||||
from mosfet.connect import component_text
|
||||
from mosfet.protocol.modern import (
|
||||
ModernChatManager, parse_incoming_private_message,
|
||||
)
|
||||
|
||||
|
||||
class FakeConnection:
|
||||
def register_packet_listener(self, *_args, **_kwargs):
|
||||
pass
|
||||
|
||||
|
||||
class FakeChat:
|
||||
def __init__(self):
|
||||
self.messages = []
|
||||
|
||||
def set_handler(self, _handler):
|
||||
pass
|
||||
|
||||
def send(self, message):
|
||||
self.messages.append(message)
|
||||
|
||||
|
||||
class TestModernChat(unittest.TestCase):
|
||||
def test_incoming_dm_translation_is_rendered_and_parsed(self):
|
||||
rendered = component_text({
|
||||
'translate': 'commands.message.display.incoming',
|
||||
'with': ['tanner', '!ping'],
|
||||
})
|
||||
self.assertEqual(rendered, 'tanner whispers to you: !ping')
|
||||
self.assertEqual(parse_incoming_private_message(rendered),
|
||||
('tanner', '!ping'))
|
||||
self.assertEqual(parse_incoming_private_message(
|
||||
'tanner -> me: 1ping'), ('tanner', '1ping'))
|
||||
|
||||
def test_player_chat_console_uses_name_but_keeps_uuid_for_commands(self):
|
||||
player_uuid = 'f6126022-2c68-37f7-be93-aaa551374663'
|
||||
state = Munch(
|
||||
connection=FakeConnection(),
|
||||
player_names={player_uuid: 'tanner'},
|
||||
reload_lock=None,
|
||||
)
|
||||
manager = ModernChatManager(state)
|
||||
received = []
|
||||
manager.set_handler(received.append)
|
||||
output = io.StringIO()
|
||||
with contextlib.redirect_stdout(output):
|
||||
manager.handle_player_chat(Munch(
|
||||
sender=player_uuid, message='!ping', chat_type_id=1,
|
||||
network_target_name_present=False))
|
||||
|
||||
self.assertEqual(output.getvalue(), '[chat] tanner: !ping\n')
|
||||
self.assertEqual(received, [
|
||||
('CHAT', player_uuid, 'tanner: !ping'),
|
||||
])
|
||||
|
||||
def test_player_chat_target_name_marks_dm_and_routes_reply(self):
|
||||
player_uuid = 'f6126022-2c68-37f7-be93-aaa551374663'
|
||||
state = Munch(
|
||||
connection=FakeConnection(),
|
||||
player_names={player_uuid: 'tanner'},
|
||||
reload_lock=None,
|
||||
)
|
||||
manager = ModernChatManager(state)
|
||||
received = []
|
||||
manager.set_handler(received.append)
|
||||
output = io.StringIO()
|
||||
packet = Munch(
|
||||
sender=player_uuid, message='!ping', chat_type_id=2,
|
||||
network_target_name_present=True)
|
||||
with contextlib.redirect_stdout(output):
|
||||
manager.handle_player_chat(packet)
|
||||
|
||||
self.assertEqual(output.getvalue(), '[chat] [DM] tanner: !ping\n')
|
||||
self.assertEqual(received, [
|
||||
('DM', player_uuid, 'tanner -> me: !ping', 'tanner'),
|
||||
])
|
||||
|
||||
def test_player_chat_parser_reads_optional_target_name(self):
|
||||
def varint(value):
|
||||
encoded = bytearray()
|
||||
while value > 0x7f:
|
||||
encoded.append((value & 0x7f) | 0x80)
|
||||
value >>= 7
|
||||
encoded.append(value)
|
||||
return bytes(encoded)
|
||||
|
||||
message = b'!ping'
|
||||
payload = (
|
||||
varint(0) + uuid.UUID(int=0).bytes + varint(0) + b'\x00' +
|
||||
varint(len(message)) + message +
|
||||
struct.pack('>qq', 0, 0) + varint(0) + b'\x00' +
|
||||
varint(0) + varint(2) + b'\x00\x01\x00'
|
||||
)
|
||||
packet = ClientboundPlayerChatPacket()
|
||||
packet.read(io.BytesIO(payload))
|
||||
|
||||
self.assertEqual(packet.message, '!ping')
|
||||
self.assertEqual(packet.chat_type_id, 2)
|
||||
self.assertTrue(packet.network_target_name_present)
|
||||
|
||||
def test_chat_type_registry_identifies_dm_without_target_name(self):
|
||||
player_uuid = 'f6126022-2c68-37f7-be93-aaa551374663'
|
||||
state = Munch(
|
||||
connection=FakeConnection(),
|
||||
player_names={player_uuid: 'tanner'},
|
||||
reload_lock=None,
|
||||
)
|
||||
state.connection.registry_ids = {
|
||||
'minecraft:chat_type': {
|
||||
'minecraft:msg_command_incoming': 2,
|
||||
},
|
||||
}
|
||||
manager = ModernChatManager(state)
|
||||
received = []
|
||||
manager.set_handler(received.append)
|
||||
output = io.StringIO()
|
||||
with contextlib.redirect_stdout(output):
|
||||
manager.handle_player_chat(Munch(
|
||||
sender=player_uuid, message='!ping', chat_type_id=2,
|
||||
network_target_name_present=False))
|
||||
|
||||
self.assertEqual(output.getvalue(), '[chat] [DM] tanner: !ping\n')
|
||||
self.assertEqual(received, [
|
||||
('DM', player_uuid, 'tanner -> me: !ping', 'tanner'),
|
||||
])
|
||||
|
||||
def test_system_dm_console_uses_dm_prefix(self):
|
||||
state = Munch(connection=FakeConnection(), reload_lock=None)
|
||||
manager = ModernChatManager(state)
|
||||
received = []
|
||||
manager.set_handler(received.append)
|
||||
output = io.StringIO()
|
||||
with contextlib.redirect_stdout(output):
|
||||
handled = manager.handle_system_chat(
|
||||
None, 'tanner whispers to you: !ping')
|
||||
|
||||
self.assertTrue(handled)
|
||||
self.assertEqual(output.getvalue(), '[chat] [DM] tanner: !ping\n')
|
||||
self.assertEqual(received, [
|
||||
('DM', 'tanner', 'tanner -> me: !ping', 'tanner'),
|
||||
])
|
||||
|
||||
def test_dm_command_replies_to_named_sender(self):
|
||||
chat = FakeChat()
|
||||
command = Commands.__new__(Commands)
|
||||
command.g = Munch(name='mosfet1', chat=chat)
|
||||
|
||||
output = io.StringIO()
|
||||
with contextlib.redirect_stdout(output):
|
||||
command.handle_chat((
|
||||
'DM', 'f6126022-2c68-37f7-be93-aaa551374663',
|
||||
'tanner -> me: !ping', 'tanner'))
|
||||
|
||||
self.assertIn('Reply: pong', output.getvalue())
|
||||
self.assertEqual(chat.messages, ['/msg tanner pong'])
|
||||
|
||||
def test_here_dm_uses_sender_uuid_and_private_reply_name(self):
|
||||
sender_uuid = 'f6126022-2c68-37f7-be93-aaa551374663'
|
||||
chat = FakeChat()
|
||||
command = Commands.__new__(Commands)
|
||||
command.g = Munch(
|
||||
name='mosfet1', chat=chat, pos=(0, 64, 0), path=[], job=None,
|
||||
players={1: Munch(player_uuid=sender_uuid, x=10, y=64, z=20)},
|
||||
world=Munch(path_to_place=lambda start, goal: [start, goal]),
|
||||
)
|
||||
|
||||
output = io.StringIO()
|
||||
with contextlib.redirect_stdout(output):
|
||||
command.handle_chat((
|
||||
'DM', sender_uuid, 'tanner -> me: 1here', 'tanner'))
|
||||
|
||||
self.assertEqual(command.g.path, [(0, 64, 0), (10, 64, 20)])
|
||||
self.assertIn('Reply: ok', output.getvalue())
|
||||
self.assertEqual(chat.messages, ['/msg tanner ok'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,21 @@
|
||||
import unittest
|
||||
from munch import Munch
|
||||
|
||||
from mosfet.jobs.plant_tree import PlantTreeStates
|
||||
|
||||
|
||||
class PlantTreeTests(unittest.TestCase):
|
||||
def test_missing_inventory_sapling_aborts_without_crashing(self):
|
||||
class FakeGame:
|
||||
@staticmethod
|
||||
def select_item(_item_ids):
|
||||
return False
|
||||
|
||||
state = PlantTreeStates(Munch(
|
||||
pos=(0, 64, 0), chopped_tree='oak', game=FakeGame()))
|
||||
state.select_sapling()
|
||||
self.assertIs(state.state.__func__, state.cleanup.__func__)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,67 @@
|
||||
import unittest
|
||||
|
||||
from munch import Munch
|
||||
from minecraft.networking.packets import PacketBuffer
|
||||
from minecraft.networking.modern import ClientTickEnd
|
||||
|
||||
from mosfet.commands import Commands
|
||||
from mosfet.game import Game
|
||||
from mosfet.protocol.modern import ClientCommandPacket
|
||||
|
||||
|
||||
class FakeConnection:
|
||||
def __init__(self):
|
||||
self.packets = []
|
||||
|
||||
def write_packet(self, packet, force=False):
|
||||
self.packets.append((packet, force))
|
||||
|
||||
|
||||
class FakeChat:
|
||||
def __init__(self):
|
||||
self.handler = None
|
||||
self.messages = []
|
||||
|
||||
def set_handler(self, handler):
|
||||
self.handler = handler
|
||||
|
||||
def send(self, message):
|
||||
self.messages.append(message)
|
||||
|
||||
|
||||
class TestRespawn(unittest.TestCase):
|
||||
def test_client_command_encodes_perform_respawn(self):
|
||||
packet = ClientCommandPacket(action_id=0)
|
||||
buffer = PacketBuffer()
|
||||
packet.write_fields(buffer)
|
||||
self.assertEqual(packet.id, 0x0C)
|
||||
self.assertEqual(buffer.get_writable(), b'\x00')
|
||||
|
||||
def test_game_respawn_sends_modern_client_command_and_tick_end(self):
|
||||
connection = FakeConnection()
|
||||
game = Game.__new__(Game)
|
||||
game.g = Munch(connection=connection)
|
||||
|
||||
game.respawn()
|
||||
|
||||
packet, forced = connection.packets[0]
|
||||
self.assertIsInstance(packet, ClientCommandPacket)
|
||||
self.assertEqual(packet.action_id, 0)
|
||||
self.assertTrue(forced)
|
||||
self.assertIsInstance(connection.packets[1][0], ClientTickEnd)
|
||||
self.assertIn('respawn_requested_at', game.g)
|
||||
|
||||
def test_respawn_command_is_enabled(self):
|
||||
chat = FakeChat()
|
||||
calls = []
|
||||
game = Munch(respawn=lambda: calls.append('respawn'))
|
||||
commands = Commands(Munch(name='mosfet1', chat=chat, game=game))
|
||||
|
||||
commands.handle_chat(('SYSTEM', None, 'server: 1respawn'))
|
||||
|
||||
self.assertEqual(calls, ['respawn'])
|
||||
self.assertEqual(chat.messages, ['ok'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,60 @@
|
||||
import io
|
||||
import unittest
|
||||
from munch import Munch
|
||||
|
||||
from minecraft.networking.modern import (
|
||||
ModernPlayingReactor, SetEntityDataPacket,
|
||||
)
|
||||
from mosfet.info import items
|
||||
from mosfet.protocol.managers import EntityManager
|
||||
from mosfet.world import World
|
||||
|
||||
|
||||
def encode_varint(value):
|
||||
encoded = bytearray()
|
||||
while value & ~0x7F:
|
||||
encoded.append((value & 0x7F) | 0x80)
|
||||
value >>= 7
|
||||
encoded.append(value)
|
||||
return bytes(encoded)
|
||||
|
||||
|
||||
class SaplingEntityTests(unittest.TestCase):
|
||||
def test_protocol_777_item_metadata_decodes_item_stack(self):
|
||||
sapling_id = items.get_id('oak_sapling')
|
||||
payload = (
|
||||
encode_varint(42) +
|
||||
bytes((8,)) + encode_varint(7) +
|
||||
encode_varint(1) + encode_varint(sapling_id) +
|
||||
encode_varint(0) + encode_varint(0) +
|
||||
bytes((0xFF,))
|
||||
)
|
||||
packet = SetEntityDataPacket()
|
||||
packet.read(io.BytesIO(payload))
|
||||
|
||||
self.assertEqual(packet.entity_id, 42)
|
||||
self.assertEqual(len(packet.item_stacks), 1)
|
||||
self.assertEqual(packet.item_stacks[0].item_id, sapling_id)
|
||||
self.assertIn(SetEntityDataPacket,
|
||||
ModernPlayingReactor.get_clientbound_packets(None))
|
||||
|
||||
def test_item_metadata_makes_dropped_sapling_searchable(self):
|
||||
sapling_id = items.get_id('oak_sapling')
|
||||
entity = Munch(entity_id=42, x=1.0, y=65.0, z=2.0)
|
||||
manager = object.__new__(EntityManager)
|
||||
manager.g = Munch(objects={42: entity})
|
||||
packet = Munch(
|
||||
entity_id=42,
|
||||
item_stacks=[Munch(present=True, item_id=sapling_id,
|
||||
item_count=1)],
|
||||
)
|
||||
manager.handle_entity_data(packet)
|
||||
|
||||
found = World(Munch(objects={42: entity})).find_objects(
|
||||
items.SAPLING_IDS)
|
||||
self.assertEqual(found, [entity])
|
||||
self.assertEqual(entity.item_count, 1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,70 @@
|
||||
import unittest
|
||||
from munch import Munch
|
||||
|
||||
from mosfet.info import blocks
|
||||
from mosfet.jobs.gather_crop import GatherCropStates
|
||||
from mosfet.jobs.gather_wood import GatherWoodStates
|
||||
|
||||
|
||||
class SignWorkTargetTests(unittest.TestCase):
|
||||
def test_crop_search_filters_out_of_bounds_candidates_before_navigation(self):
|
||||
outside = (10, 64, 0)
|
||||
mature_wheat = blocks.MATURE_WHEAT_ID
|
||||
crop_state = blocks.MCD_BLOCKS['wheat']['minStateId']
|
||||
|
||||
class FakeWorld:
|
||||
def find_blocks_indexed(self, _center, _block_ids, _distance):
|
||||
return [outside]
|
||||
|
||||
@staticmethod
|
||||
def work_position_allowed(position):
|
||||
return position != outside
|
||||
|
||||
def filter_work_positions(self, positions):
|
||||
return [position for position in positions
|
||||
if self.work_position_allowed(position)]
|
||||
|
||||
@staticmethod
|
||||
def block_at(*_position):
|
||||
return crop_state
|
||||
|
||||
state = GatherCropStates(Munch(world=FakeWorld(), pos=(0, 64, 0)))
|
||||
state.completed_crops = 7
|
||||
state.find_new_crop()
|
||||
|
||||
self.assertIs(state.state.__func__, state.cleanup.__func__)
|
||||
self.assertEqual(state.completed_crops, 0)
|
||||
self.assertEqual(state.bad_crops, [])
|
||||
|
||||
def test_tree_search_skips_out_of_bounds_tree_without_blacklisting_it(self):
|
||||
outside = (10, 64, 0)
|
||||
inside = (2, 64, 0)
|
||||
oak_log = blocks.MCD_BLOCKS['oak_log']['minStateId']
|
||||
|
||||
class FakeWorld:
|
||||
@staticmethod
|
||||
def find_trees(_center, _distance):
|
||||
return [outside, inside]
|
||||
|
||||
@staticmethod
|
||||
def work_position_allowed(position):
|
||||
return position != outside
|
||||
|
||||
def filter_work_positions(self, positions):
|
||||
return [position for position in positions
|
||||
if self.work_position_allowed(position)]
|
||||
|
||||
@staticmethod
|
||||
def block_at(*_position):
|
||||
return oak_log
|
||||
|
||||
state = GatherWoodStates(Munch(world=FakeWorld(), pos=(0, 64, 0)))
|
||||
state.find_new_tree()
|
||||
|
||||
self.assertEqual(state.tree, inside)
|
||||
self.assertEqual(state.type, 'oak')
|
||||
self.assertEqual(state.bad_trees, [])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,196 @@
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
from munch import Munch
|
||||
|
||||
from mosfet.commands import Commands
|
||||
from mosfet.info import blocks
|
||||
from mosfet.protocol.managers import EntityManager, WorldState
|
||||
from mosfet.world import World
|
||||
|
||||
|
||||
class SignReadingTests(unittest.TestCase):
|
||||
def test_world_decodes_front_and_back_sign_components(self):
|
||||
chunks = Munch(block_entities={
|
||||
(2, 64, 3): {
|
||||
'type': 7,
|
||||
'data': {
|
||||
'front_text': {'messages': [
|
||||
'{"text":"Hello","extra":[{"text":" world"}]}',
|
||||
'{"text":"line two"}', '', ''],
|
||||
},
|
||||
'back_text': {'messages': [
|
||||
'{"text":"back"}', '', '', ''],
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
signs = World(Munch(chunks=chunks)).find_signs((0, 64, 0), 10)
|
||||
|
||||
self.assertEqual(signs, [
|
||||
{'position': (2, 64, 3), 'side': 'front',
|
||||
'lines': ('Hello world', 'line two', '', '')},
|
||||
{'position': (2, 64, 3), 'side': 'back',
|
||||
'lines': ('back', '', '', '')},
|
||||
])
|
||||
|
||||
def test_block_entity_update_is_cached_for_sign_search(self):
|
||||
chunks = WorldState()
|
||||
manager = object.__new__(EntityManager)
|
||||
manager.g = Munch(chunks=chunks)
|
||||
manager.handle_block_entity_data(Munch(
|
||||
location=Munch(x=4, y=65, z=-2),
|
||||
block_entity_type=7,
|
||||
data={'front_text': {'messages': ['{"text":"Farm"}', '', '', '']}},
|
||||
))
|
||||
|
||||
signs = World(Munch(chunks=chunks)).find_signs((4, 65, -2), 1)
|
||||
self.assertEqual(signs[0]['lines'], ('Farm', '', '', ''))
|
||||
|
||||
def test_broken_sign_block_update_removes_cached_sign_entity(self):
|
||||
position = (4, 65, -2)
|
||||
sign_state = blocks.MCD_BLOCKS['oak_wall_sign']['minStateId']
|
||||
|
||||
class FakeColumn:
|
||||
def __init__(self):
|
||||
self.states = {}
|
||||
|
||||
def get_block_at(self, x, y, z):
|
||||
return self.states.get((x, y, z), blocks.AIR)
|
||||
|
||||
def set_block_at(self, x, y, z, state_id):
|
||||
previous = self.get_block_at(x, y, z)
|
||||
self.states[(x, y, z)] = state_id
|
||||
return previous
|
||||
|
||||
chunks = WorldState()
|
||||
chunks.chunks[(0, -1)] = FakeColumn()
|
||||
chunks.set_block_at(*position, sign_state)
|
||||
chunks.set_block_entity(position, 7, {
|
||||
'front_text': {'messages': ['mosfet1 stay', 'within 8 square', '', '']},
|
||||
})
|
||||
world = World(Munch(chunks=chunks))
|
||||
|
||||
self.assertEqual(len(world.find_signs(position, 1)), 1)
|
||||
chunks.set_block_at(*position, blocks.AIR)
|
||||
|
||||
self.assertNotIn(position, chunks.block_entities)
|
||||
self.assertEqual(world.find_signs(position, 1), [])
|
||||
|
||||
def test_sign_search_ignores_stale_block_entity_for_non_sign_block(self):
|
||||
position = (4, 65, -2)
|
||||
chunks = Munch(
|
||||
block_entities={position: {'data': {'front_text': {
|
||||
'messages': ['mosfet1 stay', 'within 8 square', '', ''],
|
||||
}}}},
|
||||
get_block_at=lambda *_position: blocks.AIR,
|
||||
)
|
||||
|
||||
self.assertEqual(World(Munch(chunks=chunks)).find_signs(position, 1), [])
|
||||
|
||||
def test_group_and_individual_sign_addresses(self):
|
||||
group_world = World(Munch(chunks=Munch(block_entities={
|
||||
(0, 64, 0): {'data': {'front_text': {'messages': [
|
||||
'mosfet', 'stay within25', 'square', '',
|
||||
]}}},
|
||||
}), pos=(0, 64, 0)))
|
||||
for bot_name in ('mosfet1', 'mosfet2', 'mosfet3'):
|
||||
self.assertEqual([p['shape'] for p in
|
||||
group_world.sign_policies(bot_name)], ['square'])
|
||||
self.assertEqual(group_world.sign_policies('mosfet4'), [])
|
||||
|
||||
individual_world = World(Munch(chunks=Munch(block_entities={
|
||||
(1, 64, 0): {'data': {'front_text': {'messages': [
|
||||
'mosfet2', 'stay within 10 circle', '', '',
|
||||
]}}},
|
||||
}), pos=(1, 64, 0)))
|
||||
self.assertEqual([p['shape'] for p in
|
||||
individual_world.sign_policies('mosfet2')], ['circle'])
|
||||
self.assertEqual(individual_world.sign_policies('mosfet1'), [])
|
||||
|
||||
def test_nearest_sign_policy_overrides_farther_matching_sign(self):
|
||||
chunks = Munch(block_entities={
|
||||
(-138, 71, -268): {'data': {'front_text': {'messages': [
|
||||
'mosfet1', 'stay within 25 square', '', '',
|
||||
]}}},
|
||||
(-158, 71, -248): {'data': {'front_text': {'messages': [
|
||||
'mosfet1', 'stay within 6 squares', '', '',
|
||||
]}}},
|
||||
})
|
||||
world = World(Munch(chunks=chunks, pos=(-158, 71, -248)))
|
||||
self.assertEqual(world.sign_policies('mosfet1'), [{
|
||||
'position': (-158, 71, -248), 'distance': 6,
|
||||
'shape': 'square', 'side': 'front',
|
||||
}])
|
||||
|
||||
def test_work_paths_obey_sign_boundary_but_cache_paths_do_not(self):
|
||||
sign_data = {'front_text': {'messages': [
|
||||
'mosfet1', 'stay within 25 square', '', '',
|
||||
]}}
|
||||
chunks = Munch(block_entities={(0, 64, 0): {'data': sign_data}})
|
||||
work_machine = object()
|
||||
cache_machine = object()
|
||||
job = Munch(active_machine=work_machine,
|
||||
cache_items_states=cache_machine)
|
||||
world = World(Munch(chunks=chunks, job=job, name='mosfet1',
|
||||
pos=(0, 64, 0)))
|
||||
|
||||
class FixedPathfinder:
|
||||
@staticmethod
|
||||
def astar(_start, _place):
|
||||
return [(0, 64, 0), (20, 64, 0), (30, 64, 0)]
|
||||
|
||||
with patch('mosfet.world.path.Pathfinder', return_value=FixedPathfinder()):
|
||||
self.assertIsNone(world.path_to_place((0, 64, 0), (30, 64, 0)))
|
||||
job.active_machine = cache_machine
|
||||
self.assertEqual(world.path_to_place(
|
||||
(0, 64, 0), (30, 64, 0)),
|
||||
[(0, 64, 0), (20, 64, 0), (30, 64, 0)])
|
||||
|
||||
policy = {'position': (0, 64, 0), 'distance': 25, 'shape': 'square'}
|
||||
self.assertTrue(World._path_allowed_by_sign(
|
||||
[(30, 64, 0), (27, 64, 0), (24, 64, 0)], policy))
|
||||
self.assertFalse(World._path_allowed_by_sign(
|
||||
[(30, 64, 0), (32, 64, 0), (24, 64, 0)], policy))
|
||||
|
||||
six_square = {'position': (-158, 71, -248),
|
||||
'distance': 6, 'shape': 'square'}
|
||||
six_circle = dict(six_square, shape='circle')
|
||||
crop = (-162, 68, -247)
|
||||
self.assertEqual(World._sign_policy_distance(crop, six_square), 4)
|
||||
self.assertAlmostEqual(World._sign_policy_distance(crop, six_circle),
|
||||
(17 ** 0.5))
|
||||
|
||||
four_square = {'position': (0, 64, 0),
|
||||
'distance': 4, 'shape': 'square'}
|
||||
self.assertEqual(World._sign_policy_distance((4, 70, 4), four_square), 4)
|
||||
self.assertTrue(World._inside_sign_policy((4, 70, 4), four_square))
|
||||
self.assertFalse(World._inside_sign_policy((5, 64, 4), four_square))
|
||||
same_xz_far_y = (-158, -20, -248)
|
||||
self.assertEqual(
|
||||
World._sign_policy_distance(same_xz_far_y, six_square), 0)
|
||||
|
||||
def test_signs_command_replies_with_nearby_text(self):
|
||||
class FakeChat:
|
||||
def __init__(self):
|
||||
self.sent = []
|
||||
|
||||
def set_handler(self, handler):
|
||||
self.handler = handler
|
||||
|
||||
def send(self, message):
|
||||
self.sent.append(message)
|
||||
|
||||
chat = FakeChat()
|
||||
world = Munch(find_signs=lambda _position, _distance: [{
|
||||
'position': (1, 64, 2), 'side': 'front',
|
||||
'lines': ('Hello', 'world', '', ''),
|
||||
}])
|
||||
commands = Commands(Munch(
|
||||
name='mosfet1', chat=chat, world=world, pos=(0.5, 64.0, 0.5)))
|
||||
commands.handle_chat(('CHAT', 'tester', 'tester: !signs'))
|
||||
|
||||
self.assertEqual(chat.sent, ['front (1, 64, 2): Hello | world'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,463 @@
|
||||
import io
|
||||
import unittest
|
||||
from contextlib import redirect_stdout
|
||||
from unittest.mock import patch
|
||||
|
||||
from munch import Munch
|
||||
from minecraft.networking.packets import PacketBuffer
|
||||
from minecraft.networking.types import Float, Long, VarInt, VarLong
|
||||
|
||||
from mosfet.game import Game
|
||||
from mosfet.info import blocks, items
|
||||
from mosfet.protocol.types import Slot
|
||||
from mosfet.jobs.sleep_with_bed import SleepWithBedStates
|
||||
from mosfet.world import World
|
||||
from mosfet.protocol.modern import PlayerCommandPacket, UpdateTimePacket
|
||||
from minecraft.networking.modern import ClientTickEnd, UseItemOnBlockPacket
|
||||
|
||||
|
||||
class FakeConnection:
|
||||
def __init__(self):
|
||||
self.packets = []
|
||||
|
||||
def write_packet(self, packet, force=False):
|
||||
self.packets.append((packet, force))
|
||||
|
||||
|
||||
class FakeChunks:
|
||||
def __init__(self, block):
|
||||
self.block = block
|
||||
|
||||
def get_block_at(self, *position):
|
||||
return self.block
|
||||
|
||||
|
||||
class FakeWorld:
|
||||
def __init__(self, block=blocks.AIR):
|
||||
self.block = block
|
||||
|
||||
def block_at(self, *position):
|
||||
return self.block
|
||||
|
||||
def check_bed_occupied(self, position):
|
||||
return False
|
||||
|
||||
|
||||
class FakeGame:
|
||||
def __init__(self):
|
||||
self.placements = []
|
||||
|
||||
def place_block(self, location, face, hand=0, cursor_y=None):
|
||||
self.placements.append((location, face, hand, cursor_y))
|
||||
|
||||
|
||||
class TestSleepWithBed(unittest.TestCase):
|
||||
def test_confirmed_sleep_records_bed_for_following_cache_pass(self):
|
||||
bed = (1, 64, 2)
|
||||
g = Munch(world=FakeWorld(), path=[], look_at=None)
|
||||
state = SleepWithBedStates(g)
|
||||
state.area = bed
|
||||
state.sleep_confirmed = True
|
||||
|
||||
state.cleanup()
|
||||
|
||||
self.assertEqual(g.post_sleep_cache_bed, bed)
|
||||
|
||||
def test_unconfirmed_sleep_does_not_trigger_post_sleep_cache(self):
|
||||
g = Munch(world=FakeWorld(), path=[], look_at=None)
|
||||
state = SleepWithBedStates(g)
|
||||
state.area = (1, 64, 2)
|
||||
state.sleep_confirmed = False
|
||||
|
||||
state.cleanup()
|
||||
|
||||
self.assertNotIn('post_sleep_cache_bed', g)
|
||||
|
||||
def test_bed_occupancy_only_logs_first_observation_and_changes(self):
|
||||
bed_states = [
|
||||
state for state in blocks.BED_IDS
|
||||
if blocks.BLOCKS[state] == 'white_bed' and
|
||||
blocks.PROPS[state].get('part') == 'foot' and
|
||||
blocks.PROPS[state].get('facing') == 'north'
|
||||
]
|
||||
free = next(state for state in bed_states
|
||||
if blocks.PROPS[state].get('occupied') == 'false')
|
||||
occupied = next(state for state in bed_states
|
||||
if blocks.PROPS[state].get('occupied') == 'true')
|
||||
chunks = FakeChunks(free)
|
||||
world = World(Munch(chunks=chunks))
|
||||
output = io.StringIO()
|
||||
|
||||
with redirect_stdout(output):
|
||||
self.assertFalse(world.check_bed_occupied((1, 64, 2)))
|
||||
self.assertFalse(world.check_bed_occupied((1, 64, 2)))
|
||||
chunks.block = occupied
|
||||
self.assertTrue(world.check_bed_occupied((1, 64, 2)))
|
||||
self.assertTrue(world.check_bed_occupied((1, 64, 2)))
|
||||
|
||||
lines = output.getvalue().splitlines()
|
||||
self.assertEqual(len(lines), 2)
|
||||
self.assertIn('-> free', lines[0])
|
||||
self.assertIn('-> occupied', lines[1])
|
||||
|
||||
def test_update_time_packet_decodes_clock_updates(self):
|
||||
payload = PacketBuffer()
|
||||
Long.send(123456, payload)
|
||||
VarInt.send(1, payload)
|
||||
VarInt.send(0, payload)
|
||||
VarLong.send(13000, payload)
|
||||
Float.send(0.5, payload)
|
||||
Float.send(1.0, payload)
|
||||
|
||||
packet = UpdateTimePacket()
|
||||
packet.read(io.BytesIO(payload.get_writable()))
|
||||
self.assertEqual(packet.id, 0x73)
|
||||
self.assertEqual(packet.age, 123456)
|
||||
self.assertEqual(packet.clock_updates, [{
|
||||
'clock_id': 0, 'total_ticks': 13000,
|
||||
'partial_tick': 0.5, 'rate': 1.0,
|
||||
}])
|
||||
|
||||
def test_game_advances_world_clock_between_server_updates(self):
|
||||
game = Game.__new__(Game)
|
||||
game.g = Munch(
|
||||
time_base=None, time_update_received_at=None, clock_rate=1.0,
|
||||
time=0.0,
|
||||
connection=Munch(registry_ids={'minecraft:world_clock': {
|
||||
'minecraft:the_end': 1,
|
||||
'minecraft:overworld': 0,
|
||||
}}),
|
||||
dimension='overworld')
|
||||
packet = Munch(age=900000, clock_updates=[
|
||||
{'clock_id': 1, 'total_ticks': 6000,
|
||||
'partial_tick': 0.0, 'rate': 1.0},
|
||||
{'clock_id': 0, 'total_ticks': 13000,
|
||||
'partial_tick': 0.5, 'rate': 1.0},
|
||||
])
|
||||
|
||||
with patch('mosfet.game.time.monotonic', return_value=100.0):
|
||||
game.handle_time_update(packet)
|
||||
self.assertEqual(game.g.time, 13000.5)
|
||||
self.assertEqual(game.g.clock_name, 'minecraft:overworld')
|
||||
|
||||
with patch('mosfet.game.time.monotonic', return_value=100.5):
|
||||
game._advance_world_time()
|
||||
|
||||
self.assertEqual(game.g.time, 13010.5)
|
||||
|
||||
def test_player_command_encodes_stop_sleeping(self):
|
||||
packet = PlayerCommandPacket(
|
||||
entity_id=7, action_id=0, jump_boost=0)
|
||||
payload = PacketBuffer()
|
||||
packet.write_fields(payload)
|
||||
self.assertEqual(packet.id, 0x2A)
|
||||
self.assertEqual(payload.get_writable(), b'\x07\x00\x00')
|
||||
|
||||
def test_game_leave_bed_sends_protocol_777_stop_sleeping(self):
|
||||
connection = FakeConnection()
|
||||
game = Game.__new__(Game)
|
||||
game.g = Munch(connection=connection, eid=42)
|
||||
|
||||
game.leave_bed()
|
||||
|
||||
packet, force = connection.packets[0]
|
||||
self.assertIsInstance(packet, PlayerCommandPacket)
|
||||
self.assertEqual((packet.entity_id, packet.action_id,
|
||||
packet.jump_boost), (42, 0, 0))
|
||||
self.assertTrue(force)
|
||||
self.assertIsInstance(connection.packets[1][0], ClientTickEnd)
|
||||
|
||||
def test_existing_bed_use_aims_inside_the_short_bed_collision_shape(self):
|
||||
connection = FakeConnection()
|
||||
game = Game.__new__(Game)
|
||||
game.g = Munch(connection=connection)
|
||||
game.sequence = 0
|
||||
|
||||
game.place_block((-175, 70, -312), 1, cursor_y=0.5)
|
||||
|
||||
packet = connection.packets[0][0]
|
||||
self.assertIsInstance(packet, UseItemOnBlockPacket)
|
||||
self.assertEqual(packet.location, (-175, 70, -312))
|
||||
self.assertEqual(packet.cursor_y, 0.5)
|
||||
self.assertIsInstance(connection.packets[1][0], ClientTickEnd)
|
||||
|
||||
def test_bed_in_offhand_is_selectable_without_swapping_inventory(self):
|
||||
connection = FakeConnection()
|
||||
game = Game.__new__(Game)
|
||||
bed_id = next(iter(items.BED_IDS))
|
||||
game.g = Munch(
|
||||
connection=connection, inv={45: Slot(True, bed_id, 1)},
|
||||
holding_hand=0)
|
||||
|
||||
self.assertTrue(game.select_item(items.BED_IDS))
|
||||
self.assertEqual(game.g.holding, bed_id)
|
||||
self.assertEqual(game.g.holding_hand, 1)
|
||||
self.assertIsInstance(connection.packets[0][0], ClientTickEnd)
|
||||
|
||||
def test_bed_head_position_is_normalized_to_foot(self):
|
||||
bed_name = 'white_bed'
|
||||
foot_state = next(
|
||||
state for state in blocks.BED_IDS
|
||||
if blocks.BLOCKS[state] == bed_name and
|
||||
blocks.PROPS[state].get('part') == 'foot' and
|
||||
blocks.PROPS[state].get('facing') == 'west')
|
||||
head_state = next(
|
||||
state for state in blocks.BED_IDS
|
||||
if blocks.BLOCKS[state] == bed_name and
|
||||
blocks.PROPS[state].get('part') == 'head' and
|
||||
blocks.PROPS[state].get('facing') == 'west')
|
||||
foot, head = (-175, 70, -312), (-176, 70, -312)
|
||||
|
||||
class BedWorld:
|
||||
def block_at(self, *position):
|
||||
return {foot: foot_state, head: head_state}.get(tuple(position), blocks.AIR)
|
||||
|
||||
state = SleepWithBedStates(Munch(world=BedWorld()))
|
||||
self.assertEqual(state._bed_foot(head), foot)
|
||||
self.assertEqual(state._bed_foot(foot), foot)
|
||||
|
||||
def test_bed_search_falls_back_to_loaded_blocks_if_index_is_empty(self):
|
||||
bed = (1, 64, 0)
|
||||
bed_state = next(
|
||||
state for state in blocks.BED_IDS
|
||||
if blocks.PROPS[state].get('part') == 'foot')
|
||||
|
||||
class IndexedWorld:
|
||||
def find_blocks_indexed(self, center, block_ids, distance=0):
|
||||
return []
|
||||
|
||||
def find_blocks_3d(self, center, block_ids, distance, y_limit):
|
||||
self.assert_search = (center, block_ids, distance, y_limit)
|
||||
return iter([bed])
|
||||
|
||||
def block_at(self, *position):
|
||||
return bed_state if tuple(position) == bed else blocks.AIR
|
||||
|
||||
def check_bed_occupied(self, position):
|
||||
return False
|
||||
|
||||
world = IndexedWorld()
|
||||
state = SleepWithBedStates(Munch(
|
||||
world=world, pos=(0, 64, 0), time=13000,
|
||||
dimension='overworld'))
|
||||
|
||||
state.find_beds()
|
||||
|
||||
self.assertEqual(state.beds, [bed])
|
||||
self.assertEqual(state.state, state.choose_bed)
|
||||
|
||||
def test_force_new_bed_skips_existing_bed_scan(self):
|
||||
class IndexedWorld:
|
||||
def find_blocks_indexed(self, *args, **kwargs):
|
||||
raise AssertionError('forced placement must skip bed search')
|
||||
|
||||
def find_blocks_3d(self, *args, **kwargs):
|
||||
raise AssertionError('forced placement must skip local scan')
|
||||
|
||||
state = SleepWithBedStates(Munch(
|
||||
world=IndexedWorld(), pos=(0, 64, 0), time=13000,
|
||||
dimension='overworld'))
|
||||
state.force_new_bed = True
|
||||
|
||||
state.find_beds()
|
||||
|
||||
self.assertEqual(state.beds, [])
|
||||
self.assertEqual(state.state, state.choose_bed)
|
||||
|
||||
def test_bed_approach_follows_path_before_aiming_at_bed(self):
|
||||
bed = (4, 64, 2)
|
||||
opening = (3, 64, 0)
|
||||
state = SleepWithBedStates(Munch(
|
||||
pos=(0, 64, 0), path=[opening], look_at=bed,
|
||||
game=FakeGame(), world=FakeWorld()))
|
||||
state.area = bed
|
||||
state.opening = opening
|
||||
state.opening_deadline = 9999999999
|
||||
|
||||
state.going_to_bed()
|
||||
self.assertIsNone(state.g.look_at)
|
||||
|
||||
state.g.pos = opening
|
||||
state.going_to_bed()
|
||||
self.assertEqual(state.g.look_at, bed)
|
||||
self.assertEqual(state.state, state.turn_to_bed)
|
||||
|
||||
def test_bed_placement_approach_follows_path(self):
|
||||
opening = (3, 64, 0)
|
||||
state = SleepWithBedStates(Munch(
|
||||
pos=(0, 64, 0), path=[opening], look_at=(4, 64, 2),
|
||||
game=FakeGame(), world=FakeWorld()))
|
||||
state.area = (4, 64, 2)
|
||||
state.opening = opening
|
||||
state.opening_deadline = 9999999999
|
||||
|
||||
state.going_to_area()
|
||||
|
||||
self.assertIsNone(state.g.look_at)
|
||||
|
||||
def test_arrival_accepts_completed_path_with_small_position_error(self):
|
||||
state = SleepWithBedStates(Munch(
|
||||
pos=(0, 64, 0), path=[(1, 64, 0)], look_at=None,
|
||||
game=FakeGame(), world=FakeWorld()))
|
||||
state.opening = (1, 64, 0)
|
||||
state.opening_deadline = 9999999999
|
||||
|
||||
state.going_to_bed()
|
||||
|
||||
self.assertEqual(state.state, state.turn_to_bed)
|
||||
self.assertEqual(state.g.path, [])
|
||||
|
||||
def test_unconfirmed_sleep_retries_using_head_block(self):
|
||||
foot = (0, 64, 0)
|
||||
head = (0, 64, -1)
|
||||
bed_id = next(
|
||||
state for state in blocks.BED_IDS
|
||||
if blocks.PROPS[state].get('part') == 'foot')
|
||||
|
||||
class ThreatWorld(FakeWorld):
|
||||
def find_threats(self, center, distance):
|
||||
return []
|
||||
|
||||
game = FakeGame()
|
||||
state = SleepWithBedStates(Munch(
|
||||
time=13000, pos=(1, 64, 0), world=ThreatWorld(block=bed_id),
|
||||
game=game, path=[], look_at=None, correction_count=0))
|
||||
state.area = foot
|
||||
state.bed_head = head
|
||||
state.sleep_use_attempts = 1
|
||||
state.sleep_retry_at = 0
|
||||
state.sleep_deadline = 9999999999
|
||||
|
||||
state.sleep_bed()
|
||||
|
||||
self.assertEqual(game.placements, [(head, 1, 0, 0.5)])
|
||||
self.assertEqual(state.sleep_use_attempts, 2)
|
||||
|
||||
def test_failed_existing_bed_use_is_blacklisted(self):
|
||||
bed_id = next(iter(blocks.BED_IDS))
|
||||
|
||||
class ThreatWorld(FakeWorld):
|
||||
def find_threats(self, center, distance):
|
||||
return []
|
||||
|
||||
state = SleepWithBedStates(Munch(
|
||||
time=13000, pos=(1, 64, 0), world=ThreatWorld(block=bed_id),
|
||||
game=FakeGame(), path=[], look_at=None, correction_count=0))
|
||||
state.area = (0, 64, 0)
|
||||
state.sleep_use_attempts = 2
|
||||
state.sleep_retry_at = 9999999999
|
||||
state.sleep_deadline = 0
|
||||
|
||||
state.sleep_bed()
|
||||
|
||||
self.assertIn(state.area, state.bad_beds)
|
||||
self.assertEqual(state.state, state.cleanup)
|
||||
|
||||
def test_bed_waits_with_status_until_sleep_time(self):
|
||||
bed_id = next(iter(blocks.BED_IDS))
|
||||
state = SleepWithBedStates(Munch(
|
||||
time=12400, world=FakeWorld(block=bed_id), game=FakeGame(),
|
||||
path=[], look_at=None))
|
||||
state.area = (0, 64, 0)
|
||||
state.state = state.use_bed
|
||||
|
||||
state.use_bed()
|
||||
|
||||
self.assertEqual(state.state, state.use_bed)
|
||||
self.assertTrue(state.waiting_for_night)
|
||||
|
||||
def test_sleep_attempt_aborts_if_night_was_skipped_while_approaching(self):
|
||||
bed_id = next(iter(blocks.BED_IDS))
|
||||
world = FakeWorld(block=bed_id)
|
||||
state = SleepWithBedStates(Munch(
|
||||
time=13000, dimension='overworld', world=world,
|
||||
game=FakeGame(), path=[], look_at=None))
|
||||
state.init()
|
||||
state.area = (0, 64, 0)
|
||||
state.state = state.use_bed
|
||||
state.g.time = 25
|
||||
|
||||
state.use_bed()
|
||||
|
||||
self.assertEqual(state.state, state.cleanup)
|
||||
|
||||
def test_occupied_bed_is_abandoned_before_waiting_for_night(self):
|
||||
bed_id = next(iter(blocks.BED_IDS))
|
||||
|
||||
class OccupiedWorld(FakeWorld):
|
||||
@staticmethod
|
||||
def check_bed_occupied(_position):
|
||||
return True
|
||||
|
||||
state = SleepWithBedStates(Munch(
|
||||
time=13000, dimension='overworld',
|
||||
world=OccupiedWorld(block=bed_id), game=FakeGame(),
|
||||
path=[], look_at=None))
|
||||
state.init()
|
||||
state.area = (0, 64, 0)
|
||||
state.beds = [(2, 64, 0)]
|
||||
state.state = state.use_bed
|
||||
|
||||
state.use_bed()
|
||||
|
||||
self.assertEqual(state.state, state.choose_bed)
|
||||
|
||||
def test_daytime_sleep_aborts_cleanly(self):
|
||||
state = SleepWithBedStates(Munch(time=1000, dimension='overworld'))
|
||||
state.init()
|
||||
self.assertEqual(state.state, state.cleanup)
|
||||
|
||||
def test_placing_bed_uses_support_block_face_top(self):
|
||||
game = FakeGame()
|
||||
state = SleepWithBedStates(Munch(
|
||||
game=game, world=FakeWorld(), path=[], look_at=None,
|
||||
holding_hand=1))
|
||||
state.area = (4, 70, 5)
|
||||
|
||||
state.place_bed()
|
||||
|
||||
self.assertEqual(len(game.placements), 1)
|
||||
location, face, hand, cursor_y = game.placements[0]
|
||||
self.assertEqual(location, (4, 69, 5))
|
||||
self.assertEqual(int(face), 1)
|
||||
self.assertEqual(hand, 1)
|
||||
self.assertIsNone(cursor_y)
|
||||
self.assertTrue(state.my_bed)
|
||||
self.assertEqual(state.state, state.wait_use)
|
||||
|
||||
def test_wait_use_waits_for_delayed_chunk_update(self):
|
||||
bed_id = next(iter(blocks.BED_IDS))
|
||||
world = FakeWorld(block=blocks.AIR)
|
||||
state = SleepWithBedStates(Munch(
|
||||
game=FakeGame(), world=world, path=[], look_at=None))
|
||||
state.area = (4, 70, 5)
|
||||
state.my_bed = True
|
||||
state.bed_place_deadline = 9999999999
|
||||
state.state = state.wait_use
|
||||
|
||||
state.wait_use()
|
||||
self.assertEqual(state.state, state.wait_use)
|
||||
self.assertTrue(state.my_bed)
|
||||
|
||||
world.block = bed_id
|
||||
state.wait_use()
|
||||
self.assertEqual(state.state, state.use_bed)
|
||||
self.assertIsNotNone(state.bed_head)
|
||||
|
||||
def test_wait_use_aborts_after_update_timeout(self):
|
||||
state = SleepWithBedStates(Munch(
|
||||
game=FakeGame(), world=FakeWorld(block=blocks.AIR),
|
||||
path=[], look_at=None))
|
||||
state.area = (4, 70, 5)
|
||||
state.my_bed = True
|
||||
state.bed_place_deadline = 0
|
||||
|
||||
state.wait_use()
|
||||
|
||||
self.assertIn(state.area, state.bad_areas)
|
||||
self.assertFalse(state.my_bed)
|
||||
self.assertEqual(state.state, state.cleanup)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,64 @@
|
||||
import unittest
|
||||
from munch import Munch
|
||||
|
||||
from minecraft.networking.modern import ClientTickEnd, UseItemOnBlockPacket
|
||||
from minecraft.networking.types import BlockFace
|
||||
from mosfet.game import Game
|
||||
from mosfet.info import blocks
|
||||
from mosfet.protocol.modern import PlayerInputPacket
|
||||
|
||||
|
||||
class FakeConnection:
|
||||
def __init__(self):
|
||||
self.packets = []
|
||||
|
||||
def write_packet(self, packet, force=False):
|
||||
self.packets.append((packet, force))
|
||||
|
||||
|
||||
class SneakPlacementTests(unittest.TestCase):
|
||||
def test_open_container_sends_visible_face_and_hit_cursor(self):
|
||||
chest = (2, 65, -4)
|
||||
connection = FakeConnection()
|
||||
game = Game.__new__(Game)
|
||||
game.g = Munch(
|
||||
connection=connection,
|
||||
chunks=Munch(get_block_at=lambda *position:
|
||||
min(blocks.CHEST_IDS) if tuple(position) == chest
|
||||
else None),
|
||||
world=Munch())
|
||||
game.sequence = 0
|
||||
|
||||
game.open_container(
|
||||
chest, face=BlockFace.EAST, cursor=(0.9375, 0.5, 0.5))
|
||||
|
||||
packet = next(packet for packet, _force in connection.packets
|
||||
if isinstance(packet, UseItemOnBlockPacket))
|
||||
self.assertEqual(packet.location, chest)
|
||||
self.assertEqual(packet.face, BlockFace.EAST)
|
||||
self.assertEqual((packet.cursor_x, packet.cursor_y, packet.cursor_z),
|
||||
(0.9375, 0.5, 0.5))
|
||||
|
||||
def test_sneaking_wraps_block_placement_and_is_released(self):
|
||||
connection = FakeConnection()
|
||||
game = Game.__new__(Game)
|
||||
game.g = Munch(connection=connection)
|
||||
game.sequence = 0
|
||||
|
||||
game.place_block((3, 64, 7), 1, sneaking=True)
|
||||
|
||||
packets = [packet for packet, _force in connection.packets]
|
||||
self.assertEqual(len(packets), 6)
|
||||
self.assertIsInstance(packets[0], PlayerInputPacket)
|
||||
self.assertEqual(packets[0].flags, 0x20)
|
||||
self.assertIsInstance(packets[1], ClientTickEnd)
|
||||
self.assertIsInstance(packets[2], UseItemOnBlockPacket)
|
||||
self.assertEqual(packets[2].location, (3, 64, 7))
|
||||
self.assertIsInstance(packets[3], ClientTickEnd)
|
||||
self.assertIsInstance(packets[4], PlayerInputPacket)
|
||||
self.assertEqual(packets[4].flags, 0)
|
||||
self.assertIsInstance(packets[5], ClientTickEnd)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,111 @@
|
||||
import unittest
|
||||
|
||||
from munch import Munch
|
||||
|
||||
from mosfet.commands import Commands
|
||||
from mosfet.info import blocks, mobs
|
||||
from mosfet.job import JobStates
|
||||
from mosfet.jobs.check_threats import CheckThreatsStates
|
||||
from mosfet.world import World
|
||||
|
||||
|
||||
class FakeChunks:
|
||||
def __init__(self, solid=()):
|
||||
self.solid = set(solid)
|
||||
|
||||
def get_block_at(self, x, y, z):
|
||||
return blocks.STONE if (x, y, z) in self.solid else blocks.AIR
|
||||
|
||||
|
||||
class FakeChat:
|
||||
def __init__(self):
|
||||
self.handler = None
|
||||
self.messages = []
|
||||
|
||||
def set_handler(self, handler):
|
||||
self.handler = handler
|
||||
|
||||
def send(self, message):
|
||||
self.messages.append(message)
|
||||
|
||||
|
||||
class TestThreatDetection(unittest.TestCase):
|
||||
def test_find_threats_filters_passive_and_distant_entities(self):
|
||||
zombie = mobs.MOBS['minecraft:zombie']['protocol_id']
|
||||
villager = mobs.MOBS['minecraft:villager']['protocol_id']
|
||||
world = World(Munch(mobs={
|
||||
1: Munch(entity_id=1, type=zombie, x=3.2, y=64, z=0),
|
||||
2: Munch(entity_id=2, type=villager, x=2, y=64, z=0),
|
||||
3: Munch(entity_id=3, type=zombie, x=30, y=64, z=0),
|
||||
}))
|
||||
world.check_air_column = lambda pos, distance: True
|
||||
|
||||
result = world.find_threats((0, 64, 0), 12)
|
||||
|
||||
self.assertEqual([threat.entity_id for threat in result], [1])
|
||||
|
||||
def test_air_column_excludes_mobs_under_a_solid_roof(self):
|
||||
world = World(Munch(chunks=FakeChunks(solid={(0, 67, 0)})))
|
||||
self.assertFalse(world.check_air_column((0, 64, 0), 5))
|
||||
self.assertTrue(world.check_air_column((2, 64, 0), 5))
|
||||
|
||||
def test_threat_state_falls_back_to_reachable_clear_area(self):
|
||||
spot = (8, 64, 0)
|
||||
|
||||
class SafeWorld:
|
||||
def find_blocks_indexed(self, center, block_ids, distance=0):
|
||||
return []
|
||||
|
||||
def find_bed_areas(self, center, distance):
|
||||
return [spot]
|
||||
|
||||
def find_threats(self, center, distance):
|
||||
return []
|
||||
|
||||
def path_to_place(self, start, target):
|
||||
return [start, target]
|
||||
|
||||
g = Munch(world=SafeWorld(), pos=(0, 64, 0), path=[], look_at=None)
|
||||
state = CheckThreatsStates(g)
|
||||
state.state = state.find_safety
|
||||
state.threats = [Munch(entity_id=7)]
|
||||
|
||||
state.find_safety()
|
||||
|
||||
self.assertEqual(state.state, state.going_to_safety)
|
||||
self.assertEqual(state.safety, spot)
|
||||
self.assertFalse(state.external_safety)
|
||||
self.assertEqual(g.path[-1], spot)
|
||||
|
||||
g.pos = spot
|
||||
state.going_to_safety()
|
||||
self.assertEqual(state.state, state.wait)
|
||||
self.assertEqual(state.wait_time, 3)
|
||||
|
||||
def test_loiter_is_enabled_as_a_job(self):
|
||||
check = object()
|
||||
sleep = Munch(silent=False)
|
||||
eat = object()
|
||||
job = JobStates.__new__(JobStates)
|
||||
job.check_threats_states = check
|
||||
job.sleep_with_bed_states = sleep
|
||||
job.eat_food_states = eat
|
||||
|
||||
self.assertEqual(JobStates.loiter(job), [check, sleep, eat])
|
||||
self.assertTrue(sleep.silent)
|
||||
|
||||
def test_loiter_command_is_no_longer_rejected(self):
|
||||
def loiter():
|
||||
return []
|
||||
|
||||
chat = FakeChat()
|
||||
job = Munch(loiter=loiter, state=None)
|
||||
commands = Commands(Munch(name='mosfet1', chat=chat, job=job))
|
||||
commands.handle_chat(('CHAT', 'player-uuid', 'tanner: 1loiter'))
|
||||
|
||||
self.assertIs(job.state, loiter)
|
||||
self.assertEqual(chat.messages, ['ok'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,139 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import threading
|
||||
import unittest
|
||||
from munch import Munch
|
||||
|
||||
from mosfet.info import blocks
|
||||
from mosfet.protocol.types import Slot
|
||||
|
||||
|
||||
ENTRY = Path(__file__).resolve().parents[1] / 'mosfet.py'
|
||||
SPEC = importlib.util.spec_from_file_location('mosfet_web_entry', ENTRY)
|
||||
mosfet_web = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(mosfet_web)
|
||||
|
||||
|
||||
class FakeGame:
|
||||
def __init__(self):
|
||||
self.drop_calls = []
|
||||
self.dump_item = None
|
||||
self.dump_result = 2
|
||||
|
||||
def drop_inventory_slot(self, slot, whole_stack=True):
|
||||
self.drop_calls.append((slot, whole_stack))
|
||||
return True
|
||||
|
||||
def start_dump(self, item_id):
|
||||
self.dump_item = item_id
|
||||
return self.dump_result
|
||||
|
||||
|
||||
class TestWebInventoryAPI(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.g = mosfet_web.g
|
||||
self.original = {
|
||||
key: self.g.get(key) for key in
|
||||
('connected', 'game', 'inv', 'chest_viewers', 'time', 'time_base',
|
||||
'chunks', 'pos', 'yaw')
|
||||
}
|
||||
self.game = FakeGame()
|
||||
self.g.connected = True
|
||||
self.g.game = self.game
|
||||
self.g.inv = {
|
||||
9: Slot(True, 1145, 3,
|
||||
components={'custom_name': {'text': 'Test Paper'}})
|
||||
}
|
||||
self.g.reload_lock = threading.RLock()
|
||||
self.client = mosfet_web.app.test_client()
|
||||
|
||||
def tearDown(self):
|
||||
for key, value in self.original.items():
|
||||
self.g[key] = value
|
||||
|
||||
def test_inventory_api_exposes_slot_components(self):
|
||||
response = self.client.get('/api/global')
|
||||
self.assertEqual(response.status_code, 200)
|
||||
item = response.get_json()['inv']['9']
|
||||
self.assertEqual(item['components']['custom_name']['text'], 'Test Paper')
|
||||
|
||||
def test_minimap_api_returns_surface_blocks_centered_on_bot(self):
|
||||
grass = blocks.MCD_BLOCKS['grass_block']['minStateId']
|
||||
|
||||
class FakeChunk:
|
||||
sections = {
|
||||
0: {'non_empty_blocks': 1},
|
||||
1: {'non_empty_blocks': 0},
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def get_block_at(x, y, z):
|
||||
return grass if (x, y, z) == (1, 5, 1) else blocks.AIR
|
||||
|
||||
class FakeChunks:
|
||||
min_y = 0
|
||||
chunks = {(0, 0): FakeChunk()}
|
||||
|
||||
self.g.connected = True
|
||||
self.g.chunks = FakeChunks()
|
||||
self.g.pos = Munch(x=1.5, y=6.0, z=1.5)
|
||||
self.g.yaw = 90
|
||||
|
||||
response = self.client.get(
|
||||
'/api/minimap?radius=4&radius_x=6&radius_z=4')
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
data = response.get_json()
|
||||
self.assertTrue(data['ready'])
|
||||
self.assertEqual(data['center'], {'x': 1, 'y': 6, 'z': 1})
|
||||
self.assertEqual(data['yaw'], 90)
|
||||
self.assertEqual(data['radius_x'], 6)
|
||||
self.assertEqual(data['radius_z'], 4)
|
||||
self.assertEqual(len(data['cells']), 9)
|
||||
self.assertEqual(len(data['cells'][0]), 13)
|
||||
self.assertEqual(data['cells'][4][6], {'block': 'grass_block', 'y': 5})
|
||||
|
||||
def test_global_api_exposes_world_time_ticks(self):
|
||||
self.g.time = 12345.5
|
||||
self.g.time_base = 12345.5
|
||||
|
||||
response = self.client.get('/api/global')
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.get_json()['time'], 12345.5)
|
||||
self.assertEqual(response.get_json()['time_base'], 12345.5)
|
||||
|
||||
def test_global_api_stringifies_tuple_keys(self):
|
||||
self.g.chest_viewers = {(12, 64, -7): 1}
|
||||
|
||||
response = self.client.get('/api/global')
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.get_json()['chest_viewers'], {
|
||||
'(12, 64, -7)': 1,
|
||||
})
|
||||
|
||||
def test_drop_endpoint_supports_one_stack_and_matching_actions(self):
|
||||
one = self.client.post('/api/inventory/drop', json={
|
||||
'slot': 9, 'action': 'one'})
|
||||
stack = self.client.post('/api/inventory/drop', json={
|
||||
'slot': 9, 'action': 'stack'})
|
||||
matching = self.client.post('/api/inventory/drop', json={
|
||||
'slot': 9, 'action': 'matching'})
|
||||
|
||||
self.assertEqual(one.status_code, 200)
|
||||
self.assertEqual(stack.status_code, 200)
|
||||
self.assertEqual(matching.status_code, 200)
|
||||
self.assertEqual(self.game.drop_calls, [(9, False), (9, True)])
|
||||
self.assertEqual(self.game.dump_item, 1145)
|
||||
self.assertEqual(matching.get_json()['stacks'], 2)
|
||||
|
||||
def test_drop_endpoint_rejects_cross_origin_actions(self):
|
||||
response = self.client.post('/api/inventory/drop', json={
|
||||
'slot': 9, 'action': 'stack'},
|
||||
headers={'Origin': 'https://elsewhere.example'})
|
||||
self.assertEqual(response.status_code, 403)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,85 @@
|
||||
import io
|
||||
import unittest
|
||||
|
||||
from minecraft.networking.modern import (
|
||||
PaletteSection, SectionBlocksUpdatePacket,
|
||||
)
|
||||
from minecraft.networking.packets import PacketBuffer
|
||||
from minecraft.networking.types import Long, VarInt, VarLong
|
||||
|
||||
from mosfet.info import blocks
|
||||
from mosfet.protocol.managers import ChunkColumn, WorldState
|
||||
|
||||
|
||||
def encode_section_update(section_x, section_y, section_z, changes):
|
||||
"""Encode Prismarine's section-position and packed x:z:y records."""
|
||||
buffer = PacketBuffer()
|
||||
packed_section = (
|
||||
((section_x & 0x3FFFFF) << 42) |
|
||||
((section_z & 0x3FFFFF) << 20) |
|
||||
(section_y & 0xFFFFF))
|
||||
if packed_section >= (1 << 63):
|
||||
packed_section -= 1 << 64
|
||||
Long.send(packed_section, buffer)
|
||||
VarInt.send(len(changes), buffer)
|
||||
for x, y, z, block_id in changes:
|
||||
local = ((x & 0xF) << 8) | ((z & 0xF) << 4) | (y & 0xF)
|
||||
VarLong.send((block_id << 12) | local, buffer)
|
||||
packet = SectionBlocksUpdatePacket()
|
||||
packet.read(io.BytesIO(buffer.get_writable()))
|
||||
return packet
|
||||
|
||||
|
||||
class TestSectionBlockUpdates(unittest.TestCase):
|
||||
def test_negative_section_coordinates_and_local_yz_decode(self):
|
||||
bed_id = next(iter(blocks.BED_IDS))
|
||||
packet = encode_section_update(
|
||||
-11, 4, -20, [(3, 6, 9, bed_id)])
|
||||
|
||||
self.assertEqual(packet.id, 0x56)
|
||||
self.assertEqual(packet.changes, [(-173, 70, -311, bed_id)])
|
||||
|
||||
def test_unload_chunk_prunes_index_and_block_entities_safely(self):
|
||||
bed_id = next(iter(blocks.BED_IDS))
|
||||
inside = (1, 64, 1)
|
||||
outside = (17, 64, 1)
|
||||
world = WorldState()
|
||||
world.chunks[(0, 0)] = ChunkColumn(0, 0, [], world.min_section)
|
||||
world.index[bed_id] = {inside, outside}
|
||||
world.block_entities = {
|
||||
inside: {'type': 1, 'data': {}},
|
||||
outside: {'type': 1, 'data': {}},
|
||||
}
|
||||
|
||||
snapshot = world.indexed_positions({bed_id})
|
||||
world.unload_chunk(0, 0)
|
||||
|
||||
self.assertEqual(set(snapshot), {inside, outside})
|
||||
self.assertEqual(world.index[bed_id], {outside})
|
||||
self.assertEqual(set(world.block_entities), {outside})
|
||||
|
||||
def test_section_update_replaces_old_block_and_index_entry(self):
|
||||
section_x, section_y, section_z = -11, 4, -20
|
||||
x, y, z = -173, 70, -311
|
||||
bed_id = next(iter(blocks.BED_IDS))
|
||||
world = WorldState(min_y=section_y * 16)
|
||||
world.chunks[(section_x, section_z)] = ChunkColumn(
|
||||
section_x, section_z,
|
||||
[{'blocks': PaletteSection(0, [blocks.AIR], [], 4096)}],
|
||||
section_y)
|
||||
|
||||
placed = encode_section_update(
|
||||
section_x, section_y, section_z, [(x, y, z, bed_id)])
|
||||
world.handle_section_update(placed)
|
||||
self.assertEqual(world.get_block_at(x, y, z), bed_id)
|
||||
self.assertIn((x, y, z), world.index[bed_id])
|
||||
|
||||
broken = encode_section_update(
|
||||
section_x, section_y, section_z, [(x, y, z, blocks.AIR)])
|
||||
world.handle_section_update(broken)
|
||||
self.assertEqual(world.get_block_at(x, y, z), blocks.AIR)
|
||||
self.assertNotIn((x, y, z), world.index.get(bed_id, set()))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -1,88 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -eu
|
||||
|
||||
if [ ! -d "mosfet" ]
|
||||
then
|
||||
echo "You must run this from the mosfet-minecraft-bot directory."
|
||||
exit
|
||||
fi
|
||||
|
||||
if ! command -v virtualenv &> /dev/null
|
||||
then
|
||||
echo "virtualenv could not be found, please install with:"
|
||||
echo "sudo apt install virtualenv"
|
||||
exit
|
||||
fi
|
||||
|
||||
if ! command -v wget &> /dev/null
|
||||
then
|
||||
echo "wget could not be found, please install with:"
|
||||
echo "sudo apt install wget"
|
||||
exit
|
||||
fi
|
||||
|
||||
if ! command -v unzip &> /dev/null
|
||||
then
|
||||
echo "unzip could not be found, please install with:"
|
||||
echo "sudo apt install unzip"
|
||||
exit
|
||||
fi
|
||||
|
||||
if ! command -v python3 &> /dev/null
|
||||
then
|
||||
echo "python3 could not be found, please install with:"
|
||||
echo "sudo apt install python3"
|
||||
exit
|
||||
fi
|
||||
|
||||
if ! command -v pip3 &> /dev/null
|
||||
then
|
||||
echo "pip3 could not be found, please install with:"
|
||||
echo "sudo apt install pip3"
|
||||
exit
|
||||
fi
|
||||
|
||||
if ! command -v git &> /dev/null
|
||||
then
|
||||
echo "git could not be found, please install with:"
|
||||
echo "sudo apt install pip3"
|
||||
exit
|
||||
fi
|
||||
|
||||
|
||||
# download minecraft data
|
||||
|
||||
echo "Grabbing minecraft data..."
|
||||
|
||||
VERSION="1.16.4"
|
||||
|
||||
wget -Omcdata.zip "https://apimon.de/mcdata/$VERSION/$VERSION.zip"
|
||||
rm -r minecraft_data || true
|
||||
mkdir minecraft_data
|
||||
unzip mcdata.zip -d minecraft_data
|
||||
rm mcdata.zip
|
||||
|
||||
|
||||
# update code
|
||||
|
||||
git stash
|
||||
git pull --rebase
|
||||
git stash pop || true
|
||||
|
||||
|
||||
# https://github.com/pypa/virtualenv/issues/1029
|
||||
PS1=${PS1:-}
|
||||
|
||||
# create virtual environment
|
||||
|
||||
echo "Installing Python requirements..."
|
||||
|
||||
rm -r env || true
|
||||
rm -r __pycache__ || true
|
||||
virtualenv -p python3 env
|
||||
source env/bin/activate
|
||||
pip install -r requirements.txt
|
||||
|
||||
|
||||
echo "Done."
|
||||
@@ -10,6 +10,7 @@
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
/item_cache/
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const root = __dirname;
|
||||
const source = path.join(root, 'src');
|
||||
const build = path.join(root, 'build');
|
||||
|
||||
fs.rmSync(build, {recursive: true, force: true});
|
||||
fs.mkdirSync(path.join(build, 'static', 'css'), {recursive: true});
|
||||
fs.mkdirSync(path.join(build, 'static', 'js'), {recursive: true});
|
||||
fs.copyFileSync(path.join(source, 'index.html'), path.join(build, 'index.html'));
|
||||
fs.copyFileSync(path.join(source, 'dashboard.css'),
|
||||
path.join(build, 'static', 'css', 'dashboard.css'));
|
||||
fs.copyFileSync(path.join(source, 'dashboard.js'),
|
||||
path.join(build, 'static', 'js', 'dashboard.js'));
|
||||
const bundledIcons = path.join(root, 'item-icons');
|
||||
fs.cpSync(bundledIcons, path.join(build, 'static', 'item-icons'),
|
||||
{recursive: true});
|
||||
// Keep the standalone public entry synchronized for tools that serve it directly.
|
||||
fs.copyFileSync(path.join(source, 'index.html'),
|
||||
path.join(root, 'public', 'index.html'));
|
||||
console.log('Built static Mosfet dashboard into web_interface/build');
|
||||
@@ -1,17 +0,0 @@
|
||||
{
|
||||
"files": {
|
||||
"main.js": "/static/js/main.27336089.chunk.js",
|
||||
"main.js.map": "/static/js/main.27336089.chunk.js.map",
|
||||
"runtime-main.js": "/static/js/runtime-main.97b64705.js",
|
||||
"runtime-main.js.map": "/static/js/runtime-main.97b64705.js.map",
|
||||
"static/js/2.2b306052.chunk.js": "/static/js/2.2b306052.chunk.js",
|
||||
"static/js/2.2b306052.chunk.js.map": "/static/js/2.2b306052.chunk.js.map",
|
||||
"index.html": "/index.html",
|
||||
"static/js/2.2b306052.chunk.js.LICENSE.txt": "/static/js/2.2b306052.chunk.js.LICENSE.txt"
|
||||
},
|
||||
"entrypoints": [
|
||||
"static/js/runtime-main.97b64705.js",
|
||||
"static/js/2.2b306052.chunk.js",
|
||||
"static/js/main.27336089.chunk.js"
|
||||
]
|
||||
}
|
||||
@@ -1 +1,135 @@
|
||||
<!doctype html><html lang="en"><head><meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><meta name="theme-color" content="#000000"/><meta name="description" content="Web site created using create-react-app"/><title>React App</title></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><script>!function(e){function r(r){for(var n,f,i=r[0],l=r[1],a=r[2],p=0,s=[];p<i.length;p++)f=i[p],Object.prototype.hasOwnProperty.call(o,f)&&o[f]&&s.push(o[f][0]),o[f]=0;for(n in l)Object.prototype.hasOwnProperty.call(l,n)&&(e[n]=l[n]);for(c&&c(r);s.length;)s.shift()();return u.push.apply(u,a||[]),t()}function t(){for(var e,r=0;r<u.length;r++){for(var t=u[r],n=!0,i=1;i<t.length;i++){var l=t[i];0!==o[l]&&(n=!1)}n&&(u.splice(r--,1),e=f(f.s=t[0]))}return e}var n={},o={1:0},u=[];function f(r){if(n[r])return n[r].exports;var t=n[r]={i:r,l:!1,exports:{}};return e[r].call(t.exports,t,t.exports,f),t.l=!0,t.exports}f.m=e,f.c=n,f.d=function(e,r,t){f.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:t})},f.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},f.t=function(e,r){if(1&r&&(e=f(e)),8&r)return e;if(4&r&&"object"==typeof e&&e&&e.__esModule)return e;var t=Object.create(null);if(f.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:e}),2&r&&"string"!=typeof e)for(var n in e)f.d(t,n,function(r){return e[r]}.bind(null,n));return t},f.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return f.d(r,"a",r),r},f.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},f.p="/";var i=this.webpackJsonpweb_interface=this.webpackJsonpweb_interface||[],l=i.push.bind(i);i.push=r,i=i.slice();for(var a=0;a<i.length;a++)r(i[a]);var c=l;t()}([])</script><script src="/static/js/2.2b306052.chunk.js"></script><script src="/static/js/main.27336089.chunk.js"></script></body></html>
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#10130f" />
|
||||
<meta name="description" content="Live Minecraft bot dashboard" />
|
||||
<title>Mosfet · Minecraft Bot</title>
|
||||
<link rel="stylesheet" href="/static/css/dashboard.css?v=19" />
|
||||
<script defer src="/static/js/dashboard.js?v=19"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="shell">
|
||||
<main>
|
||||
<section class="hero panel">
|
||||
<div class="hero-main">
|
||||
<div class="eyebrow">LIVE SESSION <span class="eyebrow-line"></span></div>
|
||||
<h1 id="bot-name">Mosfet<span class="name-period">.</span></h1>
|
||||
<p id="session-subtitle" class="session-subtitle">Waiting for the bot connection</p>
|
||||
</div>
|
||||
<div class="hero-coordinates">
|
||||
<div class="coordinate-label">CURRENT POSITION</div>
|
||||
<div id="position" class="coordinate-value">—</div>
|
||||
<div id="dimension" class="dimension-value">NO DIMENSION</div>
|
||||
</div>
|
||||
<div class="hero-grid" aria-hidden="true"></div>
|
||||
<div class="hero-glow" aria-hidden="true"></div>
|
||||
</section>
|
||||
|
||||
<section class="stats-grid" aria-label="Bot status">
|
||||
<article class="stat-card panel">
|
||||
<div class="stat-top"><span class="stat-label">HEALTH</span><span class="stat-icon heart">♥</span></div>
|
||||
<div class="stat-value"><span id="health-value">—</span><small>/ 20</small></div>
|
||||
<div class="meter"><span id="health-meter" class="meter-fill health-fill"></span></div>
|
||||
</article>
|
||||
<article class="stat-card panel">
|
||||
<div class="stat-top"><span class="stat-label">HUNGER</span><span class="stat-icon food">◆</span></div>
|
||||
<div class="stat-value"><span id="food-value">—</span><small>/ 20</small></div>
|
||||
<div class="meter"><span id="food-meter" class="meter-fill food-fill"></span></div>
|
||||
<div id="food-saturation" class="stat-caption">Saturation —</div>
|
||||
</article>
|
||||
<article class="stat-card panel">
|
||||
<div class="stat-top"><span class="stat-label">MOVEMENT</span><span class="live-dot"></span></div>
|
||||
<div id="movement-value" class="stat-value stat-word">IDLE</div>
|
||||
<div id="movement-detail" class="stat-caption">No active path</div>
|
||||
</article>
|
||||
<article class="stat-card panel">
|
||||
<div class="stat-top"><span class="stat-label">WORLD CACHE</span><span class="stat-icon cache-icon">▦</span></div>
|
||||
<div class="stat-value"><span id="chunk-count">—</span><small> chunks</small></div>
|
||||
<div id="chunk-detail" class="stat-caption">Waiting for world data</div>
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<section class="content-grid">
|
||||
<section class="inventory-panel panel">
|
||||
<div class="section-heading">
|
||||
<div>
|
||||
<div class="eyebrow">PLAYER STORAGE</div>
|
||||
<h2>Inventory</h2>
|
||||
</div>
|
||||
<div class="inventory-summary">
|
||||
<span id="inventory-count">0 items</span>
|
||||
<span class="heading-divider"></span>
|
||||
<span id="inventory-slots">0 / 46 slots</span>
|
||||
</div>
|
||||
</div>
|
||||
<div id="inventory-warning" class="inventory-warning" hidden>
|
||||
Some item components are not decoded yet; displayed contents may be partial.
|
||||
</div>
|
||||
<div id="inventory-grid" class="inventory-grid" aria-label="Minecraft inventory"></div>
|
||||
<div class="inventory-legend"><span class="legend-swatch"></span> Empty slot <span class="legend-selected"></span> Selected hotbar slot <span class="legend-note">Hover for details · click an item for actions</span></div>
|
||||
</section>
|
||||
|
||||
<aside class="side-column">
|
||||
<section id="minimap-panel" class="side-panel panel minimap-panel">
|
||||
<div class="section-heading compact-heading">
|
||||
<div><div class="eyebrow">WORLD · SURFACE</div><h2>Minimap</h2></div>
|
||||
</div>
|
||||
<canvas id="minimap-canvas" class="minimap-canvas" width="320" height="240" role="img" aria-label="Surface map centered on the bot"></canvas>
|
||||
<div id="minimap-caption" class="minimap-caption">Waiting for world data</div>
|
||||
<div class="minimap-controls" aria-label="Minimap controls">
|
||||
<button id="minimap-zoom-out" type="button" aria-label="Zoom out" title="Zoom out">−</button>
|
||||
<button id="minimap-zoom-in" type="button" aria-label="Zoom in" title="Zoom in">+</button>
|
||||
<button id="minimap-north-lock" type="button" aria-label="Lock north to the top" aria-pressed="false" title="Lock north to the top">N ↑</button>
|
||||
<button id="minimap-size" type="button" aria-label="Enlarge minimap" aria-pressed="false" title="Enlarge minimap">⤢</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="side-panel panel">
|
||||
<div class="section-heading compact-heading">
|
||||
<div><div class="eyebrow">MULTIPLAYER</div><h2>Players</h2></div>
|
||||
<span id="player-count" class="count-badge">0</span>
|
||||
</div>
|
||||
<div id="player-list" class="player-list"><div class="empty-state">No player data yet</div></div>
|
||||
</section>
|
||||
|
||||
<section class="side-panel panel">
|
||||
<div class="section-heading compact-heading">
|
||||
<div><div class="eyebrow">AUTOMATION</div><h2>Runtime</h2></div>
|
||||
</div>
|
||||
<dl class="runtime-list">
|
||||
<div><dt>Game mode</dt><dd id="game-mode">—</dd></div>
|
||||
<div><dt>Time</dt><dd id="world-time">—</dd></div>
|
||||
<div><dt>Active job</dt><dd id="job-state">IDLE</dd></div>
|
||||
<div><dt>Path nodes</dt><dd id="path-length">0</dd></div>
|
||||
<div><dt>Entities</dt><dd id="entity-count">0 mobs · 0 drops</dd></div>
|
||||
<div><dt>AFK</dt><dd id="afk-state">NO</dd></div>
|
||||
</dl>
|
||||
<div id="movement-error" class="error-box" hidden></div>
|
||||
</section>
|
||||
</aside>
|
||||
</section>
|
||||
|
||||
<footer class="footer">
|
||||
<span class="footer-brand"><span class="footer-mark">■</span> MOSFET / 26.3</span>
|
||||
<span id="connection-pill" class="connection-pill is-offline"><i></i><span>OFFLINE</span></span>
|
||||
<span id="last-update">Waiting for API data</span>
|
||||
</footer>
|
||||
</main>
|
||||
</div>
|
||||
<div id="item-tooltip" class="item-tooltip" role="tooltip" hidden></div>
|
||||
<div id="inventory-menu" class="inventory-menu" role="menu" aria-label="Item actions" hidden>
|
||||
<div class="inventory-menu-heading">
|
||||
<strong id="inventory-menu-title">Item</strong>
|
||||
<span id="inventory-menu-meta"></span>
|
||||
</div>
|
||||
<button type="button" data-inventory-action="one" role="menuitem">Drop one</button>
|
||||
<button type="button" data-inventory-action="stack" role="menuitem">Drop whole stack</button>
|
||||
<button type="button" data-inventory-action="matching" role="menuitem">Drop all matching</button>
|
||||
<div id="inventory-menu-status" class="inventory-menu-status" aria-live="polite" hidden></div>
|
||||
<button type="button" class="menu-cancel" data-inventory-action="cancel" role="menuitem">Cancel</button>
|
||||
</div>
|
||||
<div id="toast" class="toast" role="status" aria-live="polite"></div>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
/*
|
||||
object-assign
|
||||
(c) Sindre Sorhus
|
||||
@license MIT
|
||||
*/
|
||||
|
||||
/** @license React v0.20.2
|
||||
* scheduler.production.min.js
|
||||
*
|
||||
* Copyright (c) Facebook, Inc. and its affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
/** @license React v17.0.2
|
||||
* react-dom.production.min.js
|
||||
*
|
||||
* Copyright (c) Facebook, Inc. and its affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
/** @license React v17.0.2
|
||||
* react-jsx-runtime.production.min.js
|
||||
*
|
||||
* Copyright (c) Facebook, Inc. and its affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
/** @license React v17.0.2
|
||||
* react.production.min.js
|
||||
*
|
||||
* Copyright (c) Facebook, Inc. and its affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
@@ -1,2 +0,0 @@
|
||||
(this.webpackJsonpweb_interface=this.webpackJsonpweb_interface||[]).push([[0],{41:function(e,t,n){"use strict";n.r(t);var c=n(2),r=n.n(c),s=n(14),a=n.n(s),i=n(4),j=n.n(i),l=n(15),d=n(16),o=n(5),p=n.n(o),b=n(0);p.a.defaults.baseURL=Object({NODE_ENV:"production",PUBLIC_URL:"",WDS_SOCKET_HOST:void 0,WDS_SOCKET_PATH:void 0,WDS_SOCKET_PORT:void 0,FAST_REFRESH:!0}).REACT_APP_SERVER;var u=function(){var e=Object(c.useState)(!1),t=Object(d.a)(e,2),n=t[0],r=t[1];return Object(c.useEffect)((function(){var e=setInterval(function(){var e=Object(l.a)(j.a.mark((function e(){var t;return j.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return e.prev=0,e.next=3,p.a.get("/api/global");case 3:t=e.sent,r(t.data),e.next=10;break;case 7:e.prev=7,e.t0=e.catch(0),r(!1);case 10:case"end":return e.stop()}}),e,null,[[0,7]])})));return function(){return e.apply(this,arguments)}}(),500);return function(){return clearInterval(e)}}),[]),Object(b.jsx)("div",{className:"app",children:n&&Object(b.jsxs)(b.Fragment,{children:[Object(b.jsxs)("p",{children:["Name: ",n.name]}),Object(b.jsxs)("p",{children:["Pos: ",n.pos]}),Object(b.jsxs)("p",{children:["Yaw: ",n.yaw]}),Object(b.jsxs)("p",{children:["Pitch: ",n.pitch]}),Object(b.jsxs)("p",{children:["Dimention: ",n.dimension]}),Object(b.jsxs)("p",{children:["Players:",Object.values(n.players).map((function(e){return Object(b.jsx)("div",{children:n.player_names[e.player_uuid]})}))]}),Object(b.jsxs)("p",{children:["Holding: ",n.holding]}),Object(b.jsxs)("p",{children:["AFK: ","".concat(n.afk)]}),Object(b.jsxs)("p",{children:["Health: ",n.health]}),Object(b.jsxs)("p",{children:["Food: ",n.food]}),Object(b.jsxs)("p",{children:["Time: ",n.time]})]})})};a.a.render(Object(b.jsx)(r.a.StrictMode,{children:Object(b.jsx)(u,{})}),document.getElementById("root"))}},[[41,1,2]]]);
|
||||
//# sourceMappingURL=main.27336089.chunk.js.map
|
||||
@@ -1 +0,0 @@
|
||||
{"version":3,"sources":["App.js","index.js"],"names":["axios","defaults","baseURL","process","REACT_APP_SERVER","App","useState","global","setGlobal","useEffect","interval","setInterval","a","get","res","data","clearInterval","className","name","pos","yaw","pitch","dimension","Object","values","players","map","x","player_names","player_uuid","holding","afk","health","food","time","ReactDOM","render","StrictMode","document","getElementById"],"mappings":"kNAGAA,IAAMC,SAASC,QAAUC,mIAAYC,iBAiDtBC,MA/Cf,WAAgB,IAAD,EACcC,oBAAS,GADvB,mBACPC,EADO,KACCC,EADD,KAiBd,OAdAC,qBAAU,WACT,IASMC,EAAWC,YATR,uCAAG,4BAAAC,EAAA,+EAEQZ,IAAMa,IAAI,eAFlB,OAEJC,EAFI,OAGVN,EAAUM,EAAIC,MAHJ,gDAKVP,GAAU,GALA,yDAAH,qDASyB,KAClC,OAAO,kBAAMQ,cAAcN,MACzB,IAGF,qBAAKO,UAAU,MAAf,SACEV,GACA,qCACC,uCAAUA,EAAOW,QACjB,sCAASX,EAAOY,OAChB,sCAASZ,EAAOa,OAChB,wCAAWb,EAAOc,SAElB,4CAAed,EAAOe,aAEtB,yCACEC,OAAOC,OAAOjB,EAAOkB,SAASC,KAAI,SAAAC,GAAC,OACnC,8BACEpB,EAAOqB,aAAaD,EAAEE,qBAK1B,0CAAatB,EAAOuB,WACpB,gDAAYvB,EAAOwB,QACnB,yCAAYxB,EAAOyB,UACnB,uCAAUzB,EAAO0B,QACjB,uCAAU1B,EAAO2B,cCzCtBC,IAASC,OACR,cAAC,IAAMC,WAAP,UACC,cAAC,EAAD,MAEDC,SAASC,eAAe,W","file":"static/js/main.27336089.chunk.js","sourcesContent":["import React, { useState, useEffect } from 'react';\nimport axios from 'axios';\n\naxios.defaults.baseURL = process.env.REACT_APP_SERVER;\n\nfunction App() {\n\tconst [global, setGlobal] = useState(false);\n\n\tuseEffect(() => {\n\t\tconst get = async() => {\n\t\t\ttry {\n\t\t\t\tconst res = await axios.get('/api/global');\n\t\t\t\tsetGlobal(res.data);\n\t\t\t} catch (error) {\n\t\t\t\tsetGlobal(false);\n\t\t\t}\n\t\t};\n\n\t\tconst interval = setInterval(get, 500);\n\t\treturn () => clearInterval(interval);\n\t}, []);\n\n\treturn (\n\t\t<div className=\"app\">\n\t\t\t{global &&\n\t\t\t\t<>\n\t\t\t\t\t<p>Name: {global.name}</p>\n\t\t\t\t\t<p>Pos: {global.pos}</p>\n\t\t\t\t\t<p>Yaw: {global.yaw}</p>\n\t\t\t\t\t<p>Pitch: {global.pitch}</p>\n\n\t\t\t\t\t<p>Dimention: {global.dimension}</p>\n\n\t\t\t\t\t<p>Players:\n\t\t\t\t\t\t{Object.values(global.players).map(x =>\n\t\t\t\t\t\t\t<div>\n\t\t\t\t\t\t\t\t{global.player_names[x.player_uuid]}\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t)}\n\t\t\t\t\t</p>\n\n\t\t\t\t\t<p>Holding: {global.holding}</p>\n\t\t\t\t\t<p>AFK: {`${global.afk}`}</p>\n\t\t\t\t\t<p>Health: {global.health}</p>\n\t\t\t\t\t<p>Food: {global.food}</p>\n\t\t\t\t\t<p>Time: {global.time}</p>\n\t\t\t\t</>\n\t\t\t}\n\t\t</div>\n\t);\n}\n\nexport default App;\n","import React from 'react';\nimport ReactDOM from 'react-dom';\nimport App from './App';\n\nReactDOM.render(\n\t<React.StrictMode>\n\t\t<App />\n\t</React.StrictMode>,\n\tdocument.getElementById('root')\n);\n"],"sourceRoot":""}
|
||||
@@ -1,2 +0,0 @@
|
||||
!function(e){function r(r){for(var n,f,i=r[0],l=r[1],a=r[2],p=0,s=[];p<i.length;p++)f=i[p],Object.prototype.hasOwnProperty.call(o,f)&&o[f]&&s.push(o[f][0]),o[f]=0;for(n in l)Object.prototype.hasOwnProperty.call(l,n)&&(e[n]=l[n]);for(c&&c(r);s.length;)s.shift()();return u.push.apply(u,a||[]),t()}function t(){for(var e,r=0;r<u.length;r++){for(var t=u[r],n=!0,i=1;i<t.length;i++){var l=t[i];0!==o[l]&&(n=!1)}n&&(u.splice(r--,1),e=f(f.s=t[0]))}return e}var n={},o={1:0},u=[];function f(r){if(n[r])return n[r].exports;var t=n[r]={i:r,l:!1,exports:{}};return e[r].call(t.exports,t,t.exports,f),t.l=!0,t.exports}f.m=e,f.c=n,f.d=function(e,r,t){f.o(e,r)||Object.defineProperty(e,r,{enumerable:!0,get:t})},f.r=function(e){"undefined"!==typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},f.t=function(e,r){if(1&r&&(e=f(e)),8&r)return e;if(4&r&&"object"===typeof e&&e&&e.__esModule)return e;var t=Object.create(null);if(f.r(t),Object.defineProperty(t,"default",{enumerable:!0,value:e}),2&r&&"string"!=typeof e)for(var n in e)f.d(t,n,function(r){return e[r]}.bind(null,n));return t},f.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return f.d(r,"a",r),r},f.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},f.p="/";var i=this.webpackJsonpweb_interface=this.webpackJsonpweb_interface||[],l=i.push.bind(i);i.push=r,i=i.slice();for(var a=0;a<i.length;a++)r(i[a]);var c=l;t()}([]);
|
||||
//# sourceMappingURL=runtime-main.97b64705.js.map
|
||||
|
After Width: | Height: | Size: 932 B |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 1.0 KiB |
|
After Width: | Height: | Size: 580 B |
|
After Width: | Height: | Size: 3.7 KiB |
|
After Width: | Height: | Size: 2.6 KiB |
|
After Width: | Height: | Size: 781 B |
|
After Width: | Height: | Size: 4.6 KiB |
|
After Width: | Height: | Size: 4.3 KiB |
|
After Width: | Height: | Size: 5.4 KiB |
|
After Width: | Height: | Size: 2.2 KiB |
|
After Width: | Height: | Size: 873 B |
|
After Width: | Height: | Size: 3.4 KiB |
|
After Width: | Height: | Size: 721 B |