2027 冬日绘版 py 代码

· · 休闲·娱乐

:::info[code]

"""Bounded-concurrency Painter client.

Assumptions to verify with the service operator:
- The protocol accepts several (slot, paint_token) binds in one WebSocket packet.
- The operator-approved limits are 50 token requests/second and 50 open WebSockets.
- MAX_TOKENS_PER_WS is within the server's per-connection slot limit.

This file keeps a single WebSocket per group of painters, batches binds, and batches
paint requests that arrive close together. Token HTTP requests remain one request per
UID/access_key because /api/paint-token is a single-credential endpoint.
"""

from PIL import Image

import asyncio
import hashlib
import http.client
import json
import os
import random
import struct
import time
import urllib.error
import urllib.request
import uuid
from dataclasses import dataclass
from typing import Optional

from compression import zstd
import numpy as np
import websockets


# ============================================================
# Configuration
# ============================================================

MODE = "none"  # "none" or "access_key" 身份来源:none 用 UID,access_key 用本地 key。
SERVER = "https://pb.ika.zip"
CACHE_PAINT_TOKENS_FILE = "D:/WP/json/WP-v2.3_paint_tokens.json"
ACCESS_KEYS_FILE = "D:/WP/json/access_keys.json"
IMAGE_FILE = "D:/WP/img/acat.png"
# 服务器、token 缓存、key 文件、图片文件的位置。

X, Y = 350, 450
W, H = 300, 150
#   图片在画布上的位置和缩放尺寸;这里绘制区域是从 (200, 0) 开始的 100×100 图片。
BIG_ROWS, BIG_COLS = 40, 40 # 大区网格;40×40 对应 1600 个 Painter。
SMALL_ROWS, SMALL_COLS = 2, 2 # 受袭时每个大区切成 2×2 小区。

ATTACK_THRESHOLD = 6 # 观测到的异色像素数严格大于 6 才算受袭,也就是至少 7 个已观测异色像素。
RECOVER_THRESHOLD = 2 # 受袭区低于 2 后开始计时;持续 10 秒才恢复常态。
RECOVER_DURATION = 10.0 #   救援 Painter 与受袭区之间允许的最大大区网格曼哈顿距离。
SCHEDULER_INTERVAL = 0.5 #
MAX_SUPPORT_DISTANCE = 5 
MAX_SUPPORT_PER_ATTACK = SMALL_ROWS * SMALL_COLS - 1 #  每个受袭区最多 3 名支援者;因为 2×2 小区最多分给 4 人,包含负责人。
DISTANCE_WEIGHT = 10.0 # 下面是拍卖权重
HOME_DAMAGE_WEIGHT = 2.0
ATTACK_PRIORITY_WEIGHT = 0.5
STICKY_BONUS = 20.0
GROWTH_LOOKAHEAD = 3.0
PATROL_INTERVAL = 0.05

# Explicit load-test bounds provided for this test.
MAX_TOKEN_RPS = 50 # 只影响缺少 token 或刷新 token 时的 HTTP 请求;缓存已有 1600 个时,启动阶段基本不走这部分。
MAX_TOKEN_IN_FLIGHT = 50 # 同上
MAX_WS_CONNECTIONS = 8000  # 同时允许打开的连接数,不是实际要开的连接数。你只需 200 个;设 8000 不会自动多开。
WS_CONNECT_RPS = 1280        # 每秒新建多少个 WebSocket 连接;目前为 1。
TOKENS_PER_WS = 1600       # 每条连接绑定多少个 Painter;
WS_START_INTERVAL = 1.0 / WS_CONNECT_RPS #  由启动速率算出的间隔;如果代码实际用 StartRateLimiter(WS_CONNECT_RPS),这个变量本身不会生效。
PAINT_BATCH_WINDOW = 0.010 # 同一连接等待 10 毫秒,把同时到来的绘制请求合成一批。
HTTP_TIMEOUT = 20 # token HTTP 请求超时时间。

COOLING = 1
STATUS = {
    0: "OK",
    1: "COOLING",
    2: "NO_PAINT_TOKEN",
    3: "BAD_PAINT_TOKEN",
    4: "BANNED",
    5: "CLOSED",
    6: "IP_LIMIT",
}

BOARD_WIDTH = 0
BOARD_HEIGHT = 0


# ============================================================
# Wire helpers
# ============================================================

def pad4(n: int) -> int:
    return (n + 3) & ~3


def rgb_to_color(r: int, g: int, b: int) -> int:
    return (b << 16) | (g << 8) | r | 0xFF000000


