mirror of
https://github.com/deunix-educ/PyQuest.git
synced 2026-11-25 08:19:44 +01:00
Add author editor data model (LevelDraft) with exact round-trip and YAML export; validate_levels --file
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,240 @@
|
|||||||
|
// Modèle de formulaire de l'éditeur de niveaux ⇄ niveau au format du schéma.
|
||||||
|
// Le formulaire manipule des champs « complets » (textes fr/en, indices sur des lignes, valeurs en texte) ;
|
||||||
|
// toLevel() produit l'objet propre du schéma (champs facultatifs vides omis, ordre des clés stable) et
|
||||||
|
// fromLevel() fait l'inverse. toLevel(fromLevel(niveau)) redonne le niveau d'origine (testé sur tous les niveaux).
|
||||||
|
|
||||||
|
import yaml from '../lib/js-yaml/js-yaml.mjs';
|
||||||
|
|
||||||
|
export const REWARD_SOUNDS = ['success_small', 'success_big', 'level_unlocked'];
|
||||||
|
export const PYTHON_TYPES = ['str', 'int', 'float', 'bool', 'list', 'dict'];
|
||||||
|
|
||||||
|
/** Kinds éditables et champs qu'ils utilisent. */
|
||||||
|
export const TEST_KINDS = {
|
||||||
|
no_syntax_error: { name: false, value: false },
|
||||||
|
stdout_equals: { name: false, value: 'text' },
|
||||||
|
stdout_contains: { name: false, value: 'text' },
|
||||||
|
stdout_matches_regex: { name: false, value: 'text' },
|
||||||
|
code_contains: { name: false, value: 'text' },
|
||||||
|
var_equals: { name: true, value: 'typed' },
|
||||||
|
var_type_is: { name: true, value: 'type' },
|
||||||
|
};
|
||||||
|
|
||||||
|
const i18n = (fr = '', en = '') => ({ fr, en });
|
||||||
|
|
||||||
|
export function emptyLevelModel() {
|
||||||
|
return {
|
||||||
|
id: '',
|
||||||
|
title: i18n(),
|
||||||
|
difficulty: 1,
|
||||||
|
xp: 30,
|
||||||
|
requires: [],
|
||||||
|
steps: [],
|
||||||
|
mission: { title: i18n(), goal: i18n(), starter: '', tests: [], solution: '', rewardSound: 'success_small' },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function newTestModel(kind = 'stdout_equals') {
|
||||||
|
return { kind, name: '', value: '', valueType: 'text', inputs: '', message: i18n() };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function newStepModel(type) {
|
||||||
|
return type === 'explain'
|
||||||
|
? { type: 'explain', text: i18n(), voice: true, image: '' }
|
||||||
|
: { type: 'code', instruction: i18n(), starter: '', tests: [newTestModel()], hints: i18n(), solution: '' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- modèle -> niveau ------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
const text = ({ fr, en }) => (en ? { fr, en } : { fr });
|
||||||
|
const lines = (value) => value.split('\n').map((line) => line.trim()).filter(Boolean);
|
||||||
|
|
||||||
|
/** Saisies scriptées : une par ligne, les lignes vides finales sont ignorées (celles du milieu sont des saisies vides). */
|
||||||
|
function inputLines(value) {
|
||||||
|
const all = value.split('\n');
|
||||||
|
while (all.length > 0 && all.at(-1) === '') {
|
||||||
|
all.pop();
|
||||||
|
}
|
||||||
|
return all;
|
||||||
|
}
|
||||||
|
|
||||||
|
function testToLevel(test) {
|
||||||
|
const spec = TEST_KINDS[test.kind];
|
||||||
|
const out = { kind: test.kind };
|
||||||
|
if (spec.name) {
|
||||||
|
out.name = test.name;
|
||||||
|
}
|
||||||
|
if (spec.value === 'typed') {
|
||||||
|
out.value = test.valueType === 'number' && test.value.trim() !== '' && !Number.isNaN(Number(test.value)) ? Number(test.value) : test.valueType === 'boolean' ? test.value === 'true' : test.value;
|
||||||
|
} else if (spec.value) {
|
||||||
|
out.value = test.value;
|
||||||
|
}
|
||||||
|
const inputs = inputLines(test.inputs);
|
||||||
|
if (inputs.length > 0) {
|
||||||
|
out.inputs = inputs;
|
||||||
|
}
|
||||||
|
if (test.message.fr || test.message.en) {
|
||||||
|
out.message = text(test.message);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function stepToLevel(step) {
|
||||||
|
if (step.type === 'explain') {
|
||||||
|
const out = { type: 'explain' };
|
||||||
|
if (step.voice) {
|
||||||
|
out.voice = true;
|
||||||
|
}
|
||||||
|
out.text = text(step.text);
|
||||||
|
if (step.image.trim()) {
|
||||||
|
out.image = step.image.trim();
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
const out = { type: 'code', starter: step.starter, instruction: text(step.instruction), tests: step.tests.map(testToLevel) };
|
||||||
|
const hints = {};
|
||||||
|
for (const lang of ['fr', 'en']) {
|
||||||
|
const list = lines(step.hints[lang]);
|
||||||
|
if (list.length > 0) {
|
||||||
|
hints[lang] = list;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (Object.keys(hints).length > 0) {
|
||||||
|
out.hints = hints;
|
||||||
|
}
|
||||||
|
if (step.solution.trim()) {
|
||||||
|
out.solution = step.solution;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Modèle de formulaire -> niveau au format du schéma. */
|
||||||
|
export function toLevel(model) {
|
||||||
|
const { mission } = model;
|
||||||
|
const outMission = { title: text(mission.title), goal: text(mission.goal) };
|
||||||
|
if (mission.starter.trim()) {
|
||||||
|
outMission.starter = mission.starter;
|
||||||
|
}
|
||||||
|
if (mission.tests.length > 0) {
|
||||||
|
outMission.tests = mission.tests.map(testToLevel);
|
||||||
|
}
|
||||||
|
if (mission.solution.trim()) {
|
||||||
|
outMission.solution = mission.solution;
|
||||||
|
}
|
||||||
|
if (mission.rewardSound) {
|
||||||
|
outMission.reward_sound = mission.rewardSound;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
id: model.id,
|
||||||
|
title: text(model.title),
|
||||||
|
difficulty: model.difficulty,
|
||||||
|
xp: model.xp,
|
||||||
|
requires: [...model.requires],
|
||||||
|
steps: model.steps.map(stepToLevel),
|
||||||
|
mission: outMission,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- niveau -> modèle ------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
const fromText = (value) => i18n(value?.fr ?? '', value?.en ?? '');
|
||||||
|
const fromHints = (hints) => i18n((hints?.fr ?? []).join('\n'), (hints?.en ?? []).join('\n'));
|
||||||
|
|
||||||
|
function testFromLevel(test) {
|
||||||
|
const model = newTestModel(test.kind);
|
||||||
|
model.name = test.name ?? '';
|
||||||
|
const { value } = test;
|
||||||
|
if (typeof value === 'number') {
|
||||||
|
model.valueType = 'number';
|
||||||
|
model.value = String(value);
|
||||||
|
} else if (typeof value === 'boolean') {
|
||||||
|
model.valueType = 'boolean';
|
||||||
|
model.value = String(value);
|
||||||
|
} else {
|
||||||
|
model.value = value ?? '';
|
||||||
|
}
|
||||||
|
model.inputs = (test.inputs ?? []).join('\n');
|
||||||
|
model.message = fromText(test.message);
|
||||||
|
return model;
|
||||||
|
}
|
||||||
|
|
||||||
|
function stepFromLevel(step) {
|
||||||
|
if (step.type === 'explain') {
|
||||||
|
return { type: 'explain', text: fromText(step.text), voice: Boolean(step.voice), image: step.image ?? '' };
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
type: 'code',
|
||||||
|
instruction: fromText(step.instruction),
|
||||||
|
starter: step.starter ?? '',
|
||||||
|
tests: (step.tests ?? []).map(testFromLevel),
|
||||||
|
hints: fromHints(step.hints),
|
||||||
|
solution: step.solution ?? '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Niveau au format du schéma -> modèle de formulaire (tolère les champs absents). */
|
||||||
|
export function fromLevel(level) {
|
||||||
|
const mission = level.mission ?? {};
|
||||||
|
return {
|
||||||
|
id: level.id ?? '',
|
||||||
|
title: fromText(level.title),
|
||||||
|
difficulty: level.difficulty ?? 1,
|
||||||
|
xp: level.xp ?? 0,
|
||||||
|
requires: [...(level.requires ?? [])],
|
||||||
|
steps: (level.steps ?? []).map(stepFromLevel),
|
||||||
|
mission: {
|
||||||
|
title: fromText(mission.title),
|
||||||
|
goal: fromText(mission.goal),
|
||||||
|
starter: mission.starter ?? '',
|
||||||
|
tests: (mission.tests ?? []).map(testFromLevel),
|
||||||
|
solution: mission.solution ?? '',
|
||||||
|
rewardSound: mission.reward_sound ?? '',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- YAML ------------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* js-yaml écrit chaque élément de liste sur deux lignes (« - » seul puis le contenu indenté de 4 espaces).
|
||||||
|
* On le ramène au style des niveaux écrits à la main : « - clé: valeur » avec le reste aligné deux colonnes
|
||||||
|
* à droite du tiret.
|
||||||
|
*/
|
||||||
|
function compactListItems(source) {
|
||||||
|
const input = source.split('\n');
|
||||||
|
const output = [];
|
||||||
|
const indentOf = (line) => line.length - line.trimStart().length;
|
||||||
|
for (let i = 0; i < input.length; i++) {
|
||||||
|
const line = input[i];
|
||||||
|
if (/(^|\s)\|[-+]?$/.test(line)) {
|
||||||
|
// Bloc littéral (code, texte multiligne) : copié tel quel, même s'il contient une ligne « - ».
|
||||||
|
output.push(line);
|
||||||
|
while (i + 1 < input.length && (input[i + 1] === '' || indentOf(input[i + 1]) > indentOf(line))) {
|
||||||
|
output.push(input[++i]);
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!/^\s*-$/.test(line)) {
|
||||||
|
output.push(line);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const base = indentOf(line);
|
||||||
|
const block = [];
|
||||||
|
while (i + 1 < input.length && (input[i + 1] === '' || indentOf(input[i + 1]) > base)) {
|
||||||
|
block.push(input[++i]);
|
||||||
|
}
|
||||||
|
// Récursion : les listes imbriquées sont d'abord compactées, puis tout le bloc recule de deux colonnes.
|
||||||
|
const inner = compactListItems(block.join('\n')).split('\n').map((blockLine) => (blockLine === '' ? '' : blockLine.slice(2)));
|
||||||
|
const [first, ...rest] = inner;
|
||||||
|
output.push(`${' '.repeat(base)}- ${first.trimStart()}`, ...rest);
|
||||||
|
}
|
||||||
|
return output.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Sérialise un niveau en YAML conforme aux conventions du projet (4 espaces, pas de repli de ligne). */
|
||||||
|
export function levelToYaml(level) {
|
||||||
|
return compactListItems(yaml.dump(level, { indent: 4, lineWidth: -1, noRefs: true, noCompatMode: true, quotingType: '"' }));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function levelFromYaml(source) {
|
||||||
|
return yaml.load(source);
|
||||||
|
}
|
||||||
Binary file not shown.
@@ -45,7 +45,7 @@ def code_snippets(level: dict[str, Any]) -> list[tuple[str, str]]:
|
|||||||
return snippets
|
return snippets
|
||||||
|
|
||||||
|
|
||||||
def validate_level(path: Path, schema: dict[str, Any], require_en: bool) -> list[str]:
|
def validate_level(path: Path, schema: dict[str, Any], require_en: bool, check_folder: bool = True) -> list[str]:
|
||||||
errors: list[str] = []
|
errors: list[str] = []
|
||||||
try:
|
try:
|
||||||
level = yaml.safe_load(path.read_text(encoding="utf-8"))
|
level = yaml.safe_load(path.read_text(encoding="utf-8"))
|
||||||
@@ -59,7 +59,7 @@ def validate_level(path: Path, schema: dict[str, Any], require_en: bool) -> list
|
|||||||
if errors:
|
if errors:
|
||||||
return errors
|
return errors
|
||||||
|
|
||||||
if level["id"] != path.parent.name:
|
if check_folder and level["id"] != path.parent.name:
|
||||||
errors.append(f"id '{level['id']}' différent du dossier '{path.parent.name}'")
|
errors.append(f"id '{level['id']}' différent du dossier '{path.parent.name}'")
|
||||||
if require_en:
|
if require_en:
|
||||||
errors.extend(f"traduction `en` manquante : {where}" for where in missing_english(level))
|
errors.extend(f"traduction `en` manquante : {where}" for where in missing_english(level))
|
||||||
@@ -90,11 +90,19 @@ def validate_manifest(known_ids: set[str]) -> list[str]:
|
|||||||
def main() -> int:
|
def main() -> int:
|
||||||
parser = argparse.ArgumentParser(description=__doc__)
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
parser.add_argument("--allow-missing-en", action="store_true", help="n'exige pas les traductions en")
|
parser.add_argument("--allow-missing-en", action="store_true", help="n'exige pas les traductions en")
|
||||||
|
parser.add_argument("--file", type=Path, help="valide un seul fichier level.yaml (ex. exporté par l'éditeur), hors manifeste")
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
|
schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
|
||||||
jsonschema.Draft202012Validator.check_schema(schema)
|
jsonschema.Draft202012Validator.check_schema(schema)
|
||||||
|
|
||||||
|
if args.file is not None:
|
||||||
|
errors = validate_level(args.file, schema, require_en=not args.allow_missing_en, check_folder=False)
|
||||||
|
print(f"{'OK ' if not errors else 'KO '} {args.file}")
|
||||||
|
for message in errors:
|
||||||
|
print(f" - {message}")
|
||||||
|
return 1 if errors else 0
|
||||||
|
|
||||||
files = sorted(LEVELS_DIR.glob("*/level.yaml"))
|
files = sorted(LEVELS_DIR.glob("*/level.yaml"))
|
||||||
failed = False
|
failed = False
|
||||||
for path in files:
|
for path in files:
|
||||||
|
|||||||
@@ -0,0 +1,81 @@
|
|||||||
|
// Modèle de l'éditeur : aller-retour exact sur tous les niveaux, nettoyage des champs vides, YAML valide
|
||||||
|
// (rechargeable, conforme au schéma, et accepté par scripts/validate_levels.py).
|
||||||
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import { mkdtempSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import assert from 'node:assert';
|
||||||
|
import yaml from '../../app/js/lib/js-yaml/js-yaml.mjs';
|
||||||
|
import { LevelLinter } from '../../app/js/core/LevelLinter.js';
|
||||||
|
import { emptyLevelModel, fromLevel, levelFromYaml, levelToYaml, newStepModel, newTestModel, toLevel } from '../../app/js/author/LevelDraft.js';
|
||||||
|
|
||||||
|
const root = new URL('../../', import.meta.url).pathname;
|
||||||
|
const ids = readdirSync(`${root}levels`).filter((name) => /^\d\d-/.test(name));
|
||||||
|
const load = (id) => yaml.load(readFileSync(`${root}levels/${id}/level.yaml`, 'utf8'));
|
||||||
|
const linter = new LevelLinter(JSON.parse(readFileSync(`${root}levels/schema/level.schema.json`, 'utf8')));
|
||||||
|
const tmp = mkdtempSync(join(tmpdir(), 'pyquest-draft-'));
|
||||||
|
|
||||||
|
// --- Aller-retour exact sur tous les niveaux, et YAML exporté rechargeable à l'identique.
|
||||||
|
for (const id of ids) {
|
||||||
|
const level = load(id);
|
||||||
|
assert.deepEqual(toLevel(fromLevel(level)), level, `${id} : aller-retour modèle`);
|
||||||
|
const source = levelToYaml(toLevel(fromLevel(level)));
|
||||||
|
assert.deepEqual(levelFromYaml(source), level, `${id} : aller-retour YAML`);
|
||||||
|
assert.ok(!/\t/.test(source), `${id} : pas de tabulation`);
|
||||||
|
const file = join(tmp, `${id}.yaml`);
|
||||||
|
writeFileSync(file, source);
|
||||||
|
// Le validateur Python de la CI accepte exactement ce que l'éditeur exporte.
|
||||||
|
const output = execFileSync('python3', ['-I', '-c', `
|
||||||
|
import sys, json
|
||||||
|
sys.path.insert(0, ${JSON.stringify(`${root}scripts`)})
|
||||||
|
import validate_levels as v
|
||||||
|
schema = json.load(open(${JSON.stringify(`${root}levels/schema/level.schema.json`)}))
|
||||||
|
print(v.validate_level(__import__('pathlib').Path(${JSON.stringify(file)}), schema, True, check_folder=False))`], { encoding: 'utf8' });
|
||||||
|
assert.equal(output.trim(), '[]', `${id} : validate_levels.py`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Un niveau vide, une fois rempli à minima, est conforme (sauf traductions et solutions à compléter).
|
||||||
|
const model = emptyLevelModel();
|
||||||
|
model.id = '99-essai';
|
||||||
|
model.title = { fr: 'Essai', en: 'Test' };
|
||||||
|
model.steps = [newStepModel('explain'), newStepModel('code')];
|
||||||
|
model.steps[0].text = { fr: 'Texte', en: 'Text' };
|
||||||
|
model.steps[1].instruction = { fr: 'Fais ceci', en: 'Do this' };
|
||||||
|
model.steps[1].solution = 'print("x")';
|
||||||
|
model.steps[1].tests = [{ ...newTestModel('stdout_equals'), value: 'x\n' }];
|
||||||
|
model.steps[1].hints = { fr: 'Un indice\n\n Deux \n', en: 'A hint\nTwo' };
|
||||||
|
model.mission.title = { fr: 'M', en: 'M' };
|
||||||
|
model.mission.goal = { fr: 'But', en: 'Goal' };
|
||||||
|
const level = toLevel(model);
|
||||||
|
assert.deepEqual(linter.lint(level, { knownLevelIds: ids }).filter((p) => p.severity === 'error'), []);
|
||||||
|
|
||||||
|
// --- Nettoyage : champs facultatifs vides omis, ordre des clés stable.
|
||||||
|
assert.deepEqual(Object.keys(level), ['id', 'title', 'difficulty', 'xp', 'requires', 'steps', 'mission']);
|
||||||
|
assert.deepEqual(Object.keys(level.steps[0]), ['type', 'voice', 'text']);
|
||||||
|
assert.deepEqual(Object.keys(level.steps[1]), ['type', 'starter', 'instruction', 'tests', 'hints', 'solution']);
|
||||||
|
assert.deepEqual(level.steps[1].hints, { fr: ['Un indice', 'Deux'], en: ['A hint', 'Two'] }, 'lignes vides retirées, espaces rognés');
|
||||||
|
assert.deepEqual(Object.keys(level.mission), ['title', 'goal', 'reward_sound']);
|
||||||
|
model.steps[1].hints = { fr: '', en: '' };
|
||||||
|
assert.equal('hints' in toLevel(model).steps[1], false);
|
||||||
|
model.steps[0].voice = false; model.steps[0].image = ' img.png ';
|
||||||
|
assert.deepEqual(toLevel(model).steps[0], { type: 'explain', text: { fr: 'Texte', en: 'Text' }, image: 'img.png' });
|
||||||
|
model.steps[0].text.en = '';
|
||||||
|
assert.deepEqual(toLevel(model).steps[0].text, { fr: 'Texte' }, 'en vide omis (signalé ensuite par le linter)');
|
||||||
|
|
||||||
|
// --- Tests typés et saisies scriptées.
|
||||||
|
const typed = (valueType, value) => toLevel({ ...model, steps: [{ ...model.steps[1], tests: [{ ...newTestModel('var_equals'), name: 'x', valueType, value }] }] }).steps[0].tests[0].value;
|
||||||
|
assert.equal(typed('number', '2.5'), 2.5);
|
||||||
|
assert.equal(typed('number', 'abc'), 'abc', 'nombre invalide conservé tel quel (le linter/validation le signalera)');
|
||||||
|
assert.equal(typed('boolean', 'true'), true);
|
||||||
|
assert.equal(typed('text', '12'), '12');
|
||||||
|
const withInputs = toLevel({ ...model, steps: [{ ...model.steps[1], tests: [{ ...newTestModel('stdout_contains'), value: 'a', inputs: 'x\n\ny\n\n' }] }] }).steps[0].tests[0];
|
||||||
|
assert.deepEqual(withInputs.inputs, ['x', '', 'y'], 'ligne vide du milieu conservée, finales ignorées');
|
||||||
|
assert.deepEqual(Object.keys(toLevel({ ...model, steps: [{ ...model.steps[1], tests: [newTestModel('no_syntax_error')] }] }).steps[0].tests[0]), ['kind']);
|
||||||
|
|
||||||
|
// --- Le compactage des listes ne touche jamais au contenu des blocs littéraux (code avec une ligne « - »).
|
||||||
|
model.steps[1].starter = 'x = 1\n-\n- item\n -\n';
|
||||||
|
model.steps[1].solution = '-\nprint("ok")';
|
||||||
|
const exported = toLevel(model);
|
||||||
|
assert.deepEqual(levelFromYaml(levelToYaml(exported)), exported, 'blocs littéraux préservés');
|
||||||
|
|
||||||
|
console.log('level draft ok');
|
||||||
Reference in New Issue
Block a user