Files
Forge-Engine/tests/game/test_personnage_commands.py
williamandClaude Sonnet 5 b2e933f322
Build and deploy / test-python (push) Successful in 11m12s
Build and deploy / test-js (push) Successful in 53s
Build and deploy / lint-python (push) Successful in 3m56s
Build and deploy / lint-js (push) Successful in 3m1s
Build and deploy / build-and-push (push) Skipped
Build and deploy / deploy (push) Skipped
Build and deploy / sonarqube (push) Failing after 3m58s
Reorganisation game/document : renommage screens->game_engine + sous-dossiers game/ dans routes, scripts, static, templates, tests
Prepare la scission a venir entre l'editeur Jeu 2D et le futur editeur
Support de formation (voir docs/plan/PLAN.md), sans toucher a
l'architecture en couches existante :

- screens/ renomme en game_engine/ (nom clair pour le moteur du jeu 2D,
  avant l'arrivee d'un second "moteur" cote document) : ~85 imports
  corriges, contrat import-linter mis a jour, meme forme de couches.
- routes/, scripts/, static/, templates/, tests/ : tout ce qui est
  propre au jeu 2D deplace dans un sous-dossier game/ de chacun
  (routes/game/, static/game/, templates/game/, tests/game/,
  scripts/game/) ; ce qui est partage par le site (auth, onboarding,
  dashboard, uploads, db/) reste a la racine de chaque dossier. Un
  sous-dossier document/ (vide) cree dans chacun pour le futur chantier.
- styles/ volontairement inchange : les 3 fichiers sources sont
  concatenes en un seul static/style.css charge par tout le site,
  scinder leur CONTENU (editeur vs partage) serait un refactor CSS
  distinct, pas un deplacement mecanique.
- Chaine d'export SCORM (publish/build_scorm_package.py) mise a jour en
  profondeur : copie des assets, URLs d'icones relatives a
  static/style.css (qui ne bouge pas), manifeste, wrapper SCORM.
- Deux regressions d'un sweep de renommage anterieur corrigees au passage
  (screens.js/screens/scene-objects incorrectement convertis en
  game_engine.js/game_engine/scene-objects dans des commentaires).
- Effet de bord Windows decouvert et corrige : git mv + Path.write_text
  convertissent des fichiers en CRLF (core.autocrlf=true) - ~189 fichiers
  normalises en LF.
- .eslintrc.json/package.json : uniquement les chemins de glob mis a jour
  (static/game/js/...) ; la preparation eslint-plugin-unicorn du lot 7
  reste volontairement non committee (package-lock.json restaure a la
  version precedente).

Verifications : ruff, mypy --strict (391 fichiers), vulture, bandit,
lint-imports tous verts ; 591/591 tests Python, 276/276 tests JS ;
demarrage serveur + requetes HTTP manuelles confirmant que les assets
deplaces repondent en 200 au nouvel emplacement et 404 a l'ancien.

SKIP=djlint : backlog H021 (styles inline) deja documente comme dette
assumee dans CODE_QUALITY.md section 6, aucun template touche par ce
commit au-dela d'un deplacement de fichier.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-19 12:27:53 +02:00

189 lines
7.8 KiB
Python

