mirror of
https://github.com/deunix-educ/PyQuest.git
synced 2026-11-25 08:19:44 +01:00
Add guide character (owl) with varied bilingual messages, moods and setting
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,112 @@
|
||||
/* Personnage-guide : chouette (aux couleurs du thème) et sa bulle. Masqué par le réglage « guide ». */
|
||||
|
||||
.guide-bubble {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 0.75rem;
|
||||
margin: 0.75rem 0;
|
||||
animation: guide-pop 0.3s ease-out;
|
||||
}
|
||||
|
||||
.guide-avatar {
|
||||
flex: 0 0 3.5rem;
|
||||
width: 3.5rem;
|
||||
height: 3.5rem;
|
||||
}
|
||||
|
||||
.guide-avatar svg {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.guide-text {
|
||||
position: relative;
|
||||
margin: 0.25rem 0 0;
|
||||
padding: 0.6rem 0.9rem;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
border: 2px solid var(--accent);
|
||||
border-radius: 0.75rem;
|
||||
}
|
||||
|
||||
/* Pointe de la bulle, vers l'avatar. */
|
||||
.guide-text::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: -0.55rem;
|
||||
top: 0.9rem;
|
||||
width: 0.8rem;
|
||||
height: 0.8rem;
|
||||
background: var(--bg);
|
||||
border-left: 2px solid var(--accent);
|
||||
border-bottom: 2px solid var(--accent);
|
||||
transform: rotate(45deg);
|
||||
}
|
||||
|
||||
:root[data-guide="off"] .guide-bubble {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@keyframes guide-pop {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(0.4rem) scale(0.97);
|
||||
}
|
||||
}
|
||||
|
||||
/* Dessin : couleurs via les jetons du thème. */
|
||||
.owl-body {
|
||||
fill: var(--accent);
|
||||
}
|
||||
|
||||
.owl-belly {
|
||||
fill: var(--surface);
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
.owl-eye {
|
||||
fill: var(--bg);
|
||||
}
|
||||
|
||||
.owl-pupil {
|
||||
fill: var(--text);
|
||||
}
|
||||
|
||||
.owl-glint {
|
||||
fill: var(--bg);
|
||||
}
|
||||
|
||||
.owl-beak,
|
||||
.owl-spark {
|
||||
fill: var(--hl);
|
||||
}
|
||||
|
||||
.owl-line {
|
||||
fill: none;
|
||||
stroke: var(--text);
|
||||
stroke-width: 4;
|
||||
stroke-linecap: round;
|
||||
}
|
||||
|
||||
/* Humeurs : par défaut (neutral) yeux ronds ; les autres groupes sont masqués. */
|
||||
.owl-wings,
|
||||
.owl-sparkles,
|
||||
.eyes-happy,
|
||||
.eyes-thinking {
|
||||
display: none;
|
||||
}
|
||||
|
||||
[data-mood="happy"] .eyes-round,
|
||||
[data-mood="celebrate"] .eyes-round,
|
||||
[data-mood="thinking"] .eyes-round {
|
||||
display: none;
|
||||
}
|
||||
|
||||
[data-mood="happy"] .eyes-happy,
|
||||
[data-mood="celebrate"] .eyes-happy,
|
||||
[data-mood="thinking"] .eyes-thinking,
|
||||
[data-mood="celebrate"] .owl-wings,
|
||||
[data-mood="celebrate"] .owl-sparkles {
|
||||
display: inline;
|
||||
}
|
||||
@@ -11,6 +11,7 @@
|
||||
<link rel="stylesheet" href="css/themes.css">
|
||||
<link rel="stylesheet" href="css/base.css">
|
||||
<link rel="stylesheet" href="css/cells.css">
|
||||
<link rel="stylesheet" href="css/guide.css">
|
||||
</head>
|
||||
<body>
|
||||
<a class="skip-link" href="#main">Aller au contenu / Skip to content</a>
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
// Personnage-guide : choisit un message adapté à la situation, jamais le même deux fois de suite.
|
||||
// Les messages viennent de app/js/i18n/guide.<lang>.json ; ici seulement la logique de variété.
|
||||
|
||||
// Humeur du dessin (voir ui/guideArt.js) pour chaque situation.
|
||||
const MOODS = {
|
||||
level_start: 'happy',
|
||||
welcome_back: 'happy',
|
||||
success_step: 'happy',
|
||||
success_first_try: 'celebrate',
|
||||
success_after_retry: 'celebrate',
|
||||
error_runtime: 'thinking',
|
||||
fail_tests: 'thinking',
|
||||
suggest_hint: 'thinking',
|
||||
hint_revealed: 'thinking',
|
||||
interrupted: 'neutral',
|
||||
input_waiting: 'neutral',
|
||||
level_complete: 'celebrate',
|
||||
level_complete_replay: 'happy',
|
||||
streak: 'celebrate',
|
||||
};
|
||||
|
||||
export class GuideEngine {
|
||||
#catalogs;
|
||||
#defaultLang;
|
||||
#random;
|
||||
#bags = new Map(); // `${lang}/${situation}` -> indices restants (tirage sans remise)
|
||||
#last = new Map(); // `${lang}/${situation}` -> dernier indice dit
|
||||
|
||||
/**
|
||||
* @param {Record<string, Record<string, string[]>>} catalogs Contenu de guide.fr.json, guide.en.json.
|
||||
* @param {object} [options]
|
||||
* @param {string} [options.defaultLang]
|
||||
* @param {() => number} [options.random] Remplaçable pour des tests déterministes.
|
||||
*/
|
||||
constructor(catalogs, { defaultLang = 'fr', random = Math.random } = {}) {
|
||||
this.#catalogs = catalogs;
|
||||
this.#defaultLang = defaultLang;
|
||||
this.#random = random;
|
||||
}
|
||||
|
||||
static get situations() {
|
||||
return Object.keys(MOODS);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} situation Clé de MOODS (ex. 'success_step').
|
||||
* @param {string} lang
|
||||
* @param {Record<string, string|number>} [params] Valeurs des {paramètres} du message.
|
||||
* @returns {{situation: string, mood: string, text: string}}
|
||||
*/
|
||||
say(situation, lang, params = {}) {
|
||||
const catalog = this.#catalogs[lang]?.[situation] ? this.#catalogs[lang] : this.#catalogs[this.#defaultLang];
|
||||
const variants = catalog[situation];
|
||||
if (!variants || !(situation in MOODS)) {
|
||||
throw new Error(`Unknown guide situation: ${situation}`);
|
||||
}
|
||||
const text = variants[this.#nextIndex(`${lang}/${situation}`, variants.length)].replace(/\{(\w+)\}/g, (whole, name) => String(params[name] ?? whole));
|
||||
return { situation, mood: MOODS[situation], text };
|
||||
}
|
||||
|
||||
/** Tirage sans remise : toutes les variantes passent avant qu'une se répète, jamais deux fois de suite. */
|
||||
#nextIndex(key, size) {
|
||||
if (size === 1) {
|
||||
return 0;
|
||||
}
|
||||
let bag = this.#bags.get(key) ?? [];
|
||||
if (bag.length === 0) {
|
||||
bag = this.#shuffled(size);
|
||||
// Le premier tirage du nouveau sac ne doit pas répéter le dernier message dit.
|
||||
if (bag[0] === this.#last.get(key)) {
|
||||
bag.push(bag.shift());
|
||||
}
|
||||
}
|
||||
const index = bag.shift();
|
||||
this.#bags.set(key, bag);
|
||||
this.#last.set(key, index);
|
||||
return index;
|
||||
}
|
||||
|
||||
#shuffled(size) {
|
||||
const indices = Array.from({ length: size }, (_, i) => i);
|
||||
for (let i = indices.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(this.#random() * (i + 1));
|
||||
[indices[i], indices[j]] = [indices[j], indices[i]];
|
||||
}
|
||||
return indices;
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ export const DEFAULT_SETTINGS = Object.freeze({
|
||||
volume: 0.8,
|
||||
voiceEnabled: true, // le bouton « Écouter » ne lit jamais automatiquement : un clic à chaque fois
|
||||
voiceRate: 1,
|
||||
guideEnabled: true, // personnage-guide (bulles d'encouragement)
|
||||
});
|
||||
|
||||
export class SettingsStore extends EventTarget {
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"settings.theme.auto": "Automatic",
|
||||
"settings.theme.light": "Light",
|
||||
"settings.theme.dark": "Dark",
|
||||
"settings.guide": "Guide character",
|
||||
"settings.sound": "Sound effects",
|
||||
"settings.volume": "Volume",
|
||||
"settings.voice": "Voice",
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
"settings.theme.auto": "Automatique",
|
||||
"settings.theme.light": "Clair",
|
||||
"settings.theme.dark": "Sombre",
|
||||
"settings.guide": "Personnage-guide",
|
||||
"settings.sound": "Effets sonores",
|
||||
"settings.volume": "Volume",
|
||||
"settings.voice": "Voix",
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
{
|
||||
"level_start": [
|
||||
"Let's go! One small step at a time.",
|
||||
"Ready? We'll take it easy.",
|
||||
"Welcome to this level. Take your time.",
|
||||
"Great idea to keep going. Let's do it!"
|
||||
],
|
||||
"welcome_back": [
|
||||
"Good to see you again! We pick up where you left off.",
|
||||
"You're back! No pressure, we'll go gently.",
|
||||
"Welcome back. Even a short session counts."
|
||||
],
|
||||
"success_step": [
|
||||
"Well done, that's correct!",
|
||||
"Exactly right. You're getting the hang of it.",
|
||||
"Clean! Shall we move on?",
|
||||
"It works. You're making progress."
|
||||
],
|
||||
"success_first_try": [
|
||||
"First try, well done!",
|
||||
"Right and straight to the point. Impressive!",
|
||||
"All correct on the first attempt!"
|
||||
],
|
||||
"success_after_retry": [
|
||||
"You kept at it, and it paid off!",
|
||||
"There, you found it. Every attempt got you closer.",
|
||||
"Well done for carrying on: that's how we learn."
|
||||
],
|
||||
"error_runtime": [
|
||||
"An error is a clue: look at the line shown.",
|
||||
"Don't panic, it happens to everyone. Let's read the message together.",
|
||||
"Python tells you where to look: that's helpful, not a failure.",
|
||||
"Almost! Fix the line shown and run again."
|
||||
],
|
||||
"fail_tests": [
|
||||
"It runs, but it's not the expected result yet. Reread the instruction.",
|
||||
"You're on the right track. Compare what is printed with what is asked.",
|
||||
"Not quite. A small detail to adjust?"
|
||||
],
|
||||
"suggest_hint": [
|
||||
"A hint can help: the Hint button is there for that.",
|
||||
"Stuck? Ask for a hint, there is no penalty."
|
||||
],
|
||||
"hint_revealed": [
|
||||
"Here's a nudge. Over to you!",
|
||||
"One more hint: try it with that.",
|
||||
"Does that help? Go back to your code and test."
|
||||
],
|
||||
"interrupted": [
|
||||
"Execution stopped. Good call cutting the loop!",
|
||||
"Stop! Check that your loop's condition can become false."
|
||||
],
|
||||
"input_waiting": [
|
||||
"I'm listening: type your answer.",
|
||||
"The program is waiting for your input."
|
||||
],
|
||||
"level_complete": [
|
||||
"Level complete: +{xp} XP! Nice step.",
|
||||
"Well done! +{xp} XP, and you learned something solid.",
|
||||
"Mission accomplished, +{xp} XP. You can be proud."
|
||||
],
|
||||
"level_complete_replay": [
|
||||
"Nicely revised! No new XP, but practice counts.",
|
||||
"Reviewing is always a good idea."
|
||||
],
|
||||
"streak": [
|
||||
"{days} days in a row! Come back tomorrow, no pressure.",
|
||||
"A {days}-day streak: you're building a nice habit."
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
{
|
||||
"level_start": [
|
||||
"C'est parti ! Une petite étape à la fois.",
|
||||
"Prêt·e ? On avance tranquillement.",
|
||||
"Bienvenue dans ce niveau. Prends ton temps.",
|
||||
"Bonne idée de continuer. Allons-y !"
|
||||
],
|
||||
"welcome_back": [
|
||||
"Content de te revoir ! On reprend là où tu t'étais arrêté·e.",
|
||||
"Te revoilà ! Aucune pression, on y va doucement.",
|
||||
"Bon retour. Même une petite session compte."
|
||||
],
|
||||
"success_step": [
|
||||
"Bien joué, c'est correct !",
|
||||
"Exactement ça. Tu prends le coup de main.",
|
||||
"Propre ! Passons à la suite ?",
|
||||
"Ça marche. Tu progresses."
|
||||
],
|
||||
"success_first_try": [
|
||||
"Du premier coup, bravo !",
|
||||
"Juste et sans détour. Impressionnant !",
|
||||
"Tout bon dès le premier essai !"
|
||||
],
|
||||
"success_after_retry": [
|
||||
"Tu as persévéré, et ça a payé !",
|
||||
"Voilà, tu l'as trouvé. Chaque essai t'a rapproché·e.",
|
||||
"Bravo d'avoir continué : c'est comme ça qu'on apprend."
|
||||
],
|
||||
"error_runtime": [
|
||||
"Une erreur, c'est un indice : regarde la ligne indiquée.",
|
||||
"Pas de panique, ça arrive à tout le monde. Lis le message avec moi.",
|
||||
"Python te dit où chercher : c'est utile, pas un échec.",
|
||||
"Presque ! Corrige la ligne signalée et relance."
|
||||
],
|
||||
"fail_tests": [
|
||||
"Ça tourne, mais ce n'est pas encore le résultat attendu. Relis la consigne.",
|
||||
"Tu es sur la bonne voie. Compare ce qui s'affiche avec ce qui est demandé.",
|
||||
"Pas tout à fait. Un petit détail à ajuster ?"
|
||||
],
|
||||
"suggest_hint": [
|
||||
"Un indice peut aider : le bouton Indice est là pour ça.",
|
||||
"Bloqué·e ? Demande un indice, il n'y a aucune pénalité."
|
||||
],
|
||||
"hint_revealed": [
|
||||
"Voilà un coup de pouce. À toi de jouer !",
|
||||
"Un indice de plus : essaie avec ça.",
|
||||
"Ça t'aide ? Reprends ton code et teste."
|
||||
],
|
||||
"interrupted": [
|
||||
"Exécution arrêtée. Bien vu d'avoir coupé la boucle !",
|
||||
"Stop ! Vérifie que la condition de ta boucle peut devenir fausse."
|
||||
],
|
||||
"input_waiting": [
|
||||
"Je t'écoute : tape ta réponse.",
|
||||
"Le programme attend ta saisie."
|
||||
],
|
||||
"level_complete": [
|
||||
"Niveau terminé : +{xp} XP ! Belle étape.",
|
||||
"Bravo ! +{xp} XP, et tu as appris du solide.",
|
||||
"Mission accomplie, +{xp} XP. Tu peux être fier·ère."
|
||||
],
|
||||
"level_complete_replay": [
|
||||
"Bien revu ! Pas de nouveaux XP, mais la pratique, ça compte.",
|
||||
"Réviser, c'est toujours une bonne idée."
|
||||
],
|
||||
"streak": [
|
||||
"{days} jours de suite ! Reviens demain, sans pression.",
|
||||
"Série de {days} jours : tu prends une belle habitude."
|
||||
]
|
||||
}
|
||||
+22
-4
@@ -2,6 +2,7 @@
|
||||
|
||||
import { AudioEngine } from './core/AudioEngine.js';
|
||||
import { ErrorTranslator } from './core/ErrorTranslator.js';
|
||||
import { GuideEngine } from './core/GuideEngine.js';
|
||||
import { LessonEngine } from './core/LessonEngine.js';
|
||||
import { IndexedDbKeyValueStore, MemoryKeyValueStore } from './core/KeyValueStores.js';
|
||||
import { ProgressStore } from './core/ProgressStore.js';
|
||||
@@ -49,6 +50,7 @@ function applySettings(settings) {
|
||||
root.setAttribute('data-theme', settings.theme);
|
||||
}
|
||||
root.lang = settings.lang;
|
||||
root.dataset.guide = settings.guideEnabled ? 'on' : 'off';
|
||||
}
|
||||
|
||||
class App {
|
||||
@@ -73,11 +75,13 @@ class App {
|
||||
this.#settings = new SettingsStore(store);
|
||||
const settings = await this.#settings.load();
|
||||
|
||||
const [translations, errorCatalogs] = await Promise.all([
|
||||
const [translations, errorCatalogs, guideCatalogs] = await Promise.all([
|
||||
Promise.all(LANGUAGES.map((lang) => loadJson(`./i18n/${lang}.json`))),
|
||||
Promise.all(LANGUAGES.map((lang) => loadJson(`./i18n/errors.${lang}.json`))),
|
||||
Promise.all(LANGUAGES.map((lang) => loadJson(`./i18n/guide.${lang}.json`))),
|
||||
]);
|
||||
this.#i18n = new I18n(Object.fromEntries(LANGUAGES.map((lang, i) => [lang, translations[i]])), settings.lang);
|
||||
const guide = new GuideEngine(Object.fromEntries(LANGUAGES.map((lang, i) => [lang, guideCatalogs[i]])));
|
||||
const translator = new ErrorTranslator(Object.fromEntries(LANGUAGES.map((lang, i) => [lang, errorCatalogs[i]])));
|
||||
|
||||
this.#progress = new ProgressStore(store);
|
||||
@@ -103,6 +107,7 @@ class App {
|
||||
audio: this.#audio,
|
||||
progress: this.#progress,
|
||||
toast,
|
||||
guide,
|
||||
});
|
||||
this.#manager.addEventListener('levelcomplete', () => this.#renderMap());
|
||||
|
||||
@@ -129,10 +134,23 @@ class App {
|
||||
const next = requested ?? this.#levelIds.find((id) => !this.#progress.isCompleted(id)) ?? this.#levelIds.at(-1);
|
||||
history.replaceState(null, '', `#/levels/${next}`);
|
||||
window.addEventListener('popstate', () => this.#openLevel(this.#levelFromHash() ?? this.#levelIds[0]));
|
||||
await this.#openLevel(next);
|
||||
// Retour après une pause (2 jours ou plus sans activité) : accueil bienveillant, sans reproche.
|
||||
await this.#openLevel(next, { greeting: this.#isReturning() ? 'welcome_back' : 'level_start' });
|
||||
this.#registerServiceWorker();
|
||||
}
|
||||
|
||||
/** Vrai si l'apprenant a déjà de l'activité mais pas depuis au moins deux jours. */
|
||||
#isReturning() {
|
||||
const { lastDay } = this.#progress.snapshot().streak;
|
||||
if (!lastDay) {
|
||||
return false;
|
||||
}
|
||||
const [year, month, day] = lastDay.split('-').map(Number);
|
||||
const now = new Date();
|
||||
const days = (Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()) - Date.UTC(year, month - 1, day)) / 86400000;
|
||||
return days >= 2;
|
||||
}
|
||||
|
||||
/** Id de niveau demandé par l'URL (#/levels/<id>), s'il existe. */
|
||||
#levelFromHash() {
|
||||
const match = /^#\/levels\/([a-z0-9-]+)$/.exec(location.hash);
|
||||
@@ -150,12 +168,12 @@ class App {
|
||||
await this.#openLevel(id);
|
||||
}
|
||||
|
||||
async #openLevel(id) {
|
||||
async #openLevel(id, { greeting = 'level_start' } = {}) {
|
||||
this.#currentId = id;
|
||||
await this.#renderMap();
|
||||
const session = await this.#lessons.startLevel(id, this.#i18n.lang);
|
||||
this.#updateLevelNav(session.title);
|
||||
await this.#manager.start(session);
|
||||
await this.#manager.start(session, { greeting });
|
||||
}
|
||||
|
||||
async #renderMap() {
|
||||
|
||||
@@ -9,6 +9,7 @@ export class CellManager extends EventTarget {
|
||||
#deps;
|
||||
#stepValidator;
|
||||
#session = null;
|
||||
#passes = 0; // réussites du premier coup : alterne deux familles de messages pour varier
|
||||
|
||||
/**
|
||||
* @param {object} deps
|
||||
@@ -20,6 +21,7 @@ export class CellManager extends EventTarget {
|
||||
* @param {import('../core/AudioEngine.js').AudioEngine} deps.audio
|
||||
* @param {import('../core/ProgressStore.js').ProgressStore} deps.progress
|
||||
* @param {import('./BadgeToast.js').BadgeToast} deps.toast
|
||||
* @param {import('../core/GuideEngine.js').GuideEngine} deps.guide
|
||||
*/
|
||||
constructor(deps) {
|
||||
super();
|
||||
@@ -27,8 +29,12 @@ export class CellManager extends EventTarget {
|
||||
this.#stepValidator = new StepValidator({ client: deps.client, validator: deps.validator });
|
||||
}
|
||||
|
||||
/** Démarre (ou redémarre) un niveau à partir d'une LevelSession. */
|
||||
async start(session) {
|
||||
/**
|
||||
* Démarre (ou redémarre) un niveau à partir d'une LevelSession.
|
||||
* @param {object} [options]
|
||||
* @param {string} [options.greeting] Situation du guide pour l'accueil ('level_start' ou 'welcome_back').
|
||||
*/
|
||||
async start(session, { greeting = 'level_start' } = {}) {
|
||||
const { notebook, client, i18n } = this.#deps;
|
||||
this.#session = session;
|
||||
notebook.clear();
|
||||
@@ -41,9 +47,14 @@ export class CellManager extends EventTarget {
|
||||
return;
|
||||
}
|
||||
notebook.setStatus('');
|
||||
notebook.addGuide(this.#say(greeting));
|
||||
this.#showCurrent();
|
||||
}
|
||||
|
||||
#say(situation, params = {}) {
|
||||
return this.#deps.guide.say(situation, this.#deps.i18n.lang, params);
|
||||
}
|
||||
|
||||
#showCurrent() {
|
||||
const session = this.#session;
|
||||
if (session.onMission) {
|
||||
@@ -80,9 +91,11 @@ export class CellManager extends EventTarget {
|
||||
notebook.add(cell.element);
|
||||
cell.focus();
|
||||
cell.addEventListener('stop', () => this.#stop(cell));
|
||||
cell.addEventListener('hint', () => cell.showGuide(this.#say('hint_revealed')));
|
||||
const state = { failures: 0 };
|
||||
let continueShown = false;
|
||||
cell.addEventListener('run', async (event) => {
|
||||
const passed = await this.#execute(cell, event.detail.code, step.tests);
|
||||
const passed = await this.#execute(cell, event.detail.code, step.tests, state);
|
||||
if (passed && !continueShown) {
|
||||
continueShown = true;
|
||||
notebook.addAction(i18n.t('step.continue'), () => this.#advance());
|
||||
@@ -104,13 +117,20 @@ export class CellManager extends EventTarget {
|
||||
notebook.add(cell.element);
|
||||
cell.focus();
|
||||
cell.addEventListener('stop', () => this.#stop(cell));
|
||||
cell.addEventListener('hint', () => cell.showGuide(this.#say('hint_revealed')));
|
||||
const state = { failures: 0 };
|
||||
cell.addEventListener('run', async (event) => {
|
||||
if (await this.#execute(cell, event.detail.code, mission.tests)) {
|
||||
if (await this.#execute(cell, event.detail.code, mission.tests, state)) {
|
||||
await this.#completeLevel(mission);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Deux échecs d'affilée et des indices encore cachés : le guide suggère un indice. */
|
||||
#struggling(cell, state) {
|
||||
return state.failures >= 2 && cell.hasHintsLeft;
|
||||
}
|
||||
|
||||
#stop(cell) {
|
||||
// Ordre important : l'interruption doit être posée avant d'annuler la saisie en attente,
|
||||
// pour que Python reçoive KeyboardInterrupt plutôt qu'une fin de fichier.
|
||||
@@ -122,7 +142,7 @@ export class CellManager extends EventTarget {
|
||||
* Exécute le code d'une cellule et valide. Renvoie vrai si tous les tests passent.
|
||||
* Les tests qui déclarent `inputs` rejouent le code, en isolation, avec ces saisies scriptées.
|
||||
*/
|
||||
async #execute(cell, code, tests) {
|
||||
async #execute(cell, code, tests, state) {
|
||||
const { client, translator, audio, i18n } = this.#deps;
|
||||
await audio.unlock(); // le clic sur « Exécuter » est le geste utilisateur requis
|
||||
cell.clearOutput();
|
||||
@@ -136,19 +156,37 @@ export class CellManager extends EventTarget {
|
||||
collect: ValidationEngine.variablesToCollect(tests),
|
||||
onStdout: onOutput,
|
||||
onStderr: onOutput,
|
||||
onInput: (prompt) => cell.requestInput(prompt),
|
||||
onInput: (prompt) => {
|
||||
cell.showGuide(this.#say('input_waiting'));
|
||||
return cell.requestInput(prompt);
|
||||
},
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
cell.setBusy(false);
|
||||
cell.showError(translator.translate(result.error, i18n.lang));
|
||||
audio.play('error');
|
||||
if (result.error.type === 'KeyboardInterrupt') {
|
||||
cell.showGuide(this.#say('interrupted'));
|
||||
} else {
|
||||
state.failures += 1;
|
||||
cell.showGuide(this.#say(this.#struggling(cell, state) ? 'suggest_hint' : 'error_runtime'));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
const validation = await this.#stepValidator.validate(code, tests, { stdout, result });
|
||||
cell.setBusy(false);
|
||||
cell.showValidation(validation);
|
||||
audio.play(validation.passed ? 'success_small' : 'error');
|
||||
if (validation.passed) {
|
||||
const first = state.failures === 0;
|
||||
this.#passes += first ? 1 : 0;
|
||||
cell.showGuide(this.#say(first ? (this.#passes % 2 === 1 ? 'success_first_try' : 'success_step') : 'success_after_retry'));
|
||||
state.failures = 0;
|
||||
} else {
|
||||
state.failures += 1;
|
||||
cell.showGuide(this.#say(this.#struggling(cell, state) ? 'suggest_hint' : 'fail_tests'));
|
||||
}
|
||||
return validation.passed;
|
||||
}
|
||||
|
||||
@@ -161,6 +199,10 @@ export class CellManager extends EventTarget {
|
||||
toast.showBadge(badge);
|
||||
}
|
||||
notebook.setStatus(i18n.t('mission.done', { xp: outcome.xpGained }));
|
||||
notebook.addGuide(this.#say(outcome.alreadyCompleted ? 'level_complete_replay' : 'level_complete', { xp: outcome.xpGained }));
|
||||
if (!outcome.alreadyCompleted && outcome.streak.current >= 2) {
|
||||
notebook.addGuide(this.#say('streak', { days: outcome.streak.current }));
|
||||
}
|
||||
this.dispatchEvent(new CustomEvent('levelcomplete', { detail: outcome }));
|
||||
}
|
||||
}
|
||||
|
||||
+18
-1
@@ -3,6 +3,7 @@
|
||||
|
||||
import { el, renderInline, uniqueId } from './dom.js';
|
||||
import { CodeEditor } from './CodeEditor.js';
|
||||
import { GuideBubble } from './GuideBubble.js';
|
||||
import { HintPanel } from './HintPanel.js';
|
||||
|
||||
export class CellView extends EventTarget {
|
||||
@@ -12,6 +13,8 @@ export class CellView extends EventTarget {
|
||||
#editor;
|
||||
#output;
|
||||
#feedback;
|
||||
#guideSlot;
|
||||
#hintPanel;
|
||||
#runButton;
|
||||
#stopButton;
|
||||
#busy = false;
|
||||
@@ -57,6 +60,8 @@ export class CellView extends EventTarget {
|
||||
|
||||
this.#output = el('pre', { id: outputId, class: 'cell-output', 'aria-live': 'polite', 'aria-label': i18n.t('cell.output') });
|
||||
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')) });
|
||||
|
||||
// Saisie demandée par input() : formulaire affiché seulement pendant l'attente.
|
||||
const inputId = uniqueId('input');
|
||||
@@ -79,10 +84,11 @@ export class CellView extends EventTarget {
|
||||
el('p', { class: 'cell-instruction' }, renderInline(instruction)),
|
||||
this.#editor.element,
|
||||
el('p', { id: `${editorId}-hint`, class: 'cell-shortcut', text: i18n.t('cell.shortcut') }),
|
||||
el('div', { class: 'cell-actions' }, this.#runButton, this.#stopButton, resetButton, new HintPanel(i18n, hints).element),
|
||||
el('div', { class: 'cell-actions' }, this.#runButton, this.#stopButton, resetButton, this.#hintPanel.element),
|
||||
this.#output,
|
||||
this.#inputForm,
|
||||
this.#feedback,
|
||||
this.#guideSlot,
|
||||
solutionBlock,
|
||||
);
|
||||
}
|
||||
@@ -110,6 +116,17 @@ export class CellView extends EventTarget {
|
||||
clearOutput() {
|
||||
this.#output.textContent = '';
|
||||
this.#feedback.replaceChildren();
|
||||
this.#guideSlot.replaceChildren();
|
||||
}
|
||||
|
||||
/** Reste-t-il des indices à révéler ? */
|
||||
get hasHintsLeft() {
|
||||
return this.#hintPanel.hasMore;
|
||||
}
|
||||
|
||||
/** Affiche un message du personnage-guide sous le retour de validation. */
|
||||
showGuide(message) {
|
||||
this.#guideSlot.replaceChildren(new GuideBubble(message).element);
|
||||
}
|
||||
|
||||
appendOutput(text) {
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
// Bulle du personnage-guide : avatar (chouette) + message. Décoratif pour les lecteurs d'écran
|
||||
// (l'avatar est masqué) ; le texte reste lisible dans l'ordre de lecture.
|
||||
|
||||
import { el } from './dom.js';
|
||||
import { createOwl } from './guideArt.js';
|
||||
|
||||
export class GuideBubble {
|
||||
#root;
|
||||
|
||||
/** @param {{text: string, mood: string}} message Issu de GuideEngine.say(). */
|
||||
constructor({ text, mood }) {
|
||||
this.#root = el(
|
||||
'div',
|
||||
{ class: 'guide-bubble', 'data-mood': mood },
|
||||
el('div', { class: 'guide-avatar', 'aria-hidden': 'true' }, createOwl()),
|
||||
el('p', { class: 'guide-text', text }),
|
||||
);
|
||||
}
|
||||
|
||||
get element() {
|
||||
return this.#root;
|
||||
}
|
||||
}
|
||||
+11
-2
@@ -5,14 +5,17 @@ import { el, renderInline } from './dom.js';
|
||||
export class HintPanel {
|
||||
#i18n;
|
||||
#hints;
|
||||
#onReveal;
|
||||
#revealed = 0;
|
||||
#button;
|
||||
#list;
|
||||
#root;
|
||||
|
||||
/** @param {string[]} hints Indices déjà localisés, du plus vague au plus précis. */
|
||||
constructor(i18n, hints) {
|
||||
/** @param {string[]} hints Indices déjà localisés, du plus vague au plus précis.
|
||||
* @param {{onReveal?: () => void}} [options] Rappel à chaque indice révélé. */
|
||||
constructor(i18n, hints, { onReveal = () => {} } = {}) {
|
||||
this.#i18n = i18n;
|
||||
this.#onReveal = onReveal;
|
||||
this.#hints = hints;
|
||||
this.#button = el('button', { type: 'button', class: 'btn', onclick: () => this.reveal() });
|
||||
this.#list = el('ol', { class: 'hint-list', 'aria-live': 'polite' });
|
||||
@@ -24,6 +27,11 @@ export class HintPanel {
|
||||
return this.#root;
|
||||
}
|
||||
|
||||
/** Reste-t-il au moins un indice à révéler ? */
|
||||
get hasMore() {
|
||||
return this.#revealed < this.#hints.length;
|
||||
}
|
||||
|
||||
/** Affiche l'indice suivant. Renvoie false s'il n'en reste plus. */
|
||||
reveal() {
|
||||
if (this.#revealed >= this.#hints.length) {
|
||||
@@ -32,6 +40,7 @@ export class HintPanel {
|
||||
this.#list.append(el('li', {}, renderInline(this.#hints[this.#revealed])));
|
||||
this.#revealed += 1;
|
||||
this.#refresh();
|
||||
this.#onReveal();
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// Zone verticale façon notebook : étapes d'explication, cellules et messages s'empilent.
|
||||
|
||||
import { GuideBubble } from './GuideBubble.js';
|
||||
import { el, renderInline } from './dom.js';
|
||||
|
||||
export class NotebookView {
|
||||
@@ -69,6 +70,11 @@ export class NotebookView {
|
||||
return this.add(el('section', { class: 'explain', tabindex: '-1' }, ...children));
|
||||
}
|
||||
|
||||
/** Message du personnage-guide dans le fil du notebook (sans déplacer le focus). */
|
||||
addGuide(message) {
|
||||
return this.add(new GuideBubble(message).element, { focus: false });
|
||||
}
|
||||
|
||||
/** Réaffiche ou masque les boutons « Écouter » existants (réglage de la voix modifié). */
|
||||
refreshVoiceButtons() {
|
||||
const visible = this.#canSpeak();
|
||||
|
||||
@@ -34,6 +34,7 @@ export class SettingsPanel extends EventTarget {
|
||||
options: ['auto', 'light', 'dark'].map((theme) => [theme, t(`settings.theme.${theme}`)]),
|
||||
key: 'theme',
|
||||
}),
|
||||
this.#field('settings.guide', 'checkbox', { value: settings.guideEnabled, key: 'guideEnabled' }),
|
||||
this.#field('settings.sound', 'checkbox', { value: settings.soundEnabled, key: 'soundEnabled' }),
|
||||
this.#testButton('settings.testSound', 'sound'),
|
||||
this.#field('settings.volume', 'range', { value: settings.volume, min: 0, max: 1, step: 0.1, key: 'volume', number: true }),
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
// Dessin de la chouette-guide (SVG constant, aux couleurs du thème via les classes CSS de guide.css).
|
||||
// L'humeur (neutral, happy, thinking, celebrate) est portée par l'attribut data-mood du conteneur.
|
||||
|
||||
const OWL_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 120" class="owl" aria-hidden="true" focusable="false">
|
||||
<g class="owl-wings">
|
||||
<ellipse class="owl-body" cx="17" cy="54" rx="9" ry="21" transform="rotate(-22 17 54)"/>
|
||||
<ellipse class="owl-body" cx="103" cy="54" rx="9" ry="21" transform="rotate(22 103 54)"/>
|
||||
</g>
|
||||
<ellipse class="owl-body" cx="60" cy="68" rx="38" ry="42"/>
|
||||
<path class="owl-body" d="M30 38 L38 14 L52 30 Z M90 38 L82 14 L68 30 Z"/>
|
||||
<ellipse class="owl-belly" cx="60" cy="92" rx="22" ry="14"/>
|
||||
<circle class="owl-eye" cx="44" cy="58" r="15"/>
|
||||
<circle class="owl-eye" cx="76" cy="58" r="15"/>
|
||||
<g class="eyes-round">
|
||||
<circle class="owl-pupil" cx="46" cy="59" r="7"/>
|
||||
<circle class="owl-pupil" cx="74" cy="59" r="7"/>
|
||||
<circle class="owl-glint" cx="48" cy="56" r="2.2"/>
|
||||
<circle class="owl-glint" cx="76" cy="56" r="2.2"/>
|
||||
</g>
|
||||
<g class="eyes-happy">
|
||||
<path class="owl-line" d="M35 61 Q44 49 53 61"/>
|
||||
<path class="owl-line" d="M67 61 Q76 49 85 61"/>
|
||||
</g>
|
||||
<g class="eyes-thinking">
|
||||
<circle class="owl-pupil" cx="50" cy="54" r="7"/>
|
||||
<circle class="owl-pupil" cx="80" cy="54" r="7"/>
|
||||
<circle class="owl-glint" cx="52" cy="51" r="2.2"/>
|
||||
<circle class="owl-glint" cx="82" cy="51" r="2.2"/>
|
||||
<path class="owl-line" d="M30 38 L56 43"/>
|
||||
</g>
|
||||
<path class="owl-beak" d="M54 72 L66 72 L60 84 Z"/>
|
||||
<g class="owl-sparkles">
|
||||
<path class="owl-spark" d="M8 14 L11 22 L19 25 L11 28 L8 36 L5 28 L-3 25 L5 22 Z" transform="translate(6 -2) scale(.7)"/>
|
||||
<path class="owl-spark" d="M8 14 L11 22 L19 25 L11 28 L8 36 L5 28 L-3 25 L5 22 Z" transform="translate(92 4) scale(.55)"/>
|
||||
</g>
|
||||
</svg>`;
|
||||
|
||||
/** Crée un nouvel élément SVG de chouette. */
|
||||
export function createOwl() {
|
||||
// Marque constante (jamais construite à partir de données externes) : l'analyse DOM est sûre.
|
||||
const document_ = new DOMParser().parseFromString(OWL_SVG, 'image/svg+xml');
|
||||
return document.importNode(document_.documentElement, true);
|
||||
}
|
||||
@@ -3,9 +3,9 @@
|
||||
// - Pyodide vendorisé, niveaux, scripts : mis en cache à la première utilisation (hors ligne ensuite).
|
||||
// Les en-têtes COOP/COEP du document viennent du serveur ; ce worker ne les fabrique pas.
|
||||
|
||||
const CACHE_VERSION = 'pyquest-v3';
|
||||
const CACHE_VERSION = 'pyquest-v4';
|
||||
|
||||
const SHELL = ['./', 'index.html', 'manifest.webmanifest', 'css/themes.css', 'css/base.css', 'css/cells.css', 'icons/icon.svg', 'js/main.js'];
|
||||
const SHELL = ['./', 'index.html', 'manifest.webmanifest', 'css/themes.css', 'css/base.css', 'css/cells.css', 'css/guide.css', 'icons/icon.svg', 'js/main.js'];
|
||||
|
||||
self.addEventListener('install', (event) => {
|
||||
event.waitUntil(caches.open(CACHE_VERSION).then((cache) => cache.addAll(SHELL)));
|
||||
|
||||
Reference in New Issue
Block a user