mirror of
https://github.com/db9979/uconsole_asw_game.git
synced 2026-12-05 12:24:25 +01:00
Share missions through an exchange folder with their user units; fairness hints
This commit is contained in:
6 files changed
+498
-23
No files matched your search
+23
-2
@@ -2052,7 +2052,7 @@
|
||||
"editor.create_hint": "Enter: erstellen",
|
||||
"editor.remove_hint": "Entf: löschen",
|
||||
"editor.add_hint": "E/G/A: hinzufügen",
|
||||
"editor.bundle_hint": "Strg+E/I: Export/Import",
|
||||
"editor.bundle_hint": "Strg+E/I: teilen/importieren",
|
||||
"editor.import_hint": "Strg+I: importieren",
|
||||
"editor.wiki_button": "Wikipedia",
|
||||
"editor.wiki_hint": "Strg+W: Wikipedia öffnen",
|
||||
@@ -6516,5 +6516,26 @@
|
||||
"uboot.end.objective": "AUFTRAG ERFÜLLT - SIEG",
|
||||
"uboot.objective.custom_reach": "Zielpunkt erreichen: Peilung {bearing}, {range} sm (noch {left})",
|
||||
"uboot.objective.custom_sink": "Ziele versenken: {sunk} von {total} versenkt (noch {left})",
|
||||
"uboot.objective.custom_survive": "Bis zum Ende der Mission durchhalten (noch {left})"
|
||||
"uboot.objective.custom_survive": "Bis zum Ende der Mission durchhalten (noch {left})",
|
||||
"editor.hint.boat_close": "Hinweis: Das U-Boot startet nur {range} sm von der Fregatte entfernt und wird sofort gefunden",
|
||||
"editor.hint.no_threat": "Hinweis: Keine feindliche Einheit platziert, die Fregatte kann gegen keinen Gegner verlieren",
|
||||
"editor.hint.reach_far.frigate": "Hinweis: Der Zielpunkt ist {range} sm entfernt; die Fregatte schafft das in {minutes} min kaum",
|
||||
"editor.hint.reach_far.boat": "Hinweis: Der Zielpunkt ist {range} sm entfernt; das U-Boot schafft das in {minutes} min kaum",
|
||||
"editor.hint.sink_far.frigate": "Hinweis: Das nächste Ziel ist {range} sm entfernt; in {minutes} min bleibt wenig Suchzeit",
|
||||
"editor.hint.sink_far.boat": "Hinweis: Das nächste Ziel ist {range} sm entfernt; das U-Boot kommt in {minutes} min kaum hin",
|
||||
"editor.hint.none": "Keine Fairness-Hinweise: Beide Seiten haben eine Chance",
|
||||
"field.boat_id": "Eigenes U-Boot",
|
||||
"editor.side.frigate": "Fregatte",
|
||||
"editor.side.uboot": "U-Boot (KI-Fregatte jagt es)",
|
||||
"editor.boat_none": "(keins)",
|
||||
"editor.shared": "In den Austauschordner gelegt: {path}",
|
||||
"editor.share_title": "Aus dem Austauschordner importieren",
|
||||
"editor.share_list_hint": "Austauschordner: {path}",
|
||||
"editor.share_empty": "Der Austauschordner ist leer: geteilte Missionsdateien nach {path} kopieren",
|
||||
"editor.share_keys": "Enter: importieren | O: Ordner öffnen | Tab: Pfad eingeben | Esc: schließen",
|
||||
"editor.share_exists": "Schon vorhanden und anders: Enter noch einmal überschreibt, Esc behält",
|
||||
"editor.share_folder_opened": "Austauschordner {path} geöffnet",
|
||||
"editor.share_folder_path": "Austauschordner: {path}",
|
||||
"editor.share_hint": "Strg+E/I: teilen/importieren",
|
||||
"editor.folder_hint": "O: Ordner"
|
||||
}
|
||||
+23
-2
@@ -2052,7 +2052,7 @@
|
||||
"editor.create_hint": "Enter: create",
|
||||
"editor.remove_hint": "Del: remove",
|
||||
"editor.add_hint": "E/G/A: add",
|
||||
"editor.bundle_hint": "Ctrl+E/I: export/import",
|
||||
"editor.bundle_hint": "Ctrl+E/I: share/import",
|
||||
"editor.import_hint": "Ctrl+I: import",
|
||||
"editor.wiki_button": "Wikipedia",
|
||||
"editor.wiki_hint": "Ctrl+W: open Wikipedia",
|
||||
@@ -6516,5 +6516,26 @@
|
||||
"uboot.end.objective": "OBJECTIVE ACHIEVED - VICTORY",
|
||||
"uboot.objective.custom_reach": "Reach the objective point: bearing {bearing}, {range} nm (time left {left})",
|
||||
"uboot.objective.custom_sink": "Sink the targets: {sunk} of {total} sunk (time left {left})",
|
||||
"uboot.objective.custom_survive": "Stay afloat to the end of the mission (time left {left})"
|
||||
"uboot.objective.custom_survive": "Stay afloat to the end of the mission (time left {left})",
|
||||
"editor.hint.boat_close": "Hint: the submarine starts only {range} nm from the frigate and will be found at once",
|
||||
"editor.hint.no_threat": "Hint: no hostile unit is placed, the frigate cannot lose to an enemy",
|
||||
"editor.hint.reach_far.frigate": "Hint: the point is {range} nm away; the frigate hardly makes it in {minutes} min",
|
||||
"editor.hint.reach_far.boat": "Hint: the point is {range} nm away; the submarine hardly makes it in {minutes} min",
|
||||
"editor.hint.sink_far.frigate": "Hint: the nearest target is {range} nm away; little search time is left in {minutes} min",
|
||||
"editor.hint.sink_far.boat": "Hint: the nearest target is {range} nm away; the submarine hardly gets there in {minutes} min",
|
||||
"editor.hint.none": "No fairness hints: both sides have a chance",
|
||||
"field.boat_id": "Player's submarine",
|
||||
"editor.side.frigate": "Frigate",
|
||||
"editor.side.uboot": "Submarine (AI frigate hunts it)",
|
||||
"editor.boat_none": "(none)",
|
||||
"editor.shared": "Shared to exchange folder: {path}",
|
||||
"editor.share_title": "Import from the exchange folder",
|
||||
"editor.share_list_hint": "Exchange folder: {path}",
|
||||
"editor.share_empty": "The exchange folder is empty: copy shared mission files to {path}",
|
||||
"editor.share_keys": "Enter: import | O: open folder | Tab: type a path | Esc: close",
|
||||
"editor.share_exists": "Already here and different: Enter again overwrites, Esc keeps it",
|
||||
"editor.share_folder_opened": "Opened the exchange folder {path}",
|
||||
"editor.share_folder_path": "Exchange folder: {path}",
|
||||
"editor.share_hint": "Ctrl+E/I: share/import",
|
||||
"editor.folder_hint": "O: folder"
|
||||
}
|
||||
@@ -404,3 +404,65 @@ class MissionDefinition:
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return copy.deepcopy(self.data)
|
||||
|
||||
|
||||
# Fairness hints (editor only, never a validation error): rough transit
|
||||
# speeds of each side for "can this side still make it in time".
|
||||
HINT_FRIGATE_KN = 20.0
|
||||
HINT_BOAT_KN = 8.0
|
||||
HINT_DETECT_NM = 3.0
|
||||
HINT_MAX = 4
|
||||
|
||||
|
||||
def mission_hints(data: Mapping[str, Any]) -> list[tuple[str, dict[str, Any]]]:
|
||||
"""(message key, params) warnings that a mission may be hard to win for
|
||||
one side; empty for an invalid mission. Pure and bounded."""
|
||||
if validate_mission(data):
|
||||
return []
|
||||
sectors = {sector["id"]: sector for sector in data["world"].get("sectors", [])}
|
||||
|
||||
def where(placement):
|
||||
if placement["kind"] == "fixed":
|
||||
return float(placement["x"]), float(placement["y"])
|
||||
sector = sectors[placement["sector"]]
|
||||
return (sector["x"] + sector["width"] / 2.0, sector["y"] + sector["height"] / 2.0)
|
||||
|
||||
exact = {unit["id"]: unit for unit in data["units"]["exact"]}
|
||||
groups = {group["id"]: group for group in data["units"]["random_groups"]}
|
||||
positions = {key: where(unit["placement"]) for key, unit in exact.items()}
|
||||
positions.update({key: where(group["placement"]) for key, group in groups.items()})
|
||||
frigate = (float(data["player"]["x"]), float(data["player"]["y"]))
|
||||
objective = data["objective"]
|
||||
limit_s = float(objective["time_limit_s"])
|
||||
side = mission_side(data)
|
||||
hints: list[tuple[str, dict[str, Any]]] = []
|
||||
|
||||
def far(start, point, speed_kn, share):
|
||||
distance = ((start[0] - point[0]) ** 2 + (start[1] - point[1]) ** 2) ** 0.5
|
||||
return distance, distance / speed_kn * 3600.0 > limit_s * share
|
||||
|
||||
if side == "uboot":
|
||||
boat = positions[data["boat_id"]]
|
||||
mover, speed, who = boat, HINT_BOAT_KN, "boat"
|
||||
distance = ((boat[0] - frigate[0]) ** 2 + (boat[1] - frigate[1]) ** 2) ** 0.5
|
||||
if distance < HINT_DETECT_NM:
|
||||
hints.append(("editor.hint.boat_close", {"range": f"{distance:.1f}"}))
|
||||
else:
|
||||
mover, speed, who = frigate, HINT_FRIGATE_KN, "frigate"
|
||||
hostile = [key for key, unit in {**exact, **groups}.items() if unit["side"] == "hostile"]
|
||||
if objective["type"] in ("survive", "protect") and not hostile:
|
||||
hints.append(("editor.hint.no_threat", {}))
|
||||
minutes = int(limit_s // 60)
|
||||
if objective["type"] == "reach":
|
||||
point = objective["reach"]
|
||||
distance, late = far(mover, (float(point["x"]), float(point["y"])), speed, 1.0)
|
||||
if late:
|
||||
hints.append((f"editor.hint.reach_far.{who}",
|
||||
{"range": f"{distance:.0f}", "minutes": minutes}))
|
||||
elif objective["type"] == "sink" and objective["target_ids"]:
|
||||
nearest = min(far(mover, positions[target], speed, 0.5)
|
||||
for target in objective["target_ids"] if target in positions)
|
||||
if nearest[1]:
|
||||
hints.append((f"editor.hint.sink_far.{who}",
|
||||
{"range": f"{nearest[0]:.0f}", "minutes": minutes}))
|
||||
return hints[:HINT_MAX]
|
||||
@@ -17,6 +17,21 @@ from src.data.validation import (ContentValidationError, ValidationIssue, issue,
|
||||
DEFAULT_ROOT = Path.home() / ".u-jagd"
|
||||
BUNDLE_FORMAT = "u-jagd.editor-bundle"
|
||||
BUNDLE_VERSION = 1
|
||||
# Exchange folder for shared missions (``~/.u-jagd/share``): an export lands
|
||||
# there, the import list shows its files. Bounded: files read and listed.
|
||||
SHARE_DIR = "share"
|
||||
SHARE_MAX_FILES = 100
|
||||
BUNDLE_MAX_BYTES = 1024 * 1024
|
||||
BUNDLE_MAX_ITEMS = 64
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SharedFile:
|
||||
"""One bundle file in the exchange folder (``error`` when unreadable)."""
|
||||
path: Path
|
||||
missions: tuple[tuple[str, str, str], ...] = () # (key, name, side)
|
||||
units: int = 0
|
||||
error: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -79,6 +94,10 @@ def _stage_bytes(path: Path, value: bytes) -> Path:
|
||||
return Path(temporary)
|
||||
|
||||
|
||||
def _reject_constant(name: str):
|
||||
raise ValueError(f"non-finite JSON constant {name}")
|
||||
|
||||
|
||||
def _remove_if_present(path: str | Path) -> None:
|
||||
try:
|
||||
os.unlink(path)
|
||||
@@ -94,6 +113,7 @@ class UserContentStore:
|
||||
unit_validator: Callable[[Mapping[str, Any]], Iterable[ValidationIssue]] | None = None):
|
||||
self.root = Path(root).expanduser()
|
||||
self.roots = {"mission": self.root / "missions", "unit": self.root / "units"}
|
||||
self.share_root = self.root / SHARE_DIR
|
||||
self.validators = {"mission": mission_validator, "unit": unit_validator}
|
||||
|
||||
def _kind(self, kind: str) -> str:
|
||||
@@ -170,19 +190,77 @@ class UserContentStore:
|
||||
raise_for_issues(problems)
|
||||
return atomic_write_json(path, payload)
|
||||
|
||||
def mission_bundle(self, mission: Mapping[str, Any]) -> dict[str, Any]:
|
||||
"""A shareable bundle of one mission with the user unit profiles it
|
||||
references, so it starts on another console too."""
|
||||
from src.data.user_profiles import referenced_user_keys
|
||||
units = []
|
||||
for key in referenced_user_keys(mission):
|
||||
try:
|
||||
units.append(self.load("unit", key))
|
||||
except FileNotFoundError:
|
||||
raise ContentValidationError([
|
||||
issue(f"units.{key}", "missing", "referenced unit profile is missing")]) from None
|
||||
payload = {"format": BUNDLE_FORMAT, "version": BUNDLE_VERSION,
|
||||
"missions": [dict(mission)], "units": units}
|
||||
raise_for_issues(self._validate_bundle(payload))
|
||||
return payload
|
||||
|
||||
def export_mission(self, mission: Mapping[str, Any], path: str | Path | None = None) -> Path:
|
||||
"""Write one mission with its user units; default: the exchange folder."""
|
||||
payload = self.mission_bundle(mission)
|
||||
if path is None:
|
||||
path = safe_content_path(self.share_root, str(mission["key"]))
|
||||
return atomic_write_json(path, payload)
|
||||
|
||||
def read_bundle(self, path: str | Path) -> Any:
|
||||
"""Parse a bundle file, bounded in size (validation is the caller's)."""
|
||||
path = Path(path).expanduser()
|
||||
if path.is_symlink():
|
||||
raise ContentValidationError([issue("path", "symlink", "refusing symlinked path")])
|
||||
with path.open("rb") as stream:
|
||||
raw = stream.read(BUNDLE_MAX_BYTES + 1)
|
||||
if len(raw) > BUNDLE_MAX_BYTES:
|
||||
raise ContentValidationError([issue("bundle", "size", "bundle file is too large")])
|
||||
return json.loads(raw.decode("utf-8"), parse_constant=_reject_constant)
|
||||
|
||||
def shared_files(self) -> list[SharedFile]:
|
||||
"""The bundle files in the exchange folder, sorted by name, bounded."""
|
||||
root = self.share_root
|
||||
if not root.is_dir() or root.is_symlink() or (self.root.exists() and self.root.is_symlink()):
|
||||
return []
|
||||
rows = []
|
||||
for path in sorted(root.glob("*.json"))[:SHARE_MAX_FILES]:
|
||||
if path.is_symlink() or not path.is_file():
|
||||
continue
|
||||
try:
|
||||
payload = self.read_bundle(path)
|
||||
problems = self._validate_bundle(payload)
|
||||
except (OSError, ValueError, UnicodeDecodeError, ContentValidationError) as exc:
|
||||
rows.append(SharedFile(path, error=type(exc).__name__))
|
||||
continue
|
||||
if problems:
|
||||
rows.append(SharedFile(path, error=problems[0].code))
|
||||
continue
|
||||
rows.append(SharedFile(path, tuple(
|
||||
(item["key"], item["name"], str(item.get("side", "frigate")))
|
||||
for item in payload["missions"]), len(payload["units"])))
|
||||
return rows
|
||||
|
||||
def import_bundle(self, source: str | Path | Mapping[str, Any], *,
|
||||
overwrite: bool = False) -> list[ContentRecord]:
|
||||
if isinstance(source, Mapping):
|
||||
payload = dict(source)
|
||||
else:
|
||||
with Path(source).open("r", encoding="utf-8") as stream:
|
||||
payload = json.load(stream)
|
||||
payload = self.read_bundle(source)
|
||||
raise_for_issues(self._validate_bundle(payload))
|
||||
pending = []
|
||||
for plural, kind in (("missions", "mission"), ("units", "unit")):
|
||||
for data in payload[plural]:
|
||||
path = self.path_for(kind, data["key"])
|
||||
if path.exists() and not overwrite:
|
||||
if self._same_content(kind, data):
|
||||
continue # already here, unchanged: nothing to write
|
||||
raise ContentValidationError([
|
||||
issue(f"{plural}.{data['key']}", "exists", "content already exists")])
|
||||
pending.append((kind, data, path))
|
||||
@@ -244,10 +322,19 @@ class UserContentStore:
|
||||
return [ContentRecord(data["key"], kind, dict(data), source=path)
|
||||
for kind, data, path, _, _ in staged]
|
||||
|
||||
def _same_content(self, kind: str, data: Mapping[str, Any]) -> bool:
|
||||
try:
|
||||
return self.load(kind, data["key"]) == json.loads(json.dumps(data))
|
||||
except (OSError, ValueError, ContentValidationError):
|
||||
return False
|
||||
|
||||
def _validate_bundle(self, payload: Any) -> list[ValidationIssue]:
|
||||
if not isinstance(payload, Mapping):
|
||||
return [issue("bundle", "object", "bundle must be an object")]
|
||||
problems = []
|
||||
if set(payload) != {"format", "version", "missions", "units"}:
|
||||
problems.append(issue("bundle", "schema",
|
||||
"must have exactly format, version, missions and units"))
|
||||
if payload.get("format") != BUNDLE_FORMAT:
|
||||
problems.append(issue("format", "format", f"must be {BUNDLE_FORMAT!r}"))
|
||||
if payload.get("version") != BUNDLE_VERSION:
|
||||
@@ -258,6 +345,9 @@ class UserContentStore:
|
||||
if not isinstance(values, list):
|
||||
problems.append(issue(plural, "array", "must be an array"))
|
||||
continue
|
||||
if len(values) > BUNDLE_MAX_ITEMS:
|
||||
problems.append(issue(plural, "size", f"at most {BUNDLE_MAX_ITEMS} items"))
|
||||
continue
|
||||
for index, value in enumerate(values):
|
||||
base = f"{plural}[{index}]"
|
||||
if not isinstance(value, Mapping):
|
||||
|
||||
+179
-17
@@ -9,16 +9,39 @@ from typing import Any, Iterable, Mapping
|
||||
import pygame
|
||||
|
||||
from src.core.i18n import raw_text, translation_scope
|
||||
from src.core.mission_definition import (MISSION_FIELD_METADATA, REFERENCE_PREFIX,
|
||||
MissionDefinition, default_mission,
|
||||
from src.core.mission_definition import (MISSION_FIELD_METADATA, PLAYER_SIDES,
|
||||
REFERENCE_PREFIX, MissionDefinition,
|
||||
default_mission, mission_hints, mission_side,
|
||||
reference_sector_index)
|
||||
from src.data.user_content import ContentRecord, UserContentStore
|
||||
from src.data.user_content import ContentRecord, SharedFile, UserContentStore
|
||||
from src.data.validation import (ContentValidationError, localized_error,
|
||||
localized_issue)
|
||||
from src.ui import editor_widgets as widgets
|
||||
from src.world.real_coast import SECTOR_COUNT, sector_for_index
|
||||
|
||||
WORLD_KINDS = ("fixed", "reference")
|
||||
|
||||
|
||||
def open_folder(path: Path) -> bool:
|
||||
"""Show a folder in the system file manager (Windows Explorer, a desktop
|
||||
opener elsewhere); False when the system has none. Never blocks."""
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
try:
|
||||
path.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
if sys.platform.startswith("win"):
|
||||
os.startfile(str(path)) # type: ignore[attr-defined]
|
||||
return True
|
||||
opener = shutil.which("open" if sys.platform == "darwin" else "xdg-open")
|
||||
if opener is None:
|
||||
return False
|
||||
subprocess.Popen([opener, str(path)], stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL, start_new_session=True)
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
_SECTOR_SUMMARIES: list[tuple[int, tuple[str, ...], tuple[tuple[tuple[float, float], ...], ...]]] = []
|
||||
|
||||
|
||||
@@ -67,6 +90,11 @@ class MissionEditor:
|
||||
self._delete_pending: tuple[str, int] | None = None
|
||||
self.path_action: str | None = None
|
||||
self.path_input = widgets.TextField(maximum=1024)
|
||||
# The exchange-folder import list (Ctrl+I) and a pending overwrite.
|
||||
self.share_open = False
|
||||
self.share_files: list[SharedFile] = []
|
||||
self.share_box = widgets.ListBox()
|
||||
self._overwrite_pending: Path | None = None
|
||||
self.focus_area = "fields"
|
||||
self.refresh()
|
||||
|
||||
@@ -75,8 +103,10 @@ class MissionEditor:
|
||||
for key, value in sorted(self.builtins.items())]
|
||||
records.extend(self.store.list("mission"))
|
||||
self.records = records
|
||||
self.listbox.set_items([f"{'[built-in]' if item.builtin else '[user]'} {item.key}"
|
||||
for item in records])
|
||||
self.listbox.set_items([
|
||||
f"{'[built-in]' if item.builtin else '[user]'}"
|
||||
f"{' [U]' if mission_side(item.data) == 'uboot' else ''} {item.key}"
|
||||
for item in records])
|
||||
|
||||
@property
|
||||
def selected(self) -> ContentRecord | None:
|
||||
@@ -208,6 +238,88 @@ class MissionEditor:
|
||||
self.refresh()
|
||||
return records
|
||||
|
||||
def share_mission(self) -> Path:
|
||||
"""Export the open (else the selected user) mission with its user
|
||||
units into the exchange folder."""
|
||||
if self.mode == "editor" and self.current is not None:
|
||||
mission = self.current.to_dict()
|
||||
else:
|
||||
record = self.selected
|
||||
if record is None or record.builtin:
|
||||
raise ValueError("no user mission selected")
|
||||
mission = record.data
|
||||
path = self.store.export_mission(mission)
|
||||
self.status = self.tr("editor.shared", path=str(path))
|
||||
return path
|
||||
|
||||
def open_share_list(self) -> None:
|
||||
self.share_files = self.store.shared_files()
|
||||
self.share_box.set_items([self._share_label(item) for item in self.share_files])
|
||||
self.share_open = True
|
||||
self._overwrite_pending = None
|
||||
self.status = self.tr("editor.share_list_hint" if self.share_files
|
||||
else "editor.share_empty", path=str(self.store.share_root))
|
||||
|
||||
def _share_label(self, item: SharedFile) -> str:
|
||||
if item.error:
|
||||
return f"{item.path.name} ({item.error})"
|
||||
names = ", ".join(name for _key, name, _side in item.missions) or "-"
|
||||
return f"{item.path.name} {names}"
|
||||
|
||||
def import_shared(self, index: int) -> None:
|
||||
"""Import one exchange-folder file; an existing mission needs a second
|
||||
Enter to be overwritten."""
|
||||
if not 0 <= index < len(self.share_files):
|
||||
return
|
||||
path = self.share_files[index].path
|
||||
overwrite = self._overwrite_pending == path
|
||||
try:
|
||||
self.import_bundle(path, overwrite=overwrite)
|
||||
except ContentValidationError as exc:
|
||||
if any(problem.code == "exists" for problem in exc.issues) and not overwrite:
|
||||
self._overwrite_pending = path
|
||||
self.status = self.tr("editor.share_exists")
|
||||
return
|
||||
self.status = localized_error(exc, self.tr)
|
||||
return
|
||||
except (OSError, ValueError) as exc:
|
||||
self.status = localized_error(exc, self.tr)
|
||||
return
|
||||
self._overwrite_pending = None
|
||||
self.share_open = False
|
||||
self.status = self.tr("editor.path_result", action=self.tr("editor.imported"),
|
||||
path=path.name)
|
||||
|
||||
def _handle_share(self, event: pygame.event.Event) -> bool:
|
||||
if event.type != pygame.KEYDOWN:
|
||||
if event.type in (pygame.MOUSEBUTTONDOWN, pygame.MOUSEWHEEL):
|
||||
rect = self._rects.get("share")
|
||||
if rect is not None:
|
||||
self.share_box.handle_event(event, rect)
|
||||
return True
|
||||
if event.key == pygame.K_ESCAPE:
|
||||
self.share_open = False
|
||||
self.status = ""
|
||||
return True
|
||||
if event.key == pygame.K_TAB:
|
||||
self.share_open = False
|
||||
self._begin_path("import")
|
||||
return True
|
||||
if event.key == pygame.K_o:
|
||||
self._open_share_folder()
|
||||
return True
|
||||
if event.key in (pygame.K_RETURN, pygame.K_KP_ENTER):
|
||||
self.import_shared(self.share_box.selected)
|
||||
return True
|
||||
if self.share_box.handle_event(event, self._rects.get("share", pygame.Rect(0, 0, 1, 1))):
|
||||
self._overwrite_pending = None
|
||||
return True
|
||||
|
||||
def _open_share_folder(self) -> None:
|
||||
opened = open_folder(self.store.share_root)
|
||||
self.status = self.tr("editor.share_folder_opened" if opened
|
||||
else "editor.share_folder_path", path=str(self.store.share_root))
|
||||
|
||||
@staticmethod
|
||||
def _next_id(values: Iterable[Mapping[str, Any]], prefix: str) -> str:
|
||||
used = {str(value.get("id", "")) for value in values}
|
||||
@@ -222,12 +334,23 @@ class MissionEditor:
|
||||
return
|
||||
data = self.current.data
|
||||
if self.tab == "overview":
|
||||
subset = {key: data[key] for key in ("key", "name", "description", "seed")}
|
||||
data.setdefault("side", "frigate")
|
||||
data.setdefault("boat_id", "")
|
||||
subset = {key: data[key] for key in ("key", "name", "description", "seed",
|
||||
"side", "boat_id")}
|
||||
rows = widgets.mapping_rows(subset)
|
||||
# The temporary dictionary needs setters aimed at the actual model.
|
||||
for row in rows:
|
||||
key = row.path
|
||||
row.setter = lambda value, field=key: data.__setitem__(field, value)
|
||||
if key == "side":
|
||||
row.choices = lambda: [(side, self.tr("editor.side." + side))
|
||||
for side in PLAYER_SIDES]
|
||||
elif key == "boat_id":
|
||||
row.choices = lambda: [("", self.tr("editor.boat_none"))] + [
|
||||
(unit["id"], unit["id"]) for unit in data["units"]["exact"]
|
||||
if isinstance(unit, dict) and unit.get("side") == "hostile"
|
||||
and isinstance(unit.get("id"), str)]
|
||||
elif self.tab == "world":
|
||||
rows = (widgets.mapping_rows(data["world"], "world")
|
||||
+ widgets.mapping_rows(data["player"], "player")
|
||||
@@ -404,6 +527,19 @@ class MissionEditor:
|
||||
event = pygame.event.Event(pygame.KEYDOWN, key=key, mod=0, unicode="")
|
||||
if self.path_action:
|
||||
return self._handle_path(event)
|
||||
if self.share_open:
|
||||
return self._handle_share(event)
|
||||
if (event.type == pygame.KEYDOWN and event.key == pygame.K_e
|
||||
and getattr(event, "mod", 0) & pygame.KMOD_CTRL
|
||||
and not (self.mode == "editor" and self.fields.editing)):
|
||||
if getattr(event, "mod", 0) & pygame.KMOD_SHIFT:
|
||||
self._begin_path("export")
|
||||
return True
|
||||
try:
|
||||
self.share_mission()
|
||||
except (ContentValidationError, OSError, ValueError) as exc:
|
||||
self.status = localized_error(exc, self.tr)
|
||||
return True
|
||||
if self.mode == "browser":
|
||||
changed = self.listbox.handle_event(event, self._rects.get("browser", pygame.Rect(28, 104, 424, 532)))
|
||||
if event.type == pygame.KEYDOWN:
|
||||
@@ -412,7 +548,9 @@ class MissionEditor:
|
||||
if event.key == pygame.K_n:
|
||||
self.new(); return True
|
||||
if event.key == pygame.K_i and getattr(event, "mod", 0) & pygame.KMOD_CTRL:
|
||||
self._begin_path("import"); return True
|
||||
self.open_share_list(); return True
|
||||
if event.key == pygame.K_o:
|
||||
self._open_share_folder(); return True
|
||||
return changed
|
||||
if self.fields.editing:
|
||||
if (event.type == pygame.KEYDOWN and event.key == pygame.K_s
|
||||
@@ -512,10 +650,8 @@ class MissionEditor:
|
||||
except (ContentValidationError, OSError) as exc:
|
||||
self.status = localized_error(exc, self.tr)
|
||||
return True
|
||||
if event.key == pygame.K_e and getattr(event, "mod", 0) & pygame.KMOD_CTRL:
|
||||
self._begin_path("export"); return True
|
||||
if event.key == pygame.K_i and getattr(event, "mod", 0) & pygame.KMOD_CTRL:
|
||||
self._begin_path("import"); return True
|
||||
self.open_share_list(); return True
|
||||
return False
|
||||
|
||||
def draw(self, surface: pygame.Surface) -> None:
|
||||
@@ -536,7 +672,8 @@ class MissionEditor:
|
||||
self._draw_browser(surface, content)
|
||||
elif self.current:
|
||||
self._draw_editor(surface, content)
|
||||
hints = (("editor.select_hint", "editor.open_hint", "editor.new_hint")
|
||||
hints = (("editor.select_hint", "editor.open_hint", "editor.new_hint",
|
||||
"editor.share_hint", "editor.folder_hint")
|
||||
if self.mode == "browser" else
|
||||
("editor.arrow_hint", "editor.edit_hint", "editor.add_hint", "editor.remove_hint",
|
||||
"editor.save_hint", "editor.bundle_hint", "editor.cancel_hint"))
|
||||
@@ -546,6 +683,21 @@ class MissionEditor:
|
||||
max(1, bounds.width * 2 // 3), 110)
|
||||
inner = widgets.panel(surface, box, "editor.bundle_path", tr=self.tr)
|
||||
self.path_input.draw(surface, pygame.Rect(inner.x, inner.y + 5, inner.width, 34), focused=True)
|
||||
if self.share_open:
|
||||
box = pygame.Rect(max(20, bounds.width // 8), max(60, bounds.height // 6),
|
||||
max(1, bounds.width * 3 // 4), max(1, bounds.height * 2 // 3))
|
||||
inner = widgets.panel(surface, box, "editor.share_title", tr=self.tr)
|
||||
list_rect = pygame.Rect(inner.x, inner.y, inner.width, max(1, inner.height - 30))
|
||||
self._rects["share"] = list_rect
|
||||
if self.share_files:
|
||||
self.share_box.draw(surface, list_rect)
|
||||
else:
|
||||
widgets.draw_text(surface, self.tr("editor.share_empty",
|
||||
path=str(self.store.share_root)),
|
||||
list_rect, color=widgets.PALETTE.dim)
|
||||
widgets.draw_text(surface, self.tr("editor.share_keys"),
|
||||
(inner.x, inner.bottom - 26, inner.width, 24),
|
||||
color=widgets.PALETTE.dim, size=13)
|
||||
if self.status:
|
||||
widgets.draw_text(surface, raw_text(self.status), (bounds.width // 2, 18, bounds.width // 2 - 20, 28),
|
||||
color=widgets.PALETTE.focus, align="right", size=13)
|
||||
@@ -561,13 +713,18 @@ class MissionEditor:
|
||||
widgets.draw_text(surface, self.tr("editor.no_missions"), inner,
|
||||
color=widgets.PALETTE.dim)
|
||||
return
|
||||
values = (record.key, record.data.get("name", ""), record.data.get("description", ""),
|
||||
values = (raw_text(record.key), raw_text(record.data.get("name", "")),
|
||||
raw_text(record.data.get("description", "")),
|
||||
self.tr("editor.read_only" if record.builtin else "editor.user_mission"),
|
||||
self.tr("editor.side." + mission_side(record.data)),
|
||||
self.tr("editor.runtime_scope"))
|
||||
for row, value in enumerate(values):
|
||||
widgets.draw_text(surface, raw_text(value),
|
||||
hints = [self.tr(key, **params) for key, params in mission_hints(record.data)]
|
||||
for row, value in enumerate(values + tuple(hints)):
|
||||
widgets.draw_text(surface, raw_text(value) if isinstance(value, str) else value,
|
||||
(inner.x, inner.y + row * 32, inner.width, 28),
|
||||
color=widgets.PALETTE.focus if row == 4 else widgets.PALETTE.text)
|
||||
color=(widgets.PALETTE.danger if row >= len(values)
|
||||
else widgets.PALETTE.focus if row == 5
|
||||
else widgets.PALETTE.text))
|
||||
|
||||
def _draw_editor(self, surface: pygame.Surface, content: pygame.Rect) -> None:
|
||||
self._sync_fields()
|
||||
@@ -661,7 +818,12 @@ class MissionEditor:
|
||||
self.tr("editor.preview_markers", count=len(preview["markers"])),
|
||||
self.tr("editor.preview_events", count=len(preview["events"])),
|
||||
self.tr("editor.static_only"), self.tr("editor.runtime_scope"))
|
||||
for row, line in enumerate(lines):
|
||||
hints = [self.tr(key, **params) for key, params in mission_hints(self._data())] \
|
||||
or [self.tr("editor.hint.none")]
|
||||
for row, line in enumerate(lines + tuple(hints)):
|
||||
widgets.draw_text(surface, line,
|
||||
(details.x, details.y + row * 30, details.width, 26),
|
||||
color=widgets.PALETTE.focus if row >= 4 else widgets.PALETTE.text)
|
||||
color=(widgets.PALETTE.danger if row >= len(lines)
|
||||
and hints[0] != self.tr("editor.hint.none")
|
||||
else widgets.PALETTE.focus if row >= 4
|
||||
else widgets.PALETTE.text))
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Sharing custom missions: an export lands in the exchange folder with the
|
||||
user units it references, the import list reads that folder, an identical
|
||||
item is no collision, and a hostile file stays rejected."""
|
||||
|
||||
import json
|
||||
|
||||
import pygame
|
||||
import pytest
|
||||
|
||||
from src.core.mission_definition import default_mission, mission_hints
|
||||
from src.data.user_content import BUNDLE_MAX_BYTES, default_store
|
||||
from src.data.validation import ContentValidationError
|
||||
from src.ui.mission_editor import MissionEditor
|
||||
|
||||
|
||||
def _unit():
|
||||
with open("data/editor_templates/unit_sub.json", encoding="utf-8") as stream:
|
||||
return json.load(stream)
|
||||
|
||||
|
||||
def _mission(key="user.shared"):
|
||||
mission = default_mission(key)
|
||||
unit = _unit()
|
||||
mission["units"]["exact"] = [{"id": "boat", "profile": unit["key"], "side": "hostile",
|
||||
"placement": {"kind": "fixed", "x": 300.0, "y": 250.0},
|
||||
"course_deg": 0.0, "speed_kn": 4.0}]
|
||||
mission["objective"]["target_ids"] = ["boat"]
|
||||
return mission
|
||||
|
||||
|
||||
def test_export_packs_the_referenced_user_units_into_the_exchange_folder(tmp_path):
|
||||
store = default_store(tmp_path / "a")
|
||||
store.save("unit", _unit())
|
||||
path = store.export_mission(_mission())
|
||||
assert path.parent == store.share_root and path.name == "user.shared.json"
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
assert [unit["key"] for unit in payload["units"]] == [_unit()["key"]]
|
||||
other = default_store(tmp_path / "b")
|
||||
(other.share_root).mkdir(parents=True)
|
||||
(other.share_root / "friend.json").write_bytes(path.read_bytes())
|
||||
(other.share_root / "broken.json").write_text("{", encoding="utf-8")
|
||||
rows = other.shared_files()
|
||||
assert [row.path.name for row in rows] == ["broken.json", "friend.json"]
|
||||
assert rows[0].error and rows[1].missions == (("user.shared", "New mission", "frigate"),)
|
||||
assert rows[1].units == 1
|
||||
records = other.import_bundle(rows[1].path)
|
||||
assert {record.key for record in records} == {"user.shared", _unit()["key"]}
|
||||
# The same file again is no collision; a changed mission is one.
|
||||
assert other.import_bundle(rows[1].path) == []
|
||||
changed = json.loads(path.read_text(encoding="utf-8"))
|
||||
changed["missions"][0]["name"] = "Changed"
|
||||
with pytest.raises(ContentValidationError) as error:
|
||||
other.import_bundle(changed)
|
||||
assert error.value.issues[0].code == "exists"
|
||||
assert other.import_bundle(changed, overwrite=True)[0].data["name"] == "Changed"
|
||||
|
||||
|
||||
def test_a_missing_user_unit_blocks_the_export(tmp_path):
|
||||
with pytest.raises(ContentValidationError) as error:
|
||||
default_store(tmp_path).export_mission(_mission())
|
||||
assert error.value.issues[0].code == "missing"
|
||||
|
||||
|
||||
def test_hostile_bundle_files_are_rejected(tmp_path):
|
||||
store = default_store(tmp_path)
|
||||
store.share_root.mkdir(parents=True)
|
||||
big = store.share_root / "big.json"
|
||||
big.write_bytes(b" " * (BUNDLE_MAX_BYTES + 1))
|
||||
nan = store.share_root / "nan.json"
|
||||
nan.write_text('{"format": "u-jagd.editor-bundle", "version": 1, "missions": [],'
|
||||
' "units": [], "x": NaN}', encoding="utf-8")
|
||||
extra = {"format": "u-jagd.editor-bundle", "version": 1, "missions": [], "units": [],
|
||||
"script": "x"}
|
||||
for source in (big, nan, extra):
|
||||
with pytest.raises((ContentValidationError, ValueError)):
|
||||
store.import_bundle(source)
|
||||
assert all(row.error for row in store.shared_files())
|
||||
|
||||
|
||||
def test_editor_shares_and_imports_through_the_list(tmp_path):
|
||||
pygame.init()
|
||||
source = default_store(tmp_path / "a")
|
||||
source.save("mission", _mission("user.plain") | {"units": {"exact": [], "random_groups": []},
|
||||
"objective": default_mission()["objective"]})
|
||||
editor = MissionEditor(store=source, profile_keys=set())
|
||||
editor.listbox.selected = 0
|
||||
key = pygame.event.Event(pygame.KEYDOWN, key=pygame.K_e, mod=pygame.KMOD_CTRL, unicode="")
|
||||
assert editor.handle_event(key)
|
||||
shared = source.share_root / "user.plain.json"
|
||||
assert shared.exists()
|
||||
target = default_store(tmp_path / "b")
|
||||
target.share_root.mkdir(parents=True)
|
||||
(target.share_root / "x.json").write_bytes(shared.read_bytes())
|
||||
other = MissionEditor(store=target, profile_keys=set())
|
||||
other.handle_event(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_i,
|
||||
mod=pygame.KMOD_CTRL, unicode=""))
|
||||
assert other.share_open and len(other.share_files) == 1
|
||||
other.draw(pygame.Surface((1280, 720)))
|
||||
other.handle_event(pygame.event.Event(pygame.KEYDOWN, key=pygame.K_RETURN, mod=0, unicode=""))
|
||||
assert not other.share_open
|
||||
assert [record.key for record in other.records] == ["user.plain"]
|
||||
pygame.quit()
|
||||
|
||||
|
||||
def test_fairness_hints_name_a_side_that_can_hardly_win():
|
||||
mission = default_mission("user.far")
|
||||
mission["units"]["exact"] = [{"id": "sub", "profile": "sub_03", "side": "hostile",
|
||||
"placement": {"kind": "fixed", "x": 300.0, "y": 300.0},
|
||||
"course_deg": 0.0, "speed_kn": 4.0}]
|
||||
mission["objective"].update(type="sink", target_ids=["sub"], time_limit_s=1800.0)
|
||||
assert [key for key, _ in mission_hints(mission)] == ["editor.hint.sink_far.frigate"]
|
||||
mission["objective"]["time_limit_s"] = 8 * 3600.0
|
||||
assert mission_hints(mission) == []
|
||||
boat = default_mission("user.close")
|
||||
boat.update(side="uboot", boat_id="sub")
|
||||
boat["units"]["exact"] = [dict(mission["units"]["exact"][0],
|
||||
placement={"kind": "fixed", "x": 251.0, "y": 250.0})]
|
||||
boat["objective"].update(type="survive", target_ids=[])
|
||||
assert [key for key, _ in mission_hints(boat)] == ["editor.hint.boat_close"]
|
||||
Reference in new issue
Block a user