def encode_batch(
    binds: list[tuple[int, bytes]],
    paints: list[tuple[int, int, int]],
) -> bytes:
    nb, np_ = len(binds), len(paints)
    out = bytearray(struct.pack("<BBHIII", 0x01, 1, 0, nb, np_, 0))
    out += struct.pack(f"<{nb}H", *(slot for slot, _ in binds)).ljust(
        pad4(2 * nb), b"\0"
    )
    out += b"".join(token for _, token in binds)
    out += struct.pack(f"<{np_}H", *(slot for slot, _, _ in paints)).ljust(
        pad4(2 * np_), b"\0"
    )
    out += struct.pack(f"<{np_}I", *(idx for _, idx, _ in paints))
    out += struct.pack(f"<{np_}I", *(color for _, _, color in paints))
    return zstd.compress(bytes(out))


def u32(buf: bytes, off: int, count: int) -> np.ndarray:
    return np.frombuffer(buf, dtype="<u4", count=count, offset=off)


# ============================================================
# Token HTTP requests: one access_key per request, bounded at 50/s
# ============================================================

class StartRateLimiter:
    def __init__(self, rate_per_second: float):
        self.interval = 1.0 / rate_per_second
        self.lock = asyncio.Lock()
        self.next_start = 0.0

    async def acquire(self) -> None:
        async with self.lock:
            now = time.monotonic()
            delay = self.next_start - now
            if delay > 0:
                await asyncio.sleep(delay)
            self.next_start = max(now, self.next_start) + self.interval


TOKEN_RATE_LIMITER = StartRateLimiter(MAX_TOKEN_RPS)
TOKEN_SEMAPHORE = asyncio.Semaphore(MAX_TOKEN_IN_FLIGHT)


def _request_paint_token_sync(server: str, mode: str, identity) -> str:
    url = server.rstrip("/") + "/api/paint-token"
    body = {"uid": identity} if mode == "none" else {"access_key": identity}
    req = urllib.request.Request(
        url,
        data=json.dumps(body).encode("utf-8"),
        headers={
            "Content-Type": "application/json",
            "User-Agent": "curl/8.10.1",
        },
        method="POST",
    )
    try:
        with urllib.request.urlopen(req, timeout=HTTP_TIMEOUT) as response:
            result = json.loads(response.read().decode("utf-8"))
    except urllib.error.HTTPError as exc:
        detail = exc.read().decode("utf-8", errors="replace")
        raise RuntimeError(f"token API HTTP {exc.code}: {detail}") from exc
    except (urllib.error.URLError, http.client.RemoteDisconnected, TimeoutError) as exc:
        raise RuntimeError(f"token API network error: {exc}") from exc

    token = result.get("paint_token") if isinstance(result, dict) else None
    if not isinstance(token, str) or not token:
        raise RuntimeError(f"token API response has no paint_token: {result!r}")
    return token


async def request_paint_token(server: str, mode: str, identity) -> str:
    # Retries are paced by the same global rate limiter.
    last_error = None
    for attempt in range(3):
        async with TOKEN_SEMAPHORE:
            # Acquire the rate slot only after an in-flight slot is available,
            # so queued requests cannot burst after a slow response frees capacity.
            await TOKEN_RATE_LIMITER.acquire()
            try:
                return await asyncio.to_thread(
                    _request_paint_token_sync, server, mode, identity
                )
            except Exception as exc:
                last_error = exc
        if attempt < 2:
            await asyncio.sleep(0.5 * (2 ** attempt))
    raise RuntimeError(f"token request failed after 3 attempts: {last_error}")


async def request_missing_tokens(server, mode, identities, existing, cache):
    # Launch individual requests concurrently; the shared limiter and semaphore
    # cap starts at 50/s and in-flight requests at 50.
    tokens: list[Optional[str]] = list(existing[:len(identities)])
    tokens.extend([None] * (len(identities) - len(tokens)))
    cache_lock = asyncio.Lock()
    errors = []

    async def fetch_one(index):
        print(f"[TOKEN] queued {index + 1}/{len(identities)}")
        try:
            token = await request_paint_token(server, mode, identities[index])
            async with cache_lock:
                tokens[index] = token
                # Keep successful results by index, including gaps, so a failed
                # run can resume without re-requesting completed credentials.
                save_token_cache(tokens, cache["signature"])
            print(f"[TOKEN] completed {index + 1}/{len(identities)}")
        except Exception as exc:
            errors.append((index, exc))

    tasks = [
        asyncio.create_task(fetch_one(i))
        for i, token in enumerate(tokens)
        if token is None
    ]
    await asyncio.gather(*tasks)

    if errors:
        i, exc = errors[0]
        raise RuntimeError(f"token request failed for entry {i + 1}: {exc}") from exc
    if any(token is None for token in tokens):
        raise RuntimeError("token request set ended with missing entries")
    return tokens


# ============================================================
# Token cache and access_keys JSON
# ============================================================

def cache_signature(server: str, mode: str, identities: list) -> str:
    raw = json.dumps([server, mode, identities], ensure_ascii=False, sort_keys=True)
    return hashlib.sha256(raw.encode("utf-8")).hexdigest()