"""Déplacement/animation automatiques d'un personnage posé sur une scène
2D (voir static/game/js/play/personnage-controller.js) : ZQSD + E par défaut,
sans le moindre nœud de flow à poser — le panneau "🕹️ Commandes"
(templates/game/scene_edit.html) permet seulement de les remapper/bloquer un
axe. Ce fichier teste la couche serveur (défauts, route de sauvegarde,
exposition dans full_game_payload) ; static/game/js/play/__tests__/
personnage-controller.test.js teste le comportement client (tick,
bornage, blocage d'axe)."""
import re
from collections.abc import Callable
from typing import Any
from flask.testing import FlaskClient
import game_engine
from tests.conftest import not_none
def _create_jeu2d_game(
client: FlaskClient, tmp_game_slug_cleanup: Callable[[str], str], name: str = "pytest_personnage_cmd"
) -> Any:
resp = client.post("/games/new", data={"name": name}, follow_redirects=False)
slug = tmp_game_slug_cleanup(resp.headers["Location"].rstrip("/").split("/")[-1])
screen_id = game_engine.create_screen(slug, "Scène 1", kind="jeu_2d")
return slug, screen_id
def _add_personnage(client: FlaskClient, slug: str, screen_id: int, forge_character: str = "zombie") -> Any:
resp = client.post(
f"/game/{slug}/screens/{screen_id}/scene-objects/add",
data={"kind": "personnage", "forge_character": forge_character},
follow_redirects=False,
)
assert resp.status_code == 302, resp.data
return int(not_none(re.search(r"selected=(\d+)", resp.headers["Location"])).group(1))
def test_freshly_placed_personnage_gets_default_zqsd_commands(
client: FlaskClient, tmp_game_slug_cleanup: Callable[[str], str]
) -> None:
slug, screen_id = _create_jeu2d_game(client, tmp_game_slug_cleanup)
obj_id = _add_personnage(client, slug, screen_id)
obj = not_none(game_engine.get_scene_object(slug, obj_id))
assert game_engine.resolve_personnage_commands(obj) == game_engine.DEFAULT_PERSONNAGE_COMMANDS
def test_commands_route_persists_remapped_keys_and_axis_lock(
client: FlaskClient, tmp_game_slug_cleanup: Callable[[str], str]
) -> None:
slug, screen_id = _create_jeu2d_game(client, tmp_game_slug_cleanup)
obj_id = _add_personnage(client, slug, screen_id)
resp = client.post(
f"/game/{slug}/scene-objects/{obj_id}/commandes",
data=(
'{"haut": "ArrowUp", "bas": "ArrowDown", "gauche": "ArrowLeft", "droite": "ArrowRight", '
'"interagir": " ", "axe": "horizontal", "vitesse": 8}'
),
content_type="application/json",
)
assert resp.status_code == 200
assert resp.get_json()["ok"] is True
obj = not_none(game_engine.get_scene_object(slug, obj_id))
commands = game_engine.resolve_personnage_commands(obj)
assert commands == {
"haut": "ArrowUp",
"bas": "ArrowDown",
"gauche": "ArrowLeft",
"droite": "ArrowRight",
"interagir": " ",
"axe": "horizontal",
"vitesse": 8,
"extra": [],
}
def test_commands_route_persists_extra_animation_bound_keys(
client: FlaskClient, tmp_game_slug_cleanup: Callable[[str], str]
) -> None:
"""Touches supplémentaires (sauter, attaquer...) — bug remonté par
l'utilisateur : au-delà des 4 touches de déplacement et de
"interagir", il manquait un moyen de lier une touche à N'IMPORTE
QUELLE autre pose du personnage."""
slug, screen_id = _create_jeu2d_game(client, tmp_game_slug_cleanup)
obj_id = _add_personnage(client, slug, screen_id)
resp = client.post(
f"/game/{slug}/scene-objects/{obj_id}/commandes",
data='{"extra": [{"touche": "j", "animation": "jump"}, {"touche": "a", "animation": "attack"}]}',
content_type="application/json",
)
commands = resp.get_json()["commands"]
assert commands["extra"] == [{"touche": "j", "animation": "jump"}, {"touche": "a", "animation": "attack"}]
obj = not_none(game_engine.get_scene_object(slug, obj_id))
assert game_engine.resolve_personnage_commands(obj)["extra"] == commands["extra"]
def test_commands_route_drops_malformed_extra_entries(
client: FlaskClient, tmp_game_slug_cleanup: Callable[[str], str]
) -> None:
"""Une entrée sans touche/animation, un doublon de type, ou une liste
qui n'en est pas une : ignorée plutôt que de planter ou de polluer le
panneau avec une ligne inutilisable côté client."""
slug, screen_id = _create_jeu2d_game(client, tmp_game_slug_cleanup)
obj_id = _add_personnage(client, slug, screen_id)
resp = client.post(
f"/game/{slug}/scene-objects/{obj_id}/commandes",
data=(
'{"extra": [{"touche": "j", "animation": "jump"}, {"touche": ""}, '
'{"animation": "attack"}, "pas un objet", 42]}'
),
content_type="application/json",
)
assert resp.get_json()["commands"]["extra"] == [{"touche": "j", "animation": "jump"}]
resp = client.post(
f"/game/{slug}/scene-objects/{obj_id}/commandes",
data='{"extra": "pas une liste"}',
content_type="application/json",
)
assert resp.get_json()["commands"]["extra"] == []
def test_commands_route_rejects_invalid_axis_and_clamps_speed(
client: FlaskClient, tmp_game_slug_cleanup: Callable[[str], str]
) -> None:
"""Un axe inconnu retombe sur "libre", une vitesse hors bornes est
ramenée dans [1, 20] — jamais une valeur qui planterait le calcul
d'un déplacement côté client (voir personnage-controller.js)."""
slug, screen_id = _create_jeu2d_game(client, tmp_game_slug_cleanup)
obj_id = _add_personnage(client, slug, screen_id)
resp = client.post(
f"/game/{slug}/scene-objects/{obj_id}/commandes",
data='{"axe": "diagonal", "vitesse": 999}',
content_type="application/json",
)
commands = resp.get_json()["commands"]
assert commands["axe"] == "libre"
assert commands["vitesse"] == 20
def test_commands_route_falls_back_to_defaults_for_blank_or_missing_keys(
client: FlaskClient, tmp_game_slug_cleanup: Callable[[str], str]
) -> None:
""" "" (chaîne vide)/absent retombe sur le défaut — mais PAS " "
(Espace), une valeur ev.key parfaitement valide côté client pour
"interagir" (voir la note dans routes/game/scenes/scene_object_commands.py)."""
slug, screen_id = _create_jeu2d_game(client, tmp_game_slug_cleanup)
obj_id = _add_personnage(client, slug, screen_id)
resp = client.post(
f"/game/{slug}/scene-objects/{obj_id}/commandes",
data='{"haut": "", "interagir": " "}',
content_type="application/json",
)
commands = resp.get_json()["commands"]
assert commands["haut"] == game_engine.DEFAULT_PERSONNAGE_COMMANDS["haut"]
assert commands["bas"] == game_engine.DEFAULT_PERSONNAGE_COMMANDS["bas"] # absent du body
assert commands["interagir"] == " "
def test_commands_route_404s_for_missing_object(client: FlaskClient, game: str) -> None:
resp = client.post(
f"/game/{game}/scene-objects/999999/commandes",
data="{}",
content_type="application/json",
)
assert resp.status_code == 404
def test_full_game_payload_exposes_resolved_commands_for_personnage_objects(
client: FlaskClient, tmp_game_slug_cleanup: Callable[[str], str]
) -> None:
slug, screen_id = _create_jeu2d_game(client, tmp_game_slug_cleanup)
_add_personnage(client, slug, screen_id)
game_engine.add_scene_object(slug, screen_id, kind="decor") # jamais de commandes sur un décor
payload = game_engine.full_game_payload(slug)
scene_screen = next(s for s in payload["screens"] if s["id"] == screen_id)
personnage_obj = next(o for o in scene_screen["elements"] if o["kind"] == "personnage")
decor_obj = next(o for o in scene_screen["elements"] if o["kind"] == "decor")
assert personnage_obj["personnage_commandes"] == game_engine.DEFAULT_PERSONNAGE_COMMANDS
assert "personnage_commandes" not in decor_obj