lost-sector-port/tools/sim/navmesh_connectivity.py
Elden cfca00c5fd Outils : sim de connectivité NavMesh (repro sans émulateur)
POURQUOI : les remontées "aucun chemin NavMesh" (Pixel 8 Pro) sont
indisable sur émulateur et le gamelog ne montre que le symptôme. Ces
scripts Python reproduisent SANS rendu ni émulateur :
- la génération procédurale (MapManager.loadProceduralMap porté au
  ligne près : java.util.Random, ordre HashMap, connecteurs, verrous,
  solidité, portes) ;
- NavMesh.init (fillIn, liens marche/chute/saut) et getPath (BFS) ;
- le spawn Exterminate (raycast de sol, ±1500 px vertical) ;
- un oracle physique (marche / chute par bord / saut <= 3 lignes) pour
  séparer l'isolation RÉELLE des liens manquants.

Les drapeaux fix_notch / fix_left_bound / _resolve_links reproduisent
exactement le patch NavMesh/Behaviour pour les mesures avant/après.
Résultats cités dans le commentaire de NavMesh.resolveNavCell.
2026-11-16 04:37:09 +01:00

799 lines
28 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Sim de connectivité NavMesh — port fidèle (Python) de :
- MapManager.loadProceduralMap (placement segments + solidité + spawn joueur)
- NavMesh.init (fillIn, walk/fall/jump links) et NavMesh.getPath (BFS)
- ExterminateMission (logique de spawn d'ennemi autour du joueur)
POURQUOI : diagnostiquer "aucun chemin NavMesh" entre étages voisins SANS
émulateur (gamelog v0.12.x Pixel 8 Pro : ennemi y=25400 ne joint jamais le
joueur y=26100-26900). Le port reproduit le code au ligne près ; toute
divergence doit être justifiée par un commentaire.
Usage : python3 tools/sim/navmesh_connectivity.py [nb_seeds]
"""
import os
import sys
import xml.etree.ElementTree as ET
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
SEG_DIR = os.path.join(ROOT, "lost-sector/src/main/resources/maps/procedural/corpus")
TILE_PX = 100 # 1 tuile TMX (16px) * MAP_SCALE 6.25 = 100 px monde
PROC_START = (0, 256) # tuiles (MapManager.PROC_START_POS)
NUM_ROOMS = 16
SEG_SIZE = 16
# ---------------------------------------------------------------- Java Random
MASK48 = (1 << 48) - 1
MULT = 0x5DEECE66D
ADD = 0xB
def s32(v):
v &= 0xFFFFFFFF
return v - 0x100000000 if v >= 0x80000000 else v
class JavaRandom:
def __init__(self, seed):
self.seed = (seed ^ MULT) & MASK48
def next(self, bits):
self.seed = (self.seed * MULT + ADD) & MASK48
return s32(self.seed >> (48 - bits)) if bits < 32 else s32(self.seed)
def next_int(self, bound):
if bound <= 0:
raise ValueError("bound must be positive")
if (bound & -bound) == bound:
return s32((bound * self.next(31)) >> 31)
while True:
bits = self.next(31) & 0x7FFFFFFF
val = bits % bound
if bits - val + (bound - 1) < (1 << 31):
return val
def s_hash(s):
h = 0
for c in s:
h = (h * 31 + ord(c)) & 0xFFFFFFFF
if h >= 0x80000000:
h -= 0x100000000
return h
class JavaHashMap:
"""Ordre d'itération de HashMap<String, V> (capacité 16, spread h^h>>>16)."""
def __init__(self):
self.table = [[] for _ in range(16)]
self.n = 0
def _spread(self, key):
h = s_hash(key) & 0xFFFFFFFF
return h ^ (h >> 16)
def _bucket(self, key):
return self._spread(key) & (len(self.table) - 1)
def put(self, key, value):
if self.n + 1 > len(self.table) * 0.75:
old = self.table
self.table = [[] for _ in range(len(old) * 2)]
for b in old:
for k, v in b:
self.table[self._bucket(k)].append((k, v))
b = self.table[self._bucket(key)]
for i, (k, _) in enumerate(b):
if k == key:
b[i] = (key, value)
return
b.append((key, value))
self.n += 1
def get(self, key):
b = self.table[self._bucket(key)]
for k, v in b:
if k == key:
return v
return None
def contains(self, key):
return self.get(key) is not None
def values(self):
out = []
for b in self.table:
for _, v in b:
out.append(v)
return out
# ---------------------------------------------------------------------- TMX
class TmxMap:
def __init__(self, path):
self.path = path
r = ET.parse(path).getroot()
self.w = int(r.get("width"))
self.h = int(r.get("height"))
self.tw = int(r.get("tilewidth"))
self.th = int(r.get("tileheight"))
self.layers = [] # (name, [gid]) dans l'ordre du fichier
self.objgroups = [] # (name, [obj dict])
for el in r:
if el.tag == "layer":
gids = []
data = el.find("data")
for t in data.findall("tile"):
g = t.get("gid")
if g is None:
g = t.get("id")
gids.append(int(g) if g is not None else 0)
# complète si le fichier n'écrit pas les cases vides
while len(gids) < self.w * self.h:
gids.append(0)
self.layers.append((el.get("name"), gids))
elif el.tag == "objectgroup":
objs = []
for o in el.findall("object"):
objs.append({
"type": o.get("type") or "",
"name": o.get("name") or "",
"x": int(o.get("x")),
"y": int(o.get("y")),
"w": int(o.get("width") or 0),
"h": int(o.get("height") or 0),
})
self.objgroups.append((el.get("name") or "", objs))
def load_segments():
d = {}
for cat in ("spawn", "main", "end", "extract", "lock"):
p = os.path.join(SEG_DIR, cat)
files = sorted(f for f in os.listdir(p) if f.endswith(".tmx"))
d[cat] = [TmxMap(os.path.join(p, f)) for f in files]
return d
class Conn:
def __init__(self, seg_map, obj):
self.map = seg_map
str_ = obj["type"]
self.pos = (obj["x"], obj["y"])
self.connection = None
parts = str_.split("_")
self.side = {"c": "CENTRE", "t": "TOP", "r": "RIGHT",
"b": "BOTTOM", "l": "LEFT"}.get(parts[0], "CENTRE")
self.type = int(parts[1])
if len(parts) >= 3:
self.lock = int(parts[2])
self.side_type = parts[0] + "_" + parts[1]
else:
self.lock = 0
self.side_type = str_
str_ += "_0"
self.str = str_
def is_valid_connection(self, other):
want = {"CENTRE": "CENTRE", "TOP": "BOTTOM", "RIGHT": "LEFT",
"BOTTOM": "TOP", "LEFT": "RIGHT"}[self.side]
return want == other.side and self.type == other.type
def matching_side_type(self):
pre = {"CENTRE": "c_", "TOP": "b_", "RIGHT": "l_",
"BOTTOM": "t_", "LEFT": "r_"}[self.side]
return pre + str(self.type)
class Seg:
def __init__(self, tmx):
self.map = tmx
self.pos = None
self.connectors = []
for name, objs in tmx.objgroups:
if name == "connectors":
for o in objs:
self.connectors.append(Conn(tmx, o))
self.w = tmx.w
self.h = tmx.h
# ------------------------------------------------- génération (MapManager)
def get_rand_obj(arr, rnd):
if len(arr) == 0:
return None
return arr[rnd.next_int(len(arr))]
def get_random_valid_connector(seg, for_main_path, rnd):
valid = []
for c in seg.connectors:
if c.connection is not None:
continue
if for_main_path and c.side == "LEFT":
continue
valid.append(c)
return get_rand_obj(valid, rnd)
def get_random_valid_segment(segments_by_key, key, curr_conn, for_main_path, rnd):
arr = segments_by_key.get(key)
if arr is None or len(arr) == 0:
return None
valid = []
for seg in arr:
if for_main_path:
has_left = any(c.side == "LEFT" for c in seg.connectors)
if curr_conn.side != "RIGHT" and len(seg.connectors) <= 2 and has_left:
continue
valid.append(seg)
return get_rand_obj(valid, rnd)
def add_to_grid(grid, seg):
gx = seg.pos[0] // SEG_SIZE
gy = seg.pos[1] // SEG_SIZE
for x in range(seg.w // SEG_SIZE):
for y in range(seg.h // SEG_SIZE):
grid[gx + x][gy + y] = seg
def generate_map(seed, segs):
"""Port de loadProceduralMap : renvoie (solidity, playerSpawn, segments)."""
rnd = JavaRandom(seed)
spawn_segs_h = JavaHashMap()
main_segs_h = JavaHashMap()
end_segs_h = JavaHashMap()
extract_h = JavaHashMap()
lock_h = JavaHashMap()
def index_into(h, seg, by_str):
for c in seg.connectors:
key = c.str if by_str else c.side_type
lst = h.get(key)
if lst is None:
lst = []
h.put(key, lst)
lst.append(seg)
for m in segs["spawn"]:
index_into(spawn_segs_h, Seg(m), False)
for m in segs["main"]:
index_into(main_segs_h, Seg(m), False)
for m in segs["end"]:
index_into(end_segs_h, Seg(m), False)
for m in segs["extract"]:
index_into(extract_h, Seg(m), False)
for m in segs["lock"]:
index_into(lock_h, Seg(m), True)
W = NUM_ROOMS * SEG_SIZE + (PROC_START[0] // SEG_SIZE) * SEG_SIZE
H = NUM_ROOMS * SEG_SIZE + (PROC_START[1] // SEG_SIZE) * SEG_SIZE
solid = [[0] * H for _ in range(W)]
grid_w = NUM_ROOMS + PROC_START[0] // SEG_SIZE
grid_h = NUM_ROOMS + PROC_START[1] // SEG_SIZE
seg_grid = [[None] * grid_h for _ in range(grid_w)]
rendered = []
curr = None
off_x, off_y = PROC_START
for i in range(NUM_ROOMS):
if i == 0:
lists = spawn_segs_h.values()
chosen_list = get_rand_obj(lists, rnd)
nxt = get_rand_obj(chosen_list, rnd) if chosen_list else None
if nxt is None:
continue
else:
cc = get_random_valid_connector(curr, True, rnd)
if cc is None:
continue
if i == NUM_ROOMS - 1:
nxt = get_random_valid_segment(extract_h, cc.matching_side_type(), cc, True, rnd)
else:
nxt = get_random_valid_segment(main_segs_h, cc.matching_side_type(), cc, True, rnd)
if nxt is None:
continue
valid_next = [c for c in nxt.connectors if cc.is_valid_connection(c)]
nc = get_rand_obj(valid_next, rnd)
cc.connection = nc
nc.connection = cc
if cc.side == "TOP":
off_x += cc.pos[0] // curr.map.tw - nc.pos[0] // nxt.map.tw
off_y -= nxt.h
elif cc.side == "RIGHT":
off_x += curr.w
off_y += cc.pos[1] // curr.map.th - nc.pos[1] // nxt.map.th
elif cc.side == "BOTTOM":
off_x += cc.pos[0] // curr.map.tw - nc.pos[0] // nxt.map.tw
off_y += curr.h
elif cc.side == "LEFT":
off_x -= nxt.w
off_y += cc.pos[1] // curr.map.th - nc.pos[1] // nxt.map.th
nxt.pos = (off_x, off_y)
rendered.append(nxt)
add_to_grid(seg_grid, nxt)
curr = nxt
# verrous sur connecteurs libres
locks_to_render = []
for seg in rendered:
for c in seg.connectors:
if c.connection is not None:
continue
lst = lock_h.get(c.str)
if lst is None:
continue
lt = get_rand_obj(lst, rnd)
if lt is None:
continue
lt.pos = seg.pos
if len(lt.connectors) != 1:
pass # log 2017, aucun effet
c.connection = lt.connectors[0]
lt.connectors[0].connection = c
locks_to_render.append(lt)
rendered.extend(locks_to_render)
player_spawn = None
for seg in rendered:
ox, oy = seg.pos
for name, gids in seg.map.layers:
if name != "main":
continue
for i, g in enumerate(gids):
if g <= 0:
continue
col, row = i % seg.map.w, i // seg.map.w
x, y = col + ox, row + oy
if 0 <= x < W and 0 <= y < H:
solid[x][y] = 1
for gname, objs in seg.map.objgroups:
if gname in ("connectors", "enemies", "spawns"):
continue
for o in objs:
px = (o["x"] + ox * SEG_SIZE) * 6.25
py = (o["y"] + oy * SEG_SIZE) * 6.25
if o["type"] == "player_spawn":
player_spawn = (px, py)
if "door" in o["type"]:
for (dx, dy) in ((0, 0), (1, 0), (0, 4), (1, 4)):
try:
solid[int(px / 100) + dx][int(py / 100) + dy] = 1
except IndexError:
pass
return solid, player_spawn, rendered
# ------------------------------------------------------------ NavMesh (port)
NONE_, PLATFORM, LEFT_EDGE, RIGHT_EDGE, SOLO = 0, 1, 2, 3, 4
WALK, FALL, JUMP = 0, 1, 2
class NP:
__slots__ = ("id", "x", "y", "type", "links", "index")
def __init__(self, i, j, id_):
self.id = id_
self.x = i * 100
self.y = j * 100
self.type = NONE_
self.links = [] # (type, target)
self.index = 0
class NavMeshSim:
def __init__(self, solid_map):
self.solid = solid_map
self.W = len(solid_map)
self.H = len(solid_map[0])
self.count_links = {WALK: 0, FALL: 0, JUMP: 0}
def coll(self, x, y):
return x >= self.W or x < 0 or y >= self.H or y < 0 or self.solid[x][y] == 1
def add_link(self, x1, y1, x2, y2, t):
if x2 < 0 or x2 >= self.W or y2 < 0 or y2 >= self.H:
return
a, b = self.nav[x1][y1], self.nav[x2][y2]
a.links.append((t, b))
b.links.append((t, a))
self.count_links[t] += 2
def fill_in(self, spawn_cell):
solid = self.solid
W, H = self.W, self.H
stack = [spawn_cell]
while stack:
x, y = stack.pop()
if solid[x][y] >= 1:
continue
if solid[x][y] == 0:
solid[x][y] = 2
if x > 0:
stack.append((x - 1, y))
if x < W - 2:
stack.append((x + 1, y))
if y > 0:
stack.append((x, y - 1))
if y < H - 2:
stack.append((x, y + 1))
def init(self, spawn_px, fix_notch=False, fix_left_bound=False, fix_shaft1=False):
self.fill_in((int(spawn_px[0] / 100), int(spawn_px[1] / 100)))
s = self.solid
for i in range(self.W):
for j in range(self.H):
if s[i][j] == 0:
s[i][j] = 1
if s[i][j] == 2:
s[i][j] = 0
self.nav = [[NP(i, j, i * self.H + j) for j in range(self.H)]
for i in range(self.W)]
nav = self.nav
for y in range(self.H):
started = False
for x in range(self.W):
if not started:
if not self.coll(x, y) and self.coll(x, y + 1) and not self.coll(x, y - 1):
nav[x][y].type = LEFT_EDGE
started = True
if started:
if self.coll(x + 1, y + 1) and not self.coll(x + 1, y) \
and nav[x][y].type != LEFT_EDGE:
nav[x][y].type = PLATFORM
self.add_link(x, y, x - 1, y, WALK)
if (not self.coll(x + 1, y + 1)) or self.coll(x + 1, y):
if nav[x][y].type == LEFT_EDGE:
nav[x][y].type = SOLO
else:
nav[x][y].type = RIGHT_EDGE
self.add_link(x, y, x - 1, y, WALK)
started = False
for x in range(self.W):
for y in range(self.H):
if nav[x][y].type in (RIGHT_EDGE, SOLO):
if fix_shaft1:
# puits à 1 colonne : l'ennemi (200px) marche hors du
# bord, son corps déborde sur x+1, il tombe le long
# de la paroi x+2 (même solide) et atterrit sur le
# sol sous x+1
ok = (not self.coll(x + 1, y) and not self.coll(x + 1, y - 1))
cols = (x + 1,)
else:
ok = (x + 2 < self.W and not self.coll(x + 1, y) and not self.coll(x + 2, y)
and not self.coll(x + 1, y - 1) and not self.coll(x + 2, y - 1))
cols = (x + 1, x + 2)
if ok:
yt = y + 1
while yt < self.H - 1 and all(not self.coll(c, yt) for c in cols):
yt += 1
yt -= 1
if not fix_notch:
self.add_link(x, y, x + 1, yt, FALL)
landing = x + 1
else:
# miroir exact de la branche LEFT 2017 : atterrir
# sur la colonne qui a un sol sous yt+1
if self.coll(x + 1, yt + 1):
landing = x + 1
elif len(cols) > 1 and self.coll(x + 2, yt + 1):
landing = x + 2
else:
landing = x + 1
self.add_link(x, y, landing, yt, FALL)
if yt - (y + 1) < 3:
self.add_link(x, y, landing, yt, JUMP)
if nav[x][y].type in (LEFT_EDGE, SOLO):
cond = (x - 2 >= 0) if fix_left_bound else (x - 2 > 0)
if cond and not self.coll(x - 1, y) and not self.coll(x - 2, y) \
and not self.coll(x - 1, y - 1) and not self.coll(x - 2, y - 1):
yt = y + 1
while yt < self.H - 1 and not self.coll(x - 1, yt) and not self.coll(x - 2, yt):
yt += 1
yt -= 1
if self.coll(x - 2, yt + 1):
self.add_link(x, y, x - 2, yt, FALL)
else:
self.add_link(x, y, x - 1, yt, FALL)
if yt - (y + 1) < 3:
landing = (x - 2 if self.coll(x - 2, yt + 1) else x - 1)
self.add_link(x, y, landing, yt, JUMP)
for x in range(self.W):
for y in range(self.H):
if nav[x][y].type in (RIGHT_EDGE, SOLO) and self.coll(x + 1, y):
for i in range(1, 4):
if self.is_jump_landing(x + 1, y - i):
self.add_link(x, y, x + 1, y - i, JUMP)
break
if nav[x][y].type in (LEFT_EDGE, SOLO) and self.coll(x - 1, y):
for i in range(1, 4):
if self.is_jump_landing(x - 1, y - i):
self.add_link(x, y, x - 1, y - i, JUMP)
break
def is_jump_landing(self, x, y):
return not self.coll(x, y) and not self.coll(x, y - 1) and self.coll(x, y, )
def get_nav_point(self, x, y):
i = int(round(x / 100.0))
j = int(round(y / 100.0)) + 1
if i < 0 or i >= self.W or j < 0 or j >= self.H:
return None
return self.nav[i][j]
# ---- BFS (getPath) port exact
def get_path(self, start, end):
if start is None or end is None:
return []
for p in self._altered:
p.index = 0
self._altered = []
end.index = -1
self._altered.append(end)
self._max_index = 0
self._found = False
q = [start]
idx = [1]
while q:
self._do_index(q.pop(0), idx.pop(0), q, idx)
if self._closest.id != end.id:
return []
path = [None] * self._max_index
if self._max_index == 0:
return path
if self._max_index == 1:
path[0] = end
return path
path[self._max_index - 1] = end
for i in range(self._max_index - 2, -1, -1):
for (t, tgt) in path[i + 1].links:
if tgt.index == i + 1 \
and not (tgt.y > path[i + 1].y and t == FALL) \
and not (tgt.y < path[i + 1].y and t == JUMP):
path[i] = tgt
break
return path
def _do_index(self, p, index, q, idx):
if self._found or (p.index > 0 and index >= p.index):
return
if p.index == -1:
p.index = index
self._max_index = index
self._closest = p
self._found = True
self._altered.append(p)
q.clear()
idx.clear()
return
p.index = index
self._altered.append(p)
if index > self._max_index:
self._max_index = index
self._closest = p
for (t, tgt) in p.links:
if not (t == FALL and tgt.y < p.y) and not (t == JUMP and tgt.y > p.y):
if tgt.index <= 0 or index + 1 < tgt.index:
q.append(tgt)
idx.append(index + 1)
# ---- ensemble joignable (direction filtré), pour le diagnostic
def reachable(self, start):
seen = {start}
q = [start]
while q:
p = q.pop()
for (t, tgt) in p.links:
if t == FALL and tgt.y < p.y:
continue
if t == JUMP and tgt.y > p.y:
continue
if tgt not in seen:
seen.add(tgt)
q.append(tgt)
return seen
def is_jump_landing(self, x, y):
return not self.coll(x, y) and not self.coll(x, y - 1) and self.coll(x, y + 1)
NavMeshSim.__init__._orig = None
def _fix_init(cls):
orig = cls.init
def init(self, spawn_px, **kw):
self._altered = []
self._closest = None
self._max_index = 0
self._found = False
orig(self, spawn_px, **kw)
cls.init = init
_fix_init(NavMeshSim)
def standable(sim, i, j):
"""Cellule où une entité 2x2 (ennemi) tient debout : libre + tête libre + sol dessous."""
return not sim.coll(i, j) and not sim.coll(i, j - 1) and sim.coll(i, j + 1)
def ground_row(sim, col, from_row):
for r in range(max(from_row, 0), sim.H):
if sim.coll(col, r):
return r
return None
def exterminate_spawn(sim, player_cell, rnd):
"""Port de la logique de spawn Exterminate : renvoie (pos ennemi, étage sol) ou None."""
pi, pj = player_cell
px, py = pi * 100.0, pj * 100.0 - 100.0 # joueur debout sur le sol pj+1
player_floor_row = pj + 1
player_floor = Physics.raycast(sim, px, py - 5000) # sol de référence du joueur
if player_floor is None:
return None
side = 1.0 if rnd.next_int(2) == 0 else -1.0
fx = max(200.0, px + side * (1500 + rnd.next_int(900) * 1.0))
pos = (fx, py - 150 - rnd.next_int(100))
for attempt in range(6):
s = 1.0 if attempt % 2 == 0 else -1.0
spawn_x = px + s * (1500 + rnd.next_int(900))
if spawn_x < 200:
continue
col = int(spawn_x / 100)
start_row = int((py - 5000) / 100)
r = ground_row(sim, col, start_row)
if r is None:
continue
if abs(r * 100 - player_floor) <= 1500: # player_floor déjà en px
pos = (spawn_x, r * 100 - 100.0)
return pos, r
return None
class Physics:
@staticmethod
def raycast(sim, x, y_start):
col = int(x / 100)
if col < 0 or col >= sim.W:
return None
start_row = int(y_start / 100)
r = ground_row(sim, col, start_row)
return r * 100 if r is not None else None
def fmt_cell(c):
return "(%d,%d)" % (c[0], c[1])
def _resolve_links(sim, np):
"""Fix A (port du fix Java) : cellule sans liens -> voisin i±1 même ligne."""
if np is None or np.links:
return np
i, j = np.x // 100, np.y // 100
for d in (-1, 1):
if 0 <= i + d < sim.W and sim.nav[i + d][j].links:
return sim.nav[i + d][j]
return np
def analyze_seed(seed, segs, verbose=False, use_fallback=False, fixes=False):
solid, tmx_spawn_px, segs_used = generate_map(seed, segs)
# Fidélité ExterminateMission.load() : playerSpawn=(20,20) est posé AVANT
# loadProceduralMap -> NavMesh.init (fillIn) part de la cellule (0,0) ;
# le spawn réel (100, 25700) n'est posé qu'APRES NavMesh.init (l.65-67).
sim = NavMeshSim(solid)
sim.init((20.0, 20.0), fix_notch=fixes, fix_left_bound=fixes)
m, f, j_ = sim.count_links[WALK], sim.count_links[FALL], sim.count_links[JUMP]
# cellules debout
stand = [(i, j) for i in range(sim.W) for j in range(sim.H) if standable(sim, i, j)]
# spawn joueur reel (Exterminate : PROC_START.x*16*6.25+100, PROC_START.y*16*6.25+100)
spawn_px = (100.0, 25700.0)
rnd = JavaRandom(seed * 2654435761 % (1 << 31))
results = []
# échantillon de positions joueur : spawn + 40 cellules debout aléatoires
player_cells = [(int(spawn_px[0] / 100), int(spawn_px[1] / 100) + 1)]
player_cells += [stand[rnd.next_int(len(stand))] for _ in range(40)]
for pc in player_cells:
sp = exterminate_spawn(sim, pc, rnd)
if sp is None:
continue
pos, erow = sp
# mapping FIDELE au jeu : getNavPoint -> round(x/100), j=round(y/100)+1
# (ennemi stabilisé debout : pos.y = erow*100-200 -> j = erow-1)
ecol = int(round(pos[0] / 100.0))
ecell = (ecol, erow - 1)
en = sim.nav[ecell[0]][ecell[1]]
# position du joueur : pos.x quelconque autour de sa cellule (il marche)
pxj = pc[0] * 100 + rnd.next_int(200) - 100
pn = sim.get_nav_point(float(pxj), float(pc[1] * 100 - 100))
if en is None or pn is None:
results.append({"player": pc, "enemy": ecell, "status": "hors_grille"})
continue
if use_fallback:
en = _resolve_links(sim, en)
pn = _resolve_links(sim, pn)
path = sim.get_path(en, pn)
droppx = abs((ecell[1] - pc[1])) * 100
if len(path) > 0:
results.append({"player": pc, "enemy": ecell, "status": "ok",
"len": len(path), "drop": droppx})
else:
reach = sim.reachable(en)
ok_targets = [(c.x // 100, c.y // 100) for c in reach if standable(sim, c.x // 100, c.y // 100)]
break_row = None
if ok_targets:
break_row = max(c[1] for c in ok_targets) # plus bas atteint
results.append({"player": pc, "enemy": ecell, "status": "aucun_chemin",
"drop": droppx, "reach_size": len(reach),
"reach_standable": len(ok_targets),
"reach_bottom": break_row})
return {"seed": seed, "m": m, "f": f, "j": j_, "results": results}
def main():
n_seeds = int(sys.argv[1]) if len(sys.argv) > 1 else 30
mode = sys.argv[2] if len(sys.argv) > 2 else "base" # base | fb | fix
fixes = mode == "fix"
use_fb = mode in ("fb", "fix")
segs = load_segments()
print("segments : spawn=%d main=%d end=%d extract=%d lock=%d [%s]" %
(tuple(len(segs[c]) for c in ("spawn", "main", "end", "extract", "lock")) + (mode,)))
tot = {"ok": 0, "aucun_chemin": 0, "spawn_solide": 0, "hors_grille": 0}
drops_fail, drops_ok = [], []
reach_bottoms = []
link_stats = []
for k in range(n_seeds):
seed = 1_000_000 + k * 7919
r = analyze_seed(seed, segs, use_fallback=use_fb, fixes=fixes)
if "error" in r:
print("seed %d : ERREUR %s" % (seed, r["error"]))
continue
link_stats.append((r["m"], r["f"], r["j"]))
for res in r["results"]:
st = res["status"]
tot[st] = tot.get(st, 0) + 1
if st == "ok":
drops_ok.append(res["drop"])
elif st == "aucun_chemin":
drops_fail.append(res["drop"])
if res.get("reach_bottom") is not None:
reach_bottoms.append(res["reach_bottom"] - res["enemy"][1])
print("\n=== stats sur %d seeds ===" % n_seeds)
if link_stats:
avg = lambda ix: sum(s[ix] for s in link_stats) / len(link_stats)
print("liens moyens : marche=%.0f chute=%.0f saut=%.0f (comptés 2x)" %
(avg(0), avg(1), avg(2)))
print("couples (spawn ennemi, joueur) : %s" % tot)
if drops_ok:
print("chutes RÉUSSIES : n=%d, Δy moyen=%.0f px, max=%.0f" %
(len(drops_ok), sum(drops_ok) / len(drops_ok), max(drops_ok)))
if drops_fail:
print("chutes ÉCHOUÉES : n=%d, Δy moyen=%.0f px" %
(len(drops_fail), sum(drops_fail) / len(drops_fail)))
if reach_bottoms:
reach_bottoms.sort()
print("profondeur max atteignable depuis l'ennemi (Δy vers le bas, px) : "
"médiane=%d max=%d" % (reach_bottoms[len(reach_bottoms) // 2], max(reach_bottoms)))
if __name__ == "__main__":
main()