Add drawing canvas (canvas module, DrawingView, drawing_* tests) and levels 13-14 (classes, saved patterns)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
denis
2026-10-16 17:40:53 +02:00
parent 4689d25700
commit d3b7c611f1
46 changed files with 1250 additions and 22 deletions
+3
View File
@@ -17,6 +17,9 @@ export const TEST_KINDS = {
code_contains: { name: false, value: 'text' },
var_equals: { name: true, value: 'typed' },
var_type_is: { name: true, value: 'type' },
drawing_segments: { name: false, value: 'text' },
drawing_has_line: { name: false, value: 'text' },
drawing_colors: { name: false, value: 'text' },
};
const i18n = (fr = '', en = '') => ({ fr, en });
+7
View File
@@ -77,8 +77,15 @@ export class LevelChecker {
return { exercises: summary, problems };
}
/** Chaque essai part d'un état vierge : ni variables ni fichiers de data/ laissés par l'essai précédent. */
async #freshStart() {
await this.#client.run("import os as _os\nfor _name in _os.listdir('data'):\n _os.remove(_os.path.join('data', _name))");
await this.#client.reset();
}
/** Exécute `code` comme l'apprenant (saisies du premier test scripté), puis valide ses tests. */
async #attempt(code, tests) {
await this.#freshStart();
const queue = [...(tests.find((test) => test.inputs)?.inputs ?? [])];
let stdout = '';
const result = await this.#client.run(code, {
+4
View File
@@ -4,6 +4,7 @@
// les textes affichés viennent des catalogues (clé `lint.<code>`), jamais d'ici.
import { Validator } from '../lib/json-schema/index.js';
import { checkDrawing } from './drawingTests.js';
import { ValidationEngine } from './ValidationEngine.js';
const DRAFT = '2020-12';
@@ -227,6 +228,9 @@ export class LevelLinter {
if (test.kind === 'var_type_is' && !PYTHON_TYPES.includes(test.value)) {
add('warning', 'type_unusual', [...here, 'value'], { allowed: PYTHON_TYPES.join(', ') });
}
if (test.kind.startsWith('drawing_') && typeof test.value === 'string' && test.value !== '' && checkDrawing(test, []) === 'invalid_test') {
add('error', 'drawing_value_invalid', [...here, 'value']);
}
if (test.kind === 'stdout_matches_regex' && typeof test.value === 'string') {
try {
new RegExp(test.value);
+8 -2
View File
@@ -1,12 +1,14 @@
// Interprète les tests déclaratifs d'un niveau (enum fermé `tests[].kind`).
// Agnostique du contenu : aucun code venant d'un fichier de niveau n'est exécuté ici.
import { checkDrawing } from './drawingTests.js';
const FLOAT_TOLERANCE = 1e-9;
export class ValidationEngine {
/** Kinds de test interprétés par le moteur (le schéma en autorise davantage : certains sont encore à définir). */
static get supportedKinds() {
return ['no_syntax_error', 'stdout_equals', 'stdout_contains', 'stdout_matches_regex', 'code_contains', 'var_equals', 'var_type_is'];
return ['no_syntax_error', 'stdout_equals', 'stdout_contains', 'stdout_matches_regex', 'code_contains', 'var_equals', 'var_type_is', 'drawing_segments', 'drawing_has_line', 'drawing_colors'];
}
/** Noms de variables à relire côté Python (option `collect` de run_code) pour ces tests. */
@@ -20,7 +22,7 @@ export class ValidationEngine {
* @param {object} execution
* @param {string} execution.stdout Sortie standard cumulée de la cellule.
* @param {string} [execution.code] Code exécuté (pour `code_contains`).
* @param {{ok: boolean, error: object|null, variables: object}} execution.result
* @param {{ok: boolean, error: object|null, variables: object, drawing?: Array}} execution.result
* @returns {{passed: boolean, results: {kind: string, passed: boolean, reason: string|null, message: string|null}[]}}
*/
validate(tests, { stdout, result, code = '' }) {
@@ -50,6 +52,10 @@ export class ValidationEngine {
return this.#varEquals(test, result.variables);
case 'var_type_is':
return this.#varTypeIs(test, result.variables);
case 'drawing_segments':
case 'drawing_has_line':
case 'drawing_colors':
return checkDrawing(test, result.drawing);
default:
// Kind connu du schéma mais pas encore interprété (ou inconnu).
return 'unsupported_kind';
+77
View File
@@ -0,0 +1,77 @@
// Tests déclaratifs sur le dessin produit par `canvas.line` (kinds `drawing_*`).
// Les valeurs sont de simples chaînes pour rester éditables dans l'éditeur de niveaux :
// drawing_segments : "4" (exactement 4 traits) ou "4+" (au moins 4)
// drawing_has_line : "0,0 100,0" ou "0,0 100,0 red" (un trait entre ces deux points, dans un sens ou
// dans l'autre, éventuellement de cette couleur)
// drawing_colors : "red,blue" (toutes ces couleurs apparaissent dans le dessin)
// Un segment est [x1, y1, x2, y2, couleur] (coordonnées déjà arrondies à 0,01 par le module Python).
export const DRAWING_COLORS = ['black', 'red', 'green', 'blue', 'orange', 'purple', 'gray'];
const POINT_TOLERANCE = 0.5;
const NUMBER = '-?\\d+(?:\\.\\d+)?';
const SEGMENTS_PATTERN = /^(\d+)(\+?)$/;
const LINE_PATTERN = new RegExp(`^\\s*(${NUMBER}),(${NUMBER})\\s+(${NUMBER}),(${NUMBER})(?:\\s+([a-z]+))?\\s*$`);
/** @returns {{count: number, atLeast: boolean}|null} null si la valeur est mal formée. */
export function parseSegmentsSpec(value) {
const match = SEGMENTS_PATTERN.exec(String(value ?? '').trim());
return match ? { count: Number(match[1]), atLeast: match[2] === '+' } : null;
}
/** @returns {{from: number[], to: number[], color: string|null}|null} */
export function parseLineSpec(value) {
const match = LINE_PATTERN.exec(String(value ?? ''));
if (!match) {
return null;
}
const [, x1, y1, x2, y2, color] = match;
if (color !== undefined && !DRAWING_COLORS.includes(color)) {
return null;
}
return { from: [Number(x1), Number(y1)], to: [Number(x2), Number(y2)], color: color ?? null };
}
/** @returns {string[]|null} */
export function parseColorsSpec(value) {
const colors = String(value ?? '')
.split(',')
.map((color) => color.trim())
.filter(Boolean);
return colors.length > 0 && colors.every((color) => DRAWING_COLORS.includes(color)) ? colors : null;
}
const near = (a, b) => Math.abs(a[0] - b[0]) <= POINT_TOLERANCE && Math.abs(a[1] - b[1]) <= POINT_TOLERANCE;
/** Renvoie null si le test passe, sinon un code de raison traduit par l'interface. */
export function checkDrawing(test, drawing) {
if (!Array.isArray(drawing)) {
return 'drawing_missing';
}
if (test.kind === 'drawing_segments') {
const spec = parseSegmentsSpec(test.value);
if (!spec) {
return 'invalid_test';
}
const ok = spec.atLeast ? drawing.length >= spec.count : drawing.length === spec.count;
return ok ? null : spec.atLeast || drawing.length < spec.count ? 'drawing_too_few' : 'drawing_too_many';
}
if (test.kind === 'drawing_has_line') {
const spec = parseLineSpec(test.value);
if (!spec) {
return 'invalid_test';
}
const found = drawing.some(([x1, y1, x2, y2, color]) => {
const same = near([x1, y1], spec.from) && near([x2, y2], spec.to);
const reversed = near([x1, y1], spec.to) && near([x2, y2], spec.from);
return (same || reversed) && (spec.color === null || spec.color === color);
});
return found ? null : 'drawing_line_missing';
}
const colors = parseColorsSpec(test.value);
if (!colors) {
return 'invalid_test';
}
const used = new Set(drawing.map((segment) => segment[4]));
return colors.every((color) => used.has(color)) ? null : 'drawing_color_missing';
}
+8 -1
View File
@@ -143,5 +143,12 @@
"lint.solution_error": "The solution crashes: {type} — {message}{line}",
"lint.solution_fails": "The solution does not pass its tests: {failures}.",
"lint.starter_passes": "The starter code already passes the tests: the exercise would already be solved.",
"lint.starter_error": "The starter code does not run: {type} — {message}{line}"
"lint.starter_error": "The starter code does not run: {type} — {message}{line}",
"author.kind.drawing_segments": "Drawing: number of lines",
"author.kind.drawing_segments.help": "Number of lines drawn by canvas.line: “4” (exactly) or “4+” (at least).",
"author.kind.drawing_has_line": "Drawing: a specific line",
"author.kind.drawing_has_line.help": "A line between two points, either direction: “0,0 100,0” or with a colour “0,0 100,0 red”. Tolerance 0.5.",
"author.kind.drawing_colors": "Drawing: colours used",
"author.kind.drawing_colors.help": "Colours that must all appear, comma-separated: “red,blue”.",
"lint.drawing_value_invalid": "Malformed drawing test value (see the test type help; colours: black, red, green, blue, orange, purple, gray)."
}
+8 -1
View File
@@ -143,5 +143,12 @@
"lint.solution_error": "La solution plante : {type} — {message}{line}",
"lint.solution_fails": "La solution ne passe pas ses tests : {failures}.",
"lint.starter_passes": "Le code de départ passe déjà les tests : l'exercice serait déjà résolu.",
"lint.starter_error": "Le code de départ ne s'exécute pas : {type} — {message}{line}"
"lint.starter_error": "Le code de départ ne s'exécute pas : {type} — {message}{line}",
"author.kind.drawing_segments": "Dessin : nombre de traits",
"author.kind.drawing_segments.help": "Nombre de traits tracés par canvas.line : « 4 » (exactement) ou « 4+ » (au moins).",
"author.kind.drawing_has_line": "Dessin : un trait précis",
"author.kind.drawing_has_line.help": "Un trait entre deux points, dans un sens ou dans l'autre : « 0,0 100,0 » ou avec couleur « 0,0 100,0 red ». Tolérance 0,5.",
"author.kind.drawing_colors": "Dessin : couleurs utilisées",
"author.kind.drawing_colors.help": "Couleurs qui doivent toutes apparaître, séparées par des virgules : « red,blue ».",
"lint.drawing_value_invalid": "Valeur de test de dessin mal formée (voir l'aide du type de test ; couleurs : black, red, green, blue, orange, purple, gray)."
}
+20 -1
View File
@@ -119,5 +119,24 @@
"sync.error.unauthorized": "The server refuses this token.",
"sync.error.unavailable": "No sync server available here. Your local progress is safe.",
"sync.error.rejected": "The server rejected the data sent.",
"sync.error.invalid": "The data received from the server is invalid and was ignored."
"sync.error.invalid": "The data received from the server is invalid and was ignored.",
"reason.drawing_missing": "No drawing was produced: use canvas.line.",
"reason.drawing_too_few": "The drawing is missing some lines.",
"reason.drawing_too_many": "The drawing has too many lines.",
"reason.drawing_line_missing": "An expected line is not in the drawing (position or colour).",
"reason.drawing_color_missing": "An expected colour is not used in the drawing.",
"reason.invalid_test": "This test is badly defined (let the level authors know).",
"drawing.title": "Drawing",
"drawing.alt.empty": "Empty sheet: no line drawn.",
"drawing.alt": "Drawing of {n} line(s). Colours: {colors}.",
"drawing.list": "See the list of lines",
"drawing.segment": "From ({x1}, {y1}) to ({x2}, {y2}), {color}",
"drawing.more": "… and {n} more line(s).",
"drawing.color.black": "black",
"drawing.color.red": "red",
"drawing.color.green": "green",
"drawing.color.blue": "blue",
"drawing.color.orange": "orange",
"drawing.color.purple": "purple",
"drawing.color.gray": "gray"
}
+20 -1
View File
@@ -119,5 +119,24 @@
"sync.error.unauthorized": "Le serveur refuse ce jeton.",
"sync.error.unavailable": "Pas de serveur de synchronisation disponible ici. Ta progression locale est intacte.",
"sync.error.rejected": "Le serveur a refusé les données envoyées.",
"sync.error.invalid": "Les données reçues du serveur sont invalides et ont été ignorées."
"sync.error.invalid": "Les données reçues du serveur sont invalides et ont été ignorées.",
"reason.drawing_missing": "Aucun dessin n'a été produit : utilise canvas.line.",
"reason.drawing_too_few": "Il manque des traits dans le dessin.",
"reason.drawing_too_many": "Il y a trop de traits dans le dessin.",
"reason.drawing_line_missing": "Un trait attendu n'est pas dans le dessin (position ou couleur).",
"reason.drawing_color_missing": "Une couleur attendue n'est pas utilisée dans le dessin.",
"reason.invalid_test": "Ce test est mal défini (signale-le aux auteurs du niveau).",
"drawing.title": "Dessin",
"drawing.alt.empty": "Feuille vide : aucun trait tracé.",
"drawing.alt": "Dessin de {n} trait(s). Couleurs : {colors}.",
"drawing.list": "Voir la liste des traits",
"drawing.segment": "De ({x1}, {y1}) à ({x2}, {y2}), {color}",
"drawing.more": "… et {n} autre(s) trait(s).",
"drawing.color.black": "noir",
"drawing.color.red": "rouge",
"drawing.color.green": "vert",
"drawing.color.blue": "bleu",
"drawing.color.orange": "orange",
"drawing.color.purple": "violet",
"drawing.color.gray": "gris"
}
+2
View File
@@ -162,6 +162,8 @@ export class CellManager extends EventTarget {
},
});
// Même interrompu ou en erreur, le début du dessin aide à comprendre ce qui s'est passé.
cell.showDrawing(result.drawing);
if (result.error) {
cell.setBusy(false);
cell.showError(translator.translate(result.error, i18n.lang));
+10
View File
@@ -3,6 +3,7 @@
import { el, renderInline, uniqueId } from './dom.js';
import { CodeEditor } from './CodeEditor.js';
import { DrawingView } from './DrawingView.js';
import { GuideBubble } from './GuideBubble.js';
import { HintPanel } from './HintPanel.js';
@@ -12,6 +13,7 @@ export class CellView extends EventTarget {
#root;
#editor;
#output;
#drawing;
#feedback;
#guideSlot;
#hintPanel;
@@ -59,6 +61,7 @@ export class CellView extends EventTarget {
const resetButton = el('button', { type: 'button', class: 'btn', text: i18n.t('cell.reset'), onclick: () => this.reset() });
this.#output = el('pre', { id: outputId, class: 'cell-output', 'aria-live': 'polite', 'aria-label': i18n.t('cell.output') });
this.#drawing = new DrawingView(i18n);
this.#feedback = el('div', { class: 'cell-feedback', role: 'status' });
this.#guideSlot = el('div', { class: 'cell-guide' });
this.#hintPanel = new HintPanel(i18n, hints, { onReveal: () => this.dispatchEvent(new CustomEvent('hint')) });
@@ -86,6 +89,7 @@ export class CellView extends EventTarget {
el('p', { id: `${editorId}-hint`, class: 'cell-shortcut', text: i18n.t('cell.shortcut') }),
el('div', { class: 'cell-actions' }, this.#runButton, this.#stopButton, resetButton, this.#hintPanel.element),
this.#output,
this.#drawing.element,
this.#inputForm,
this.#feedback,
this.#guideSlot,
@@ -115,6 +119,7 @@ export class CellView extends EventTarget {
clearOutput() {
this.#output.textContent = '';
this.#drawing.clear();
this.#feedback.replaceChildren();
this.#guideSlot.replaceChildren();
}
@@ -129,6 +134,11 @@ export class CellView extends EventTarget {
this.#guideSlot.replaceChildren(new GuideBubble(message).element);
}
/** Affiche le dessin produit par `canvas.line` (rien si aucun trait). */
showDrawing(segments) {
this.#drawing.render(segments ?? []);
}
appendOutput(text) {
this.#output.append(document.createTextNode(text));
}
+104
View File
@@ -0,0 +1,104 @@
// Feuille de dessin d'une cellule : affiche les traits produits par `canvas.line`.
// Le <canvas> est une image (role="img") dotée d'une description textuelle, et la liste des traits est
// disponible en texte : rien n'est transmis par la seule couleur ni par la seule image.
import { el } from './dom.js';
export const SIZE = 400; // repère logique : -200..200 dans les deux sens, origine au centre, y vers le haut
const HALF = SIZE / 2;
const LISTED_SEGMENTS = 50;
// Teintes choisies pour rester lisibles sur la feuille blanche (la feuille ne suit pas le thème sombre).
const COLORS = { black: '#111111', red: '#c62828', green: '#2e7d32', blue: '#1565c0', orange: '#e65100', purple: '#6a1b9a', gray: '#616161' };
const fmt = (n) => String(Math.round(n * 100) / 100);
/** Description textuelle du dessin (pure, testable sans navigateur). */
export function describeDrawing(segments, t) {
if (segments.length === 0) {
return t('drawing.alt.empty');
}
const used = [...new Set(segments.map((segment) => segment[4]))].map((color) => t(`drawing.color.${color}`));
return t('drawing.alt', { n: segments.length, colors: used.join(', ') });
}
/** Une ligne de texte par trait. */
export function describeSegment([x1, y1, x2, y2, color], t) {
return t('drawing.segment', { x1: fmt(x1), y1: fmt(y1), x2: fmt(x2), y2: fmt(y2), color: t(`drawing.color.${color}`) });
}
export class DrawingView {
#i18n;
#root;
#canvas;
#list;
#summary;
/** @param {import('../i18n/i18n.js').I18n} i18n */
constructor(i18n) {
this.#i18n = i18n;
this.#canvas = el('canvas', { class: 'drawing-canvas', width: SIZE, height: SIZE, role: 'img' });
this.#summary = el('p', { class: 'drawing-summary' });
this.#list = el('ul', { class: 'drawing-list' });
this.#root = el(
'figure',
{ class: 'cell-drawing', hidden: true },
el('figcaption', { text: i18n.t('drawing.title') }),
this.#canvas,
this.#summary,
el('details', {}, el('summary', { text: i18n.t('drawing.list') }), this.#list),
);
}
get element() {
return this.#root;
}
/** @param {Array<[number, number, number, number, string]>} segments */
render(segments) {
this.#root.hidden = segments.length === 0;
const t = (key, params) => this.#i18n.t(key, params);
const description = describeDrawing(segments, t);
this.#canvas.setAttribute('aria-label', description);
this.#summary.textContent = description;
const shown = segments.slice(0, LISTED_SEGMENTS).map((segment) => el('li', { text: describeSegment(segment, t) }));
if (segments.length > LISTED_SEGMENTS) {
shown.push(el('li', { text: t('drawing.more', { n: segments.length - LISTED_SEGMENTS }) }));
}
this.#list.replaceChildren(...shown);
this.#paint(segments);
}
clear() {
this.render([]);
}
#paint(segments) {
const context = this.#canvas.getContext('2d');
if (!context) {
return; // la description textuelle reste disponible
}
context.clearRect(0, 0, SIZE, SIZE);
context.fillStyle = '#ffffff';
context.fillRect(0, 0, SIZE, SIZE);
// Repère discret : quadrillage tous les 50 et axes.
context.lineWidth = 1;
for (let v = -HALF; v <= HALF; v += 50) {
context.strokeStyle = v === 0 ? '#9e9e9e' : '#e0e0e0';
context.beginPath();
context.moveTo(HALF + v, 0);
context.lineTo(HALF + v, SIZE);
context.moveTo(0, HALF - v);
context.lineTo(SIZE, HALF - v);
context.stroke();
}
context.lineWidth = 3;
context.lineCap = 'round';
for (const [x1, y1, x2, y2, color] of segments) {
context.strokeStyle = COLORS[color] ?? COLORS.black;
context.beginPath();
context.moveTo(HALF + x1, HALF - y1);
context.lineTo(HALF + x2, HALF - y2);
context.stroke();
}
}
}