def load_token_cache(signature: str) -> list[str]:
    try:
        with open(CACHE_PAINT_TOKENS_FILE, "r", encoding="utf-8") as f:
            data = json.load(f)
    except FileNotFoundError:
        return []
    except (json.JSONDecodeError, OSError) as exc:
        print(f"[CACHE] token cache unreadable; starting empty: {exc}")
        return []

    if data.get("signature") != signature:
        print("[CACHE] credentials/config changed; starting a fresh token cache")
        return []
    tokens = data.get("tokens")
    return tokens if isinstance(tokens, list) else []


def save_token_cache(tokens: list[str], signature: str) -> None:
    path = CACHE_PAINT_TOKENS_FILE
    parent = os.path.dirname(path)
    if parent:
        os.makedirs(parent, exist_ok=True)
    tmp = path + ".tmp"
    with open(tmp, "w", encoding="utf-8") as f:
        json.dump({"signature": signature, "tokens": tokens}, f, ensure_ascii=False)
    os.replace(tmp, path)


def load_access_keys(path: str = ACCESS_KEYS_FILE) -> list[str]:
    with open(path, "r", encoding="utf-8") as f:
        data = json.load(f)
    keys = data.get("access_keys") if isinstance(data, dict) else None
    if not isinstance(keys, list) or not keys:
        raise ValueError(f"{path}: expected {{\"access_keys\": [ ... ]}}")
    if any(not isinstance(k, str) or not k.strip() for k in keys):
        raise ValueError("access_keys must contain non-empty strings")
    keys = [k.strip() for k in keys]
    if len(set(keys)) != len(keys):
        raise ValueError("access_keys contains duplicates")
    return keys


# ============================================================
# Shared view and region model
# ============================================================

class SharedView:
    def __init__(self, ttl=10.0):
        self.ttl = ttl
        self.data: dict[int, tuple[int, float]] = {}

    def update(self, pix: int, color: int) -> None:
        self.data[pix] = (color, time.monotonic())

    def get(self, pix: int) -> Optional[int]:
        item = self.data.get(pix)
        if item is None:
            return None
        color, timestamp = item
        if time.monotonic() - timestamp > self.ttl:
            self.data.pop(pix, None)
            return None
        return color


@dataclass
class PaintTask:
    rect: tuple[int, int, int, int]
    image: np.ndarray
    region: object
    random_mode: bool = False
    sample_rects: tuple = ()

    def signature(self):
        return self.rect, self.region.id, self.random_mode, self.sample_rects


class Region:
    def __init__(self, rect, image, seen, region_id, grid_x, grid_y):
        self.id = region_id
        self.rect = rect
        self.image = image
        self.seen = seen
        self.grid_x = grid_x
        self.grid_y = grid_y
        self.main_painter = None
        self.damage = 0
        self.growth = 0.0
        self.last_damage = 0
        self.last_measure_time = time.monotonic()
        self.attacked = False
        self.recovery_since = None
        self.last_paint_idx = None

    def distance(self, other) -> int:
        return abs(self.grid_x - other.grid_x) + abs(self.grid_y - other.grid_y)

    def make_task(self, rect, random_mode=False):
        x, y, w, h = rect
        x0, y0, _, _ = self.rect
        subimage = self.image[y - y0:y - y0 + h, x - x0:x - x0 + w]
        return PaintTask(rect, subimage, self, random_mode)

    def split(self, rows, cols):
        x, y, w, h = self.rect
        tasks = []
        for i in range(rows):
            y1, y2 = h * i // rows, h * (i + 1) // rows
            for j in range(cols):
                x1, x2 = w * j // cols, w * (j + 1) // cols
                tasks.append(self.make_task((x + x1, y + y1, x2 - x1, y2 - y1)))
        return tasks

    def refresh_damage(self):
        global BOARD_WIDTH
        if BOARD_WIDTH <= 0:
            return
        x0, y0, w, h = self.rect
        count = 0
        for y in range(h):
            for x in range(w):
                idx = (y0 + y) * BOARD_WIDTH + x0 + x
                seen_color = self.seen.get(idx)
                if seen_color is None:
                    continue
                r, g, b = map(int, self.image[y, x])
                if seen_color != rgb_to_color(r, g, b):
                    count += 1
        now = time.monotonic()
        dt = now - self.last_measure_time
        if dt > 0:
            self.growth = max(0.0, (count - self.last_damage) / dt)
        self.last_damage = count
        self.last_measure_time = now
        self.damage = count

    def update_state(self, now):
        if not self.attacked:
            if self.damage > ATTACK_THRESHOLD:
                self.attacked = True
                self.recovery_since = None
                print(f"[ATTACK] Region {self.id}, damage={self.damage}, growth={self.growth:.2f}")
            return
        if self.damage < RECOVER_THRESHOLD:
            if self.recovery_since is None:
                self.recovery_since = now
            elif now - self.recovery_since >= RECOVER_DURATION:
                self.attacked = False
                self.recovery_since = None
                print(f"[RECOVERED] Region {self.id}")
        else:
            self.recovery_since = None


# ============================================================
# Painter; several Painters share one GroupConnection
# ============================================================

class Painter:
    def __init__(self, painter_id, identity, mode, paint_token, seen, token_index):
        self.id = painter_id
        self.identity = identity
        self.mode_type = mode
        self.paint_token = paint_token
        self.token_index = token_index
        self.seen = seen
        self.home_region = None
        self.group = None
        self.slot = None
        self.rules = {}
        self.brush = None
        self.clock_offset = 0.0
        self.radius = 0
        self.tasks = []
        self.generation = 0
        self.changed = asyncio.Event()
        self.idle = asyncio.Event()
        self.idle.set()
        self.mode = "idle"
        self.last_paint_idx = None

    def task_signature(self):
        return tuple(task.signature() for task in self.tasks)

    def pause(self):
        self.tasks = []
        self.generation += 1
        self.changed.set()

    async def wait_idle(self):
        await self.idle.wait()

    def install_tasks(self, tasks):
        self.tasks = tasks
        self.generation += 1
        self.changed.set()

    def get_idx(self, x, y):
        return y * self.rules["w"] + x

    def get_color(self, task, idx):
        x0, y0, _, _ = task.rect
        x, y = idx % self.rules["w"], idx // self.rules["w"]
        r, g, b = map(int, task.image[y - y0, x - x0])
        return rgb_to_color(r, g, b)

    def targets(self, task):
        x0, y0, w, h = task.rect
        for row in range(h):
            cols = range(w) if row % 2 == 0 else range(w - 1, -1, -1)
            for col in cols:
                yield (y0 + row) * self.rules["w"] + x0 + col

    def wait_seconds(self, idx):
        if self.brush is None:
            return 0.0
        brush_idx, timestamp = self.brush
        board_w = self.rules["w"]
        distance = abs(idx % board_w - brush_idx % board_w) + abs(idx // board_w - brush_idx // board_w)
        ready = (timestamp + self.rules["c0"] + self.rules["k"] * distance) / 1e6
        return max(0.0, ready - (time.time() + self.clock_offset))

    async def refresh_token_and_bind(self):
        print(f"[TOKEN-REFRESH] Painter {self.id}: requesting replacement")
        new_token = await request_paint_token(SERVER, self.mode_type, self.identity)
        status, value = await self.group.bind_one(self.slot, uuid.UUID(new_token).bytes)
        if status != 0:
            raise RuntimeError(f"Painter {self.id}: replacement bind failed: {STATUS.get(status, status)}")
        self.paint_token = new_token
        self.group.manager.tokens[self.token_index] = new_token
        async with self.group.manager.cache_lock:
            save_token_cache(self.group.manager.tokens, self.group.manager.signature)
        print(f"[TOKEN-REFRESH] Painter {self.id}: replacement bound")

    async def paint_one(self, idx, color, gen, region):
        while gen == self.generation:
            wait = self.wait_seconds(idx)
            if wait > 0:
                try:
                    await asyncio.wait_for(self.changed.wait(), timeout=min(wait, 0.25))
                except asyncio.TimeoutError:
                    pass
                continue
            if gen != self.generation:
                return False

            status, value = await self.group.paint(self.slot, idx, color)
            if gen != self.generation:
                return False
            if status == COOLING:
                await asyncio.sleep(value / 1e6)
                continue
            if status in (2, 3):
                await self.refresh_token_and_bind()
                continue
            if status != 0:
                raise RuntimeError(f"Painter {self.id} paint rejected: {STATUS.get(status, status)}")

            self.last_paint_idx = idx
            region.last_paint_idx = idx
            self.seen.update(idx, color)
            return True
        return False

    async def run_random_task(self, task, gen):
        rects = task.sample_rects or (task.rect,)
        total = sum(w * h for _, _, w, h in rects)
        if total <= 0:
            return

        # Pick one pixel uniformly from the healthy portions of this patrol block.
        offset = random.randrange(total)
        px = py = None
        for x, y, w, h in rects:
            area = w * h
            if offset < area:
                px = x + offset % w
                py = y + offset // w
                break
            offset -= area

        if px is None or py is None:
            return

        idx = self.get_idx(px, py)
        color = self.get_color(task, idx)
        if self.seen.get(idx) != color:
            await self.paint_one(idx, color, gen, task.region)

    async def worker_loop(self):
        while True:
            if not self.tasks:
                self.mode = "idle"
                self.idle.set()
                self.changed.clear()
                if self.tasks:
                    continue
                await self.changed.wait()
                continue

            self.idle.clear()
            gen, tasks = self.generation, self.tasks
            self.changed.clear()
            self.mode = "working"

            for task in tasks:
                if gen != self.generation:
                    break
                if task.random_mode:
                    await self.run_random_task(task, gen)
                    continue
                for idx in self.targets(task):
                    if gen != self.generation:
                        break
                    color = self.get_color(task, idx)
                    if self.seen.get(idx) == color:
                        continue
                    await self.paint_one(idx, color, gen, task.region)

            self.idle.set()
            if gen == self.generation:
                await asyncio.sleep(PATROL_INTERVAL)


# ============================================================
# One WebSocket carries multiple token slots and batched paints
# ============================================================

class GroupConnection:
    def __init__(self, manager, painters):
        self.manager = manager
        self.painters = painters
        self.ws = None
        self.rules_ready = asyncio.Event()
        self.request_lock = asyncio.Lock()
        self.pending_response = None
        self.paint_queue = asyncio.Queue()
        self.batch_task = None

        for slot, painter in enumerate(painters):
            painter.group = self
            painter.slot = slot

    async def _request_packet(self, binds, paints, expected):
        async with self.request_lock:
            loop = asyncio.get_running_loop()
            future = loop.create_future()
            self.pending_response = (future, expected)
            await self.ws.send(encode_batch(binds, paints))
            try:
                return await asyncio.wait_for(future, timeout=30)
            finally:
                if self.pending_response and self.pending_response[0] is future:
                    self.pending_response = None

    async def bind_all(self):
        binds = [(p.slot, uuid.UUID(p.paint_token).bytes) for p in self.painters]
        results = await self._request_packet(binds, [], len(binds))
        for painter, (status, _) in zip(self.painters, results):
            if status in (2, 3):
                await painter.refresh_token_and_bind()
            elif status != 0:
                raise RuntimeError(f"Painter {painter.id} bind failed: {STATUS.get(status, status)}")

    async def bind_one(self, slot, token_bytes):
        results = await self._request_packet([(slot, token_bytes)], [], 1)
        return results[0]

    async def paint(self, slot, idx, color):
        loop = asyncio.get_running_loop()
        future = loop.create_future()
        await self.paint_queue.put((slot, idx, color, future))
        return await future

    async def paint_batch_loop(self):
        while True:
            first = await self.paint_queue.get()
            batch = [first]
            deadline = time.monotonic() + PAINT_BATCH_WINDOW
            while len(batch) < len(self.painters):
                remaining = deadline - time.monotonic()
                if remaining <= 0:
                    break
                try:
                    item = await asyncio.wait_for(self.paint_queue.get(), timeout=remaining)
                except asyncio.TimeoutError:
                    break
                batch.append(item)

            paints = [(slot, idx, color) for slot, idx, color, _ in batch]
            try:
                results = await self._request_packet([], paints, len(batch))
                if len(results) != len(batch):
                    raise RuntimeError(f"paint batch response mismatch: expected {len(batch)}, got {len(results)}")
                for item, result in zip(batch, results):
                    future = item[3]
                    if not future.done():
                        future.set_result(result)
            except Exception as exc:
                for item in batch:
                    if not item[3].done():
                        item[3].set_exception(exc)

    def on_message(self, frame):
        p = zstd.decompress(frame)
        if not p:
            return
        kind = p[0]

        if kind == 0x84:
            w, h, radius = struct.unpack_from("<HHH", p, 4)
            c0, k = struct.unpack_from("<QQ", p, 16)
            (server_us,) = struct.unpack_from("<Q", p, 88)
            self.manager.set_board_rules(w, h)
            for painter in self.painters:
                painter.radius = radius
                painter.clock_offset = server_us / 1e6 - time.time()
                painter.rules = {"w": w, "h": h, "c0": c0, "k": k}
            self.rules_ready.set()
            return

        if kind != 0x81:
            return

        r, nr = struct.unpack_from("<HI", p, 2)
        nb, nk = struct.unpack_from("<II", p, 16)
        diamond_size = 2 * r * r + 2 * r + 1

        brush_t = np.frombuffer(p, dtype="<u8", count=nb, offset=32)
        off = 32 + 8 * nb
        brush_idx = u32(p, off, nb)
        off += 4 * nb
        brush_slot = np.frombuffer(p, dtype="<u2", count=nb, offset=off)
        off += pad4(2 * nb)
        statuses = np.frombuffer(p, dtype=np.uint8, count=nr, offset=off)
        off += pad4(nr)
        values = u32(p, off, nr)
        off += 4 * nr
        sonar_idx = u32(p, off, nk)
        off += 4 * nk
        sonar_colors = u32(p, off, nk * diamond_size).reshape(nk, diamond_size)

        for center, block in zip(sonar_idx.tolist(), sonar_colors.tolist()):
            for pix, color in zip(self.diamond(center, r), block):
                if pix is not None:
                    self.manager.seen.update(pix, color)

        for slot, timestamp, idx in zip(brush_slot.tolist(), brush_t.tolist(), brush_idx.tolist()):
            if 0 <= slot < len(self.painters):
                self.painters[slot].brush = (idx, timestamp) if timestamp else None

        pending = self.pending_response
        if nr and pending is not None:
            future, expected = pending
            if not future.done():
                result = list(zip(statuses.tolist(), values.tolist()))
                # A server may include fewer results than requested; surface that clearly.
                if len(result) != expected:
                    future.set_exception(RuntimeError(
                        f"server returned {len(result)} statuses for {expected} operations"
                    ))
                else:
                    future.set_result(result)

    def diamond(self, center, radius):
        w, h = self.manager.board_width, self.manager.board_height
        x, y = center % w, center // w
        for dy in range(-radius, radius + 1):
            span = radius - abs(dy)
            for dx in range(-span, span + 1):
                xx, yy = x + dx, y + dy
                yield yy * w + xx if 0 <= xx < w and 0 <= yy < h else None

    async def reader_loop(self, ws):
        async for frame in ws:
            self.on_message(frame)
        raise ConnectionError("WebSocket reader ended")

    async def run(self, url):
        async with self.manager.ws_semaphore:
            await self.manager.ws_rate_limiter.acquire()
            async with websockets.connect(
                url,
                max_size=None,
                open_timeout=30,
                ping_interval=20,
                ping_timeout=30,
            ) as ws:
                self.ws = ws
                reader = asyncio.create_task(self.reader_loop(ws))
                try:
                    await self.bind_all()
                    await self.rules_ready.wait()
                    self.batch_task = asyncio.create_task(self.paint_batch_loop())
                    worker_tasks = [asyncio.create_task(p.worker_loop()) for p in self.painters]
                    done, pending = await asyncio.wait(
                        [reader, *worker_tasks], return_when=asyncio.FIRST_COMPLETED
                    )
                    for task in done:
                        task.result()
                    raise ConnectionError("Painter group stopped unexpectedly")
                finally:
                    if self.batch_task and not self.batch_task.done():
                        self.batch_task.cancel()
                    for task in [reader, *(locals().get("worker_tasks", []))]:
                        if not task.done():
                            task.cancel()
                    await asyncio.gather(
                        reader,
                        *locals().get("worker_tasks", []),
                        *( [self.batch_task] if self.batch_task else [] ),
                        return_exceptions=True,
                    )
                    self.ws = None


# ============================================================
# Scheduler
# ============================================================

class Scheduler:
    def __init__(self, manager):
        self.manager = manager
        self.borrowed_to = {}

    def auction_cost(self, painter, target):
        home = painter.home_region
        distance = home.distance(target)
        attack_priority = target.damage + target.growth * GROWTH_LOOKAHEAD
        cost = (
            distance * DISTANCE_WEIGHT
            + home.damage * HOME_DAMAGE_WEIGHT
            - attack_priority * ATTACK_PRIORITY_WEIGHT
        )
        if self.borrowed_to.get(painter.id) == target.id:
            cost -= STICKY_BONUS
        return cost

    def auction(self, attacked, reserved_painter_ids):
        teams = {region.id: [] for region in attacked}
        used = {region.main_painter.id for region in attacked}
        candidates = [
            region.main_painter
            for region in self.manager.regions
            if (
                not region.attacked
                and region.main_painter.id not in reserved_painter_ids
            )
        ]
        max_donors = min(
            MAX_SUPPORT_PER_ATTACK,
            SMALL_ROWS * SMALL_COLS - 1,
        )
        bids = []
        for region in attacked:
            for painter in candidates:
                if painter.home_region.distance(region) <= MAX_SUPPORT_DISTANCE:
                    bids.append((
                        self.auction_cost(painter, region),
                        region.id,
                        painter.id,
                        painter,
                    ))
        bids.sort(key=lambda item: item[0])
        counts = {region.id: 0 for region in attacked}
        for _, region_id, painter_id, painter in bids:
            if painter_id in used or counts[region_id] >= max_donors:
                continue
            teams[region_id].append(painter)
            counts[region_id] += 1
            used.add(painter_id)
        return teams

    def build_patrol_tasks(self):
        """During attacks, reserve one random-point checker per macro patrol block.

        Block edge = max(2 * BigRegion edge, 10 image pixels). Only healthy
        portions of a block are sampled. Returns task map and reserved painter IDs.
        """
        manager = self.manager
        x0, y0, image_w, image_h = manager.rect
        big_w = (image_w + BIG_COLS - 1) // BIG_COLS
        big_h = (image_h + BIG_ROWS - 1) // BIG_ROWS
        patch_w = max(2 * big_w, 10)
        patch_h = max(2 * big_h, 10)

        patrol_tasks = {}
        reserved_ids = set()
        reserved_region_ids = set()

        for patch_y in range(y0, y0 + image_h, patch_h):
            patch_y2 = min(patch_y + patch_h, y0 + image_h)
            for patch_x in range(x0, x0 + image_w, patch_w):
                patch_x2 = min(patch_x + patch_w, x0 + image_w)
                healthy_parts = []
                candidates = []

                for region in manager.regions:
                    if region.attacked:
                        continue
                    rx, ry, rw, rh = region.rect
                    ix1, iy1 = max(patch_x, rx), max(patch_y, ry)
                    ix2, iy2 = min(patch_x2, rx + rw), min(patch_y2, ry + rh)
                    if ix1 >= ix2 or iy1 >= iy2:
                        continue
                    healthy_parts.append((ix1, iy1, ix2 - ix1, iy2 - iy1))
                    if region.id not in reserved_region_ids:
                        candidates.append(region)

                if not healthy_parts or not candidates:
                    continue

                center_x = (patch_x + patch_x2) / 2
                center_y = (patch_y + patch_y2) / 2
                keeper_region = min(
                    candidates,
                    key=lambda region: (
                        abs(region.rect[0] + region.rect[2] / 2 - center_x)
                        + abs(region.rect[1] + region.rect[3] / 2 - center_y)
                    ),
                )
                keeper = keeper_region.main_painter
                reserved_region_ids.add(keeper_region.id)
                reserved_ids.add(keeper.id)

                local_x = patch_x - x0
                local_y = patch_y - y0
                patch_rect = (
                    patch_x,
                    patch_y,
                    patch_x2 - patch_x,
                    patch_y2 - patch_y,
                )
                patch_image = manager.image[
                    local_y:local_y + patch_rect[3],
                    local_x:local_x + patch_rect[2],
                ]
                task = PaintTask(
                    patch_rect,
                    patch_image,
                    keeper_region,
                    random_mode=True,
                    sample_rects=tuple(healthy_parts),
                )
                patrol_tasks.setdefault(keeper.id, []).append(task)

        print(
            f"[PATROL] {len(reserved_ids)} checkers, "
            f"block={patch_w}x{patch_h}px"
        )
        return patrol_tasks, reserved_ids

    def build_plan(self):
        regions = self.manager.regions
        attacked = [region for region in regions if region.attacked]
        desired = {painter.id: [] for painter in self.manager.painters}

        # No attack: one owner paints its whole BigRegion.
        if not attacked:
            self.borrowed_to = {}
            for region in regions:
                desired[region.main_painter.id].append(
                    region.make_task(region.rect)
                )
            return desired

        # Attack mode: reserve one random checker per healthy macro block.
        patrol_tasks, reserved_ids = self.build_patrol_tasks()
        for painter_id, tasks in patrol_tasks.items():
            desired[painter_id].extend(tasks)

        # All other healthy owners are eligible rescue donors.
        teams = self.auction(attacked, reserved_ids)
        borrowed_to = {}
        for region in attacked:
            donors = teams[region.id]
            team = [region.main_painter] + donors
            for painter in donors:
                borrowed_to[painter.id] = region.id
            for i, task in enumerate(region.split(SMALL_ROWS, SMALL_COLS)):
                desired[team[i % len(team)].id].append(task)

        self.borrowed_to = borrowed_to
        return desired

    async def apply_plan(self, desired):
        changed = []
        for painter in self.manager.painters:
            new_tasks = desired[painter.id]
            if painter.task_signature() != tuple(task.signature() for task in new_tasks):
                changed.append(painter)
        if not changed:
            return
        for painter in changed:
            painter.pause()
        await asyncio.gather(*(painter.wait_idle() for painter in changed))
        for painter in changed:
            painter.install_tasks(desired[painter.id])

    async def rebalance(self):
        await self.apply_plan(self.build_plan())

    async def run(self):
        while True:
            now = time.monotonic()
            for region in self.manager.regions:
                region.refresh_damage()
            for region in self.manager.regions:
                region.update_state(now)
            await self.rebalance()
            await asyncio.sleep(SCHEDULER_INTERVAL)


# ============================================================
# Manager and entry point
# ============================================================

class Painters:
    def __init__(self, identities, mode, tokens, rect, image, big_rows, big_cols, small_rows, small_cols, signature):
        x, y, w, h = rect
        if image.shape[:2] != (h, w):
            raise ValueError(f"image size mismatch: expected {(h, w)}, got {image.shape[:2]}")
        if len(tokens) != big_rows * big_cols or len(identities) != len(tokens):
            raise ValueError("identity/token count must equal BIG_ROWS * BIG_COLS")
        if big_rows * small_rows > h or big_cols * small_cols > w:
            raise ValueError("too many partitions; some subregions would be empty")

        self.rect = rect
        self.image = image
        self.seen = SharedView(ttl=10.0)
        self.mode_type = mode
        self.identities = identities
        self.tokens = tokens
        self.signature = signature
        self.cache_lock = asyncio.Lock()
        self.board_width = 0
        self.board_height = 0
        self.rules_ready = asyncio.Event()
        self.ws_semaphore = asyncio.Semaphore(MAX_WS_CONNECTIONS)
        self.ws_rate_limiter = StartRateLimiter(WS_CONNECT_RPS)

        self.regions = []
        self.painters = []
        pid = 0
        for row in range(big_rows):
            by1, by2 = h * row // big_rows, h * (row + 1) // big_rows
            for col in range(big_cols):
                bx1, bx2 = w * col // big_cols, w * (col + 1) // big_cols
                big_rect = (x + bx1, y + by1, bx2 - bx1, by2 - by1)
                big_image = image[by1:by2, bx1:bx2]
                region = Region(big_rect, big_image, self.seen, pid, row, col)
                painter = Painter(pid, identities[pid], mode, tokens[pid], self.seen, pid)
                painter.home_region = region
                region.main_painter = painter
                painter.tasks = [region.make_task(region.rect)]
                self.regions.append(region)
                self.painters.append(painter)
                pid += 1

        self.groups = [
            GroupConnection(self, self.painters[i:i + TOKENS_PER_WS])
            for i in range(0, len(self.painters), TOKENS_PER_WS)
        ]
        self.scheduler = Scheduler(self)
        print(f"BigRegion: {big_rows} x {big_cols} = {len(self.regions)}")
        print(f"Painters: {len(self.painters)}; tokens/WS={TOKENS_PER_WS}; WS groups={len(self.groups)}")
        if len(self.groups) > MAX_WS_CONNECTIONS:
            print("WARNING: group count exceeds connection cap; connections will queue behind the semaphore")

    def set_board_rules(self, width, height):
        global BOARD_WIDTH, BOARD_HEIGHT
        if self.board_width == 0:
            self.board_width, self.board_height = width, height
            BOARD_WIDTH, BOARD_HEIGHT = width, height
        elif (self.board_width, self.board_height) != (width, height):
            raise RuntimeError("different WebSocket groups received different board sizes")
        self.rules_ready.set()

    async def refresh_painter_token(self, painter):
        # Painter method performs bind then updates cache; this method exists for manager-level hooks.
        return await request_paint_token(SERVER, self.mode_type, painter.identity)

    async def run(self, url):
        group_tasks = [asyncio.create_task(group.run(url)) for group in self.groups]
        await self.rules_ready.wait()
        scheduler_task = asyncio.create_task(self.scheduler.run())
        try:
            await asyncio.gather(scheduler_task, *group_tasks)
        finally:
            scheduler_task.cancel()
            for task in group_tasks:
                task.cancel()
            await asyncio.gather(scheduler_task, *group_tasks, return_exceptions=True)


def load_image(path):
    img = Image.open(path).convert("RGB")
    img = img.resize((W, H), Image.Resampling.NEAREST)
    return np.array(img, dtype=np.uint8)


async def main():
    image = load_image(IMAGE_FILE)
    h, w = image.shape[:2]
    rect = (X, Y, w, h)
    total = BIG_ROWS * BIG_COLS
    print(f"image={image.shape}; painters={total}; max token RPS={MAX_TOKEN_RPS}; max WS={MAX_WS_CONNECTIONS}")

    mode = MODE
    if mode == "none":
        # Replace with the exact authorized UID list; don't generate guessed IDs.
        identities = []
        for uid in range(9000,9000+total,1):
            identities.append(uid)
        if len(identities) != total:
            raise ValueError(f"need {total} authorized UIDs, got {len(identities)}")
    elif mode == "access_key":
        identities = load_access_keys()
        if len(identities) != total:
            raise ValueError(f"need {total} access_keys, got {len(identities)}")
    else:
        raise ValueError(f"unknown MODE: {mode}")

    signature = cache_signature(SERVER, mode, identities)
    tokens = load_token_cache(signature)[:total]
    print(f"cached tokens: {len(tokens)}/{total}")
    if len(tokens) < total or any(token is None for token in tokens):
        tokens = await request_missing_tokens(
            SERVER, mode, identities, tokens, {"signature": signature}
        )
    if len(tokens) != total or any(not isinstance(token, str) or not token for token in tokens):
        raise ValueError(f"token cache incomplete: expected {total} valid tokens, got {len(tokens)} entries")

    manager = Painters(
        identities, mode, tokens, rect, image,
        BIG_ROWS, BIG_COLS, SMALL_ROWS, SMALL_COLS, signature
    )
    url = SERVER.replace("https://", "wss://", 1) + "/ws?public=0"
    await manager.run(url)


if __name__ == "__main__":
    asyncio.run(main())

::: 文件目录格式:

D:--------
  |
  WP-------
      |
      WP-v2.3.py
  |
  img------
      |
      acat.png
  |
  json------
      |
      (不用手动配置)

对于配置,只需要改代码最上面那些大写变量即可。有注释,看不懂的别改。