Déplacement de fichiers et cohérence des header d'exercices
This commit is contained in:
387
exercices/memory-pictogrammes/assets/js/analytics.js
Normal file
387
exercices/memory-pictogrammes/assets/js/analytics.js
Normal file
@@ -0,0 +1,387 @@
|
||||
/* ============================================
|
||||
ANALYTICS & EVENT TRACKING
|
||||
============================================ */
|
||||
|
||||
/**
|
||||
* Manager d'analytics pour tracker les événements
|
||||
*/
|
||||
class AnalyticsManager {
|
||||
constructor() {
|
||||
this.sessionId = generateUUID();
|
||||
this.events = [];
|
||||
this.enabled = true;
|
||||
this.endpoint = window.ANALYTICS_ENDPOINT || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enregistrer un événement
|
||||
*/
|
||||
track(eventName, data = {}) {
|
||||
if (!this.enabled) return;
|
||||
|
||||
const event = {
|
||||
type: eventName,
|
||||
timestamp: Date.now(),
|
||||
sessionId: this.sessionId,
|
||||
userId: getUserId(),
|
||||
playerName: getPlayerName(),
|
||||
data: data
|
||||
};
|
||||
|
||||
this.events.push(event);
|
||||
|
||||
// Logger en debug
|
||||
DEBUG.log(`Event tracked: ${eventName}`, data);
|
||||
|
||||
// Envoyer au serveur si configuré
|
||||
if (this.endpoint) {
|
||||
this.sendToServer(event);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Démarrage du jeu
|
||||
*/
|
||||
trackGameStart(difficulty) {
|
||||
this.track('game_started', {
|
||||
difficulty: difficulty,
|
||||
mode: DIFFICULTY_MODES[difficulty].name
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Retournement de carte
|
||||
*/
|
||||
trackFlip(cardIndex, totalFlips) {
|
||||
this.track('card_flipped', {
|
||||
cardIndex: cardIndex,
|
||||
totalFlips: totalFlips
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Paire trouvée
|
||||
*/
|
||||
trackMatch(pictogrammeId, totalMatches, totalMoves) {
|
||||
this.track('pair_matched', {
|
||||
pictogrammeId: pictogrammeId,
|
||||
totalMatches: totalMatches,
|
||||
totalMoves: totalMoves
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Paire incorrecte
|
||||
*/
|
||||
trackMismatch(pictogramme1Id, pictogramme2Id, move) {
|
||||
this.track('pair_mismatched', {
|
||||
pictogramme1: pictogramme1Id,
|
||||
pictogramme2: pictogramme2Id,
|
||||
move: move
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Fin du jeu
|
||||
*/
|
||||
trackGameEnd(gameData) {
|
||||
this.track('game_completed', {
|
||||
difficulty: gameData.difficulty,
|
||||
finalScore: gameData.finalScore,
|
||||
moves: gameData.moves,
|
||||
duration: gameData.duration,
|
||||
won: gameData.won,
|
||||
achievements: gameData.achievements || []
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Changement de difficulté
|
||||
*/
|
||||
trackDifficultyChange(newDifficulty) {
|
||||
this.track('difficulty_changed', {
|
||||
newDifficulty: newDifficulty
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Affichage du classement
|
||||
*/
|
||||
trackLeaderboardView(filter) {
|
||||
this.track('leaderboard_viewed', {
|
||||
filter: filter
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Envoyer les événements au serveur
|
||||
*/
|
||||
sendToServer(event) {
|
||||
if (!this.endpoint) return;
|
||||
|
||||
fetch(this.endpoint, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(event)
|
||||
}).catch(err => {
|
||||
// Silencieusement échouer en offline
|
||||
DEBUG.log('Analytics offline:', err);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Envoyer batch d'événements
|
||||
*/
|
||||
sendBatch() {
|
||||
if (!this.endpoint || this.events.length === 0) return;
|
||||
|
||||
fetch(this.endpoint, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
batch: true,
|
||||
events: this.events,
|
||||
sessionId: this.sessionId
|
||||
})
|
||||
}).then(() => {
|
||||
this.events = []; // Vider après envoi
|
||||
DEBUG.log('Analytics batch sent');
|
||||
}).catch(err => {
|
||||
DEBUG.log('Analytics batch failed:', err);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtenir le résumé de la session
|
||||
*/
|
||||
getSessionSummary() {
|
||||
return {
|
||||
sessionId: this.sessionId,
|
||||
userId: getUserId(),
|
||||
playerName: getPlayerName(),
|
||||
eventCount: this.events.length,
|
||||
events: this.events
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Exporter les données en JSON
|
||||
*/
|
||||
exportJSON() {
|
||||
const data = {
|
||||
exportDate: new Date().toISOString(),
|
||||
sessionSummary: this.getSessionSummary(),
|
||||
allEvents: this.events
|
||||
};
|
||||
return JSON.stringify(data, null, 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Télécharger les données
|
||||
*/
|
||||
downloadData() {
|
||||
const data = this.exportJSON();
|
||||
const blob = new Blob([data], { type: 'application/json' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = `analytics-${generateUUID().slice(0, 8)}.json`;
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
/**
|
||||
* Nettoyer les événements
|
||||
*/
|
||||
clear() {
|
||||
this.events = [];
|
||||
DEBUG.log('Analytics cleared');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Heatmap Analytics - Tracker l'interaction avec les cartes
|
||||
*/
|
||||
class HeatmapAnalytics {
|
||||
constructor() {
|
||||
this.heatmap = new Map();
|
||||
}
|
||||
|
||||
/**
|
||||
* Enregistrer un clic de carte
|
||||
*/
|
||||
recordCardClick(cardIndex) {
|
||||
if (!this.heatmap.has(cardIndex)) {
|
||||
this.heatmap.set(cardIndex, 0);
|
||||
}
|
||||
this.heatmap.set(cardIndex, this.heatmap.get(cardIndex) + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtenir les données de heatmap
|
||||
*/
|
||||
getHeatmap() {
|
||||
const sorted = Array.from(this.heatmap.entries())
|
||||
.sort((a, b) => b[1] - a[1]);
|
||||
|
||||
return Object.fromEntries(sorted);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculer la carte la plus cliquée
|
||||
*/
|
||||
getMostClickedCard() {
|
||||
let maxClicks = 0;
|
||||
let maxCard = -1;
|
||||
|
||||
for (const [card, clicks] of this.heatmap) {
|
||||
if (clicks > maxClicks) {
|
||||
maxClicks = clicks;
|
||||
maxCard = card;
|
||||
}
|
||||
}
|
||||
|
||||
return { card: maxCard, clicks: maxClicks };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Performance Monitor - Analyser les performances du jeu
|
||||
*/
|
||||
class PerformanceMonitor {
|
||||
constructor() {
|
||||
this.metrics = {};
|
||||
this.startTime = performance.now();
|
||||
}
|
||||
|
||||
/**
|
||||
* Marquer un point de début
|
||||
*/
|
||||
mark(name) {
|
||||
this.metrics[name] = {
|
||||
start: performance.now(),
|
||||
end: null,
|
||||
duration: null
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Marquer la fin
|
||||
*/
|
||||
measure(name) {
|
||||
if (this.metrics[name]) {
|
||||
this.metrics[name].end = performance.now();
|
||||
this.metrics[name].duration = this.metrics[name].end - this.metrics[name].start;
|
||||
return this.metrics[name].duration;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtenir les métriques
|
||||
*/
|
||||
getMetrics() {
|
||||
return this.metrics;
|
||||
}
|
||||
|
||||
/**
|
||||
* Afficher les métriques en console
|
||||
*/
|
||||
logMetrics() {
|
||||
console.table(this.metrics);
|
||||
}
|
||||
|
||||
/**
|
||||
* FPS Monitor
|
||||
*/
|
||||
monitorFPS(callback) {
|
||||
let lastTime = performance.now();
|
||||
let frames = 0;
|
||||
|
||||
const checkFPS = () => {
|
||||
frames++;
|
||||
const currentTime = performance.now();
|
||||
|
||||
if (currentTime - lastTime >= 1000) {
|
||||
const fps = frames;
|
||||
callback(fps);
|
||||
frames = 0;
|
||||
lastTime = currentTime;
|
||||
}
|
||||
|
||||
requestAnimationFrame(checkFPS);
|
||||
};
|
||||
|
||||
checkFPS();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A/B Testing Manager
|
||||
*/
|
||||
class ABTestingManager {
|
||||
constructor() {
|
||||
this.tests = {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Créer un test A/B
|
||||
*/
|
||||
createTest(testName, variants) {
|
||||
const userId = getUserId();
|
||||
const variantIndex = parseInt(userId.slice(0, 8), 16) % variants.length;
|
||||
|
||||
this.tests[testName] = {
|
||||
variants: variants,
|
||||
selectedVariant: variants[variantIndex],
|
||||
variantIndex: variantIndex
|
||||
};
|
||||
|
||||
return this.tests[testName].selectedVariant;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtenir le variant
|
||||
*/
|
||||
getVariant(testName) {
|
||||
return this.tests[testName]?.selectedVariant || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tracker une conversion
|
||||
*/
|
||||
trackConversion(testName) {
|
||||
const test = this.tests[testName];
|
||||
if (test) {
|
||||
DEBUG.log(`Conversion tracked for test: ${testName}, variant: ${test.selectedVariant}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// INITIALISATION GLOBALES
|
||||
// ============================================
|
||||
|
||||
// Créer les managers globalement
|
||||
const analyticsManager = new AnalyticsManager();
|
||||
const heatmapAnalytics = new HeatmapAnalytics();
|
||||
const performanceMonitor = new PerformanceMonitor();
|
||||
const abTestingManager = new ABTestingManager();
|
||||
|
||||
// Exporter pour utilisation
|
||||
window.AnalyticsManager = AnalyticsManager;
|
||||
window.HeatmapAnalytics = HeatmapAnalytics;
|
||||
window.PerformanceMonitor = PerformanceMonitor;
|
||||
window.ABTestingManager = ABTestingManager;
|
||||
|
||||
// Event listener pour envoyer les analytics avant de quitter
|
||||
window.addEventListener('beforeunload', () => {
|
||||
analyticsManager.sendBatch();
|
||||
});
|
||||
|
||||
// Log de session au démarrage
|
||||
DEBUG.log('Analytics session started:', analyticsManager.sessionId);
|
||||
359
exercices/memory-pictogrammes/assets/js/game-state.js
Normal file
359
exercices/memory-pictogrammes/assets/js/game-state.js
Normal file
@@ -0,0 +1,359 @@
|
||||
/* ============================================
|
||||
GAME STATE & SCORING ENGINE
|
||||
============================================ */
|
||||
|
||||
/**
|
||||
* Moteur de scoring avancé
|
||||
* Calcule les points avec bonus temps et efficacité
|
||||
*/
|
||||
class ScoringEngine {
|
||||
constructor() {
|
||||
this.basePoints = 1000;
|
||||
this.difficultyMultiplier = 1;
|
||||
this.timeBonus = 0;
|
||||
this.efficiencyBonus = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculer le score final
|
||||
* Formule : basePoints × difficultyMultiplier + timeBonus + efficiencyBonus
|
||||
*/
|
||||
calculateFinalScore(moves, timeSeconds, pairesTotal, difficulty) {
|
||||
const mode = DIFFICULTY_MODES[difficulty];
|
||||
this.difficultyMultiplier = mode.scoreMultiplier;
|
||||
|
||||
// Bonus temps : points restants
|
||||
const timeRemaining = Math.max(0, mode.timeLimit - timeSeconds);
|
||||
this.timeBonus = Math.round((timeRemaining / mode.timeLimit) * 500);
|
||||
|
||||
// Bonus efficacité : pénalité pour erreurs
|
||||
// Jeu parfait = pairesTotal mouvements (2 cartes par paire)
|
||||
const perfectMoves = pairesTotal;
|
||||
const efficiency = Math.max(0, 1 - ((moves - perfectMoves) / (perfectMoves * 2)));
|
||||
this.efficiencyBonus = Math.round(efficiency * 500);
|
||||
|
||||
// Score final
|
||||
const baseScore = this.basePoints * this.difficultyMultiplier;
|
||||
const finalScore = Math.round(baseScore + this.timeBonus + this.efficiencyBonus);
|
||||
|
||||
return {
|
||||
baseScore: baseScore,
|
||||
timeBonus: this.timeBonus,
|
||||
efficiencyBonus: this.efficiencyBonus,
|
||||
totalScore: finalScore,
|
||||
duration: timeSeconds,
|
||||
breakdown: {
|
||||
base: baseScore,
|
||||
temps: this.timeBonus,
|
||||
efficacite: this.efficiencyBonus,
|
||||
total: finalScore
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Détecter les achievements
|
||||
*/
|
||||
detectAchievements(moves, timeSeconds, pairesTotal, difficulty) {
|
||||
const achievements = [];
|
||||
|
||||
// 🏅 Jeu parfait (0 erreurs)
|
||||
if (moves === pairesTotal) {
|
||||
achievements.push({
|
||||
id: 'perfect_game',
|
||||
name: '🏅 Jeu Parfait',
|
||||
icon: '🏅',
|
||||
description: 'Trouvé toutes les paires sans erreur!'
|
||||
});
|
||||
}
|
||||
|
||||
// ⚡ Vitesse extrême
|
||||
if (timeSeconds < DIFFICULTY_MODES[difficulty].timeLimit * 0.3) {
|
||||
achievements.push({
|
||||
id: 'speedrun',
|
||||
name: '⚡ Vitesse Éclair',
|
||||
icon: '⚡',
|
||||
description: `Complété en ${timeSeconds}s!`
|
||||
});
|
||||
}
|
||||
|
||||
// 🔥 Difficile réussi
|
||||
if (difficulty === 'hard') {
|
||||
achievements.push({
|
||||
id: 'hard_mode',
|
||||
name: '🔥 Maître du Mode Difficile',
|
||||
icon: '🔥',
|
||||
description: 'Défi chronométré réussi!'
|
||||
});
|
||||
}
|
||||
|
||||
// 🎯 Score parfait
|
||||
const perfectScore = 1000 * DIFFICULTY_MODES[difficulty].scoreMultiplier;
|
||||
if ((this.basePoints * this.difficultyMultiplier + this.timeBonus + this.efficiencyBonus) >= perfectScore + 900) {
|
||||
achievements.push({
|
||||
id: 'perfect_score',
|
||||
name: '🎯 Score Parfait',
|
||||
icon: '🎯',
|
||||
description: 'Score quasi-maximal!'
|
||||
});
|
||||
}
|
||||
|
||||
// 🏃 Rapidité respectable
|
||||
if (timeSeconds < 60 && pairesTotal === 9) {
|
||||
achievements.push({
|
||||
id: 'fast_completion',
|
||||
name: '🏃 Très Rapide',
|
||||
icon: '🏃',
|
||||
description: 'Moins d\'une minute!'
|
||||
});
|
||||
}
|
||||
|
||||
return achievements;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Manager pour le localStorage et persistance
|
||||
*/
|
||||
class StorageManager {
|
||||
static setItem(key, value, isSession = false) {
|
||||
try {
|
||||
const storage = isSession ? sessionStorage : localStorage;
|
||||
storage.setItem(key, JSON.stringify(value));
|
||||
return true;
|
||||
} catch (e) {
|
||||
console.error('Storage error:', e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static getItem(key, isSession = false) {
|
||||
try {
|
||||
const storage = isSession ? sessionStorage : localStorage;
|
||||
const item = storage.getItem(key);
|
||||
return item ? JSON.parse(item) : null;
|
||||
} catch (e) {
|
||||
console.error('Storage error:', e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static removeItem(key, isSession = false) {
|
||||
try {
|
||||
const storage = isSession ? sessionStorage : localStorage;
|
||||
storage.removeItem(key);
|
||||
return true;
|
||||
} catch (e) {
|
||||
console.error('Storage error:', e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
static clear(isSession = false) {
|
||||
try {
|
||||
const storage = isSession ? sessionStorage : localStorage;
|
||||
storage.clear();
|
||||
return true;
|
||||
} catch (e) {
|
||||
console.error('Storage error:', e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Session state - données temporaires du jeu actuel
|
||||
*/
|
||||
class GameSessionState {
|
||||
constructor() {
|
||||
this.sessionId = generateUUID();
|
||||
this.userId = getUserId();
|
||||
this.playerName = getPlayerName();
|
||||
this.startTime = null;
|
||||
this.endTime = null;
|
||||
this.difficulty = 'normal';
|
||||
this.moves = 0;
|
||||
this.score = 0;
|
||||
this.matched = 0;
|
||||
this.isPaused = false;
|
||||
this.gameActive = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Démarrer une nouvelle session
|
||||
*/
|
||||
startSession(difficulty) {
|
||||
this.sessionId = generateUUID();
|
||||
this.startTime = Date.now();
|
||||
this.difficulty = difficulty;
|
||||
this.moves = 0;
|
||||
this.score = 0;
|
||||
this.matched = 0;
|
||||
this.gameActive = true;
|
||||
this.isPaused = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Terminer la session
|
||||
*/
|
||||
endSession() {
|
||||
this.endTime = Date.now();
|
||||
this.gameActive = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtenir la durée en secondes
|
||||
*/
|
||||
getDuration() {
|
||||
const end = this.endTime || Date.now();
|
||||
return Math.floor((end - this.startTime) / 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sérialiser pour transmission
|
||||
*/
|
||||
toJSON() {
|
||||
return {
|
||||
sessionId: this.sessionId,
|
||||
userId: this.userId,
|
||||
playerName: this.playerName,
|
||||
startTime: this.startTime,
|
||||
endTime: this.endTime,
|
||||
difficulty: this.difficulty,
|
||||
moves: this.moves,
|
||||
score: this.score,
|
||||
matched: this.matched,
|
||||
duration: this.getDuration()
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gestionnaire des notifications
|
||||
*/
|
||||
class NotificationManager {
|
||||
static show(message, type = 'info', duration = 3000) {
|
||||
// Créer la notification
|
||||
const notification = document.createElement('div');
|
||||
notification.className = `notification notification-${type}`;
|
||||
notification.textContent = message;
|
||||
notification.style.cssText = `
|
||||
position: fixed;
|
||||
bottom: 20px;
|
||||
right: 20px;
|
||||
background: ${this.getTypeColor(type)};
|
||||
color: white;
|
||||
padding: 16px 24px;
|
||||
border-radius: 8px;
|
||||
font-family: 'Syne', sans-serif;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
z-index: 3000;
|
||||
animation: slideUp 0.3s ease-out;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
|
||||
`;
|
||||
|
||||
document.body.appendChild(notification);
|
||||
|
||||
// Auto-remove après durée
|
||||
setTimeout(() => {
|
||||
notification.style.animation = 'fadeOut 0.3s ease-out';
|
||||
setTimeout(() => notification.remove(), 300);
|
||||
}, duration);
|
||||
}
|
||||
|
||||
static success(message) {
|
||||
this.show(message, 'success');
|
||||
}
|
||||
|
||||
static error(message) {
|
||||
this.show(message, 'error');
|
||||
}
|
||||
|
||||
static warning(message) {
|
||||
this.show(message, 'warning');
|
||||
}
|
||||
|
||||
static info(message) {
|
||||
this.show(message, 'info');
|
||||
}
|
||||
|
||||
static getTypeColor(type) {
|
||||
const colors = {
|
||||
success: '#4CAF50',
|
||||
error: '#F44336',
|
||||
warning: '#FF9800',
|
||||
info: '#2196F3'
|
||||
};
|
||||
return colors[type] || colors.info;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gestionnaire des préférences utilisateur
|
||||
*/
|
||||
class PreferencesManager {
|
||||
static KEY_PREFERENCES = 'nextgn_preferences';
|
||||
|
||||
static defaults = {
|
||||
soundEnabled: true,
|
||||
animationsEnabled: true,
|
||||
darkMode: false,
|
||||
showStats: true,
|
||||
notifications: true
|
||||
};
|
||||
|
||||
static get() {
|
||||
const saved = localStorage.getItem(this.KEY_PREFERENCES);
|
||||
return saved ? JSON.parse(saved) : this.defaults;
|
||||
}
|
||||
|
||||
static set(preferences) {
|
||||
localStorage.setItem(this.KEY_PREFERENCES, JSON.stringify(preferences));
|
||||
this.applyPreferences(preferences);
|
||||
}
|
||||
|
||||
static update(key, value) {
|
||||
const prefs = this.get();
|
||||
prefs[key] = value;
|
||||
this.set(prefs);
|
||||
}
|
||||
|
||||
static applyPreferences(prefs) {
|
||||
// Appliquer le dark mode
|
||||
if (prefs.darkMode) {
|
||||
document.body.style.colorScheme = 'dark';
|
||||
} else {
|
||||
document.body.style.colorScheme = 'light';
|
||||
}
|
||||
|
||||
// Désactiver les animations si demandé
|
||||
if (!prefs.animationsEnabled) {
|
||||
document.documentElement.style.setProperty('--animation-duration', '0ms');
|
||||
}
|
||||
}
|
||||
|
||||
static toggle(key) {
|
||||
const prefs = this.get();
|
||||
prefs[key] = !prefs[key];
|
||||
this.set(prefs);
|
||||
return prefs[key];
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// INITIALISATION DES SINGLETONS
|
||||
// ============================================
|
||||
|
||||
// Créer une instance de session au chargement
|
||||
const gameSession = new GameSessionState();
|
||||
|
||||
// Appliquer les préférences utilisateur
|
||||
PreferencesManager.applyPreferences(PreferencesManager.get());
|
||||
|
||||
// Exporter pour utilisation globale
|
||||
window.ScoringEngine = ScoringEngine;
|
||||
window.StorageManager = StorageManager;
|
||||
window.GameSessionState = GameSessionState;
|
||||
window.NotificationManager = NotificationManager;
|
||||
window.PreferencesManager = PreferencesManager;
|
||||
389
exercices/memory-pictogrammes/assets/js/leaderboard.js
Normal file
389
exercices/memory-pictogrammes/assets/js/leaderboard.js
Normal file
@@ -0,0 +1,389 @@
|
||||
/* ============================================
|
||||
LEADERBOARD & PLAYER STATISTICS
|
||||
============================================ */
|
||||
|
||||
/**
|
||||
* Manager du classement
|
||||
*/
|
||||
class LeaderboardManager {
|
||||
static KEY_LEADERBOARD = 'nextgn_leaderboard';
|
||||
static MAX_SCORES = 100;
|
||||
|
||||
/**
|
||||
* Ajouter un score au classement
|
||||
*/
|
||||
static addScore(gameData) {
|
||||
const scores = this.getAllScores();
|
||||
|
||||
const newScore = {
|
||||
sessionId: generateUUID(),
|
||||
playerName: getPlayerName(),
|
||||
userId: getUserId(),
|
||||
score: gameData.score,
|
||||
moves: gameData.moves,
|
||||
timeSeconds: gameData.duration,
|
||||
difficulty: gameData.difficulty,
|
||||
date: new Date().toISOString(),
|
||||
isPerfect: gameData.moves === DIFFICULTY_MODES[gameData.difficulty].paires,
|
||||
won: gameData.won !== false
|
||||
};
|
||||
|
||||
scores.push(newScore);
|
||||
|
||||
// Limiter à MAX_SCORES (garder les plus récents)
|
||||
if (scores.length > this.MAX_SCORES) {
|
||||
scores.sort((a, b) => new Date(b.date) - new Date(a.date));
|
||||
scores.splice(this.MAX_SCORES);
|
||||
}
|
||||
|
||||
localStorage.setItem(this.KEY_LEADERBOARD, JSON.stringify(scores));
|
||||
|
||||
DEBUG.log('Score added:', newScore);
|
||||
|
||||
return newScore;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtenir tous les scores
|
||||
*/
|
||||
static getAllScores() {
|
||||
try {
|
||||
const scores = JSON.parse(localStorage.getItem(this.KEY_LEADERBOARD)) || [];
|
||||
return scores;
|
||||
} catch (e) {
|
||||
console.error('Leaderboard error:', e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtenir le classement (top X)
|
||||
*/
|
||||
static getLeaderboard(difficulty = 'all', limit = 10) {
|
||||
let scores = this.getAllScores();
|
||||
|
||||
// Filtrer par difficulté
|
||||
if (difficulty !== 'all') {
|
||||
scores = scores.filter(s => s.difficulty === difficulty);
|
||||
}
|
||||
|
||||
// Trier par score (décroissant)
|
||||
scores.sort((a, b) => {
|
||||
if (b.score !== a.score) {
|
||||
return b.score - a.score;
|
||||
}
|
||||
// En cas d'égalité, par temps
|
||||
return a.timeSeconds - b.timeSeconds;
|
||||
});
|
||||
|
||||
return scores.slice(0, limit);
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtenir les stats d'un joueur
|
||||
*/
|
||||
static getPlayerStats(userId) {
|
||||
const scores = this.getAllScores().filter(s => s.userId === userId);
|
||||
|
||||
if (scores.length === 0) {
|
||||
return {
|
||||
totalGames: 0,
|
||||
bestScore: 0,
|
||||
averageScore: 0,
|
||||
averageTime: 0,
|
||||
bestTime: Infinity,
|
||||
winRate: 0,
|
||||
perfectGames: 0
|
||||
};
|
||||
}
|
||||
|
||||
const bestScore = Math.max(...scores.map(s => s.score), 0);
|
||||
const totalScore = scores.reduce((a, b) => a + b.score, 0);
|
||||
const totalTime = scores.reduce((a, b) => a + b.timeSeconds, 0);
|
||||
const bestTime = Math.min(...scores.map(s => s.timeSeconds), Infinity);
|
||||
const perfectGames = scores.filter(s => s.isPerfect).length;
|
||||
const winRate = (perfectGames / scores.length) * 100;
|
||||
|
||||
return {
|
||||
totalGames: scores.length,
|
||||
bestScore: bestScore,
|
||||
averageScore: Math.round(totalScore / scores.length),
|
||||
averageTime: Math.round(totalTime / scores.length),
|
||||
bestTime: bestTime === Infinity ? 0 : bestTime,
|
||||
winRate: Math.round(winRate),
|
||||
perfectGames: perfectGames
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtenir le rang d'un score
|
||||
*/
|
||||
static getPlayerRank(userId, difficulty = 'all') {
|
||||
const leaderboard = this.getLeaderboard(difficulty, Infinity);
|
||||
const rank = leaderboard.findIndex(s => s.userId === userId) + 1;
|
||||
return rank > 0 ? rank : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifier si c'est un nouveau record personnel
|
||||
*/
|
||||
static isPersonalRecord(userId, newScore) {
|
||||
const stats = this.getPlayerStats(userId);
|
||||
return newScore > stats.bestScore;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtenir les statistiques globales
|
||||
*/
|
||||
static getGlobalStats() {
|
||||
const scores = this.getAllScores();
|
||||
|
||||
if (scores.length === 0) {
|
||||
return {
|
||||
totalGames: 0,
|
||||
totalPlayers: 0,
|
||||
averageScore: 0,
|
||||
highestScore: 0,
|
||||
fastestCompletion: Infinity
|
||||
};
|
||||
}
|
||||
|
||||
const uniquePlayers = new Set(scores.map(s => s.userId));
|
||||
const totalScore = scores.reduce((a, b) => a + b.score, 0);
|
||||
const highestScore = Math.max(...scores.map(s => s.score), 0);
|
||||
const fastestCompletion = Math.min(...scores.map(s => s.timeSeconds), Infinity);
|
||||
|
||||
return {
|
||||
totalGames: scores.length,
|
||||
totalPlayers: uniquePlayers.size,
|
||||
averageScore: Math.round(totalScore / scores.length),
|
||||
highestScore: highestScore,
|
||||
fastestCompletion: fastestCompletion === Infinity ? 0 : fastestCompletion
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Mettre à jour l'affichage du classement
|
||||
*/
|
||||
static updateDisplay(difficulty = 'all') {
|
||||
const leaderboard = this.getLeaderboard(difficulty, 10);
|
||||
const leaderboardList = document.getElementById('leaderboard-list');
|
||||
|
||||
if (!leaderboardList) return;
|
||||
|
||||
if (leaderboard.length === 0) {
|
||||
leaderboardList.innerHTML = `
|
||||
<div class="empty-state">
|
||||
<div class="empty-state-icon">🎮</div>
|
||||
<div class="empty-state-text">Aucun score pour le moment</div>
|
||||
<div class="empty-state-hint">Jouez une partie pour apparaître au classement!</div>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
leaderboardList.innerHTML = '';
|
||||
|
||||
leaderboard.forEach((score, index) => {
|
||||
const rankItem = document.createElement('div');
|
||||
rankItem.className = 'rank-item';
|
||||
|
||||
const rankNumber = this.getRankDisplay(index);
|
||||
const medal = index < 3 ? `class="rank-number medal-${index + 1}"` : 'class="rank-number"';
|
||||
|
||||
rankItem.innerHTML = `
|
||||
<div ${medal}>${rankNumber}</div>
|
||||
<div class="rank-info">
|
||||
<div class="player-name">${this.escapeHTML(score.playerName)}</div>
|
||||
<div class="player-stats">
|
||||
<span>⏱ ${formatTime(score.timeSeconds)}</span>
|
||||
<span>🎯 ${score.moves} mouvements</span>
|
||||
${score.isPerfect ? '<span>✨ Parfait</span>' : ''}
|
||||
</div>
|
||||
</div>
|
||||
<div class="rank-score">${formatNumber(score.score)}</div>
|
||||
<div class="rank-difficulty ${score.difficulty}">${DIFFICULTY_MODES[score.difficulty].name}</div>
|
||||
`;
|
||||
|
||||
leaderboardList.appendChild(rankItem);
|
||||
});
|
||||
|
||||
analyticsManager.track('leaderboard_viewed', { filter: difficulty });
|
||||
}
|
||||
|
||||
/**
|
||||
* Mettre à jour les statistiques du joueur
|
||||
*/
|
||||
static updatePlayerStats() {
|
||||
const userId = getUserId();
|
||||
const stats = this.getPlayerStats(userId);
|
||||
|
||||
// Remplir les éléments HTML
|
||||
document.getElementById('total-games').textContent = stats.totalGames;
|
||||
document.getElementById('best-score').textContent = formatNumber(stats.bestScore);
|
||||
document.getElementById('best-time').textContent = stats.bestTime === Infinity ? '--' : formatTime(stats.bestTime);
|
||||
document.getElementById('win-rate').textContent = `${stats.winRate}%`;
|
||||
|
||||
// Ajouter des classes pour animation si valeurs élevées
|
||||
if (stats.bestScore > 5000) {
|
||||
document.getElementById('best-score').parentElement.classList.add('high-value');
|
||||
}
|
||||
|
||||
if (stats.winRate >= 50) {
|
||||
document.getElementById('win-rate').parentElement.classList.add('high-value');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Afficher le rang du joueur
|
||||
*/
|
||||
static updatePlayerRank(difficulty = 'all') {
|
||||
const userId = getUserId();
|
||||
const rank = this.getPlayerRank(userId, difficulty);
|
||||
|
||||
if (rank) {
|
||||
const rankDisplay = document.getElementById('player-rank');
|
||||
if (rankDisplay) {
|
||||
rankDisplay.textContent = `Vous êtes #{rank}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Afficher les statistiques globales
|
||||
*/
|
||||
static displayGlobalStats() {
|
||||
const globalStats = this.getGlobalStats();
|
||||
DEBUG.log('Global Statistics:', globalStats);
|
||||
|
||||
return globalStats;
|
||||
}
|
||||
|
||||
/**
|
||||
* Nettoyer les scores (DEBUG)
|
||||
*/
|
||||
static clearAll() {
|
||||
if (confirm('Êtes-vous ABSOLUMENT certain de vouloir supprimer TOUS les scores?')) {
|
||||
localStorage.removeItem(this.KEY_LEADERBOARD);
|
||||
this.updateDisplay();
|
||||
this.updatePlayerStats();
|
||||
DEBUG.log('✓ Tous les scores ont été supprimés');
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Exporter les scores en CSV
|
||||
*/
|
||||
static exportCSV() {
|
||||
const scores = this.getAllScores();
|
||||
|
||||
let csv = 'Rang,Joueur,Score,Difficulté,Temps (s),Mouvements,Parfait,Date\n';
|
||||
|
||||
scores.forEach((score, index) => {
|
||||
csv += `${index + 1},"${score.playerName}",${score.score},"${score.difficulty}",${score.timeSeconds},${score.moves},${score.isPerfect ? 'Oui' : 'Non'},"${score.date}"\n`;
|
||||
});
|
||||
|
||||
const blob = new Blob([csv], { type: 'text/csv' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = `leaderboard-${new Date().toISOString().slice(0, 10)}.csv`;
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtenir l'affichage du rang (numéro ou médaille)
|
||||
*/
|
||||
static getRankDisplay(index) {
|
||||
const medals = ['🥇', '🥈', '🥉'];
|
||||
return medals[index] || `${index + 1}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Échapper le HTML (sécurité)
|
||||
*/
|
||||
static escapeHTML(str) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = str;
|
||||
return div.innerHTML;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Statistiques avancées
|
||||
*/
|
||||
class AdvancedStats {
|
||||
/**
|
||||
* Obtenir la distribution des scores par difficulté
|
||||
*/
|
||||
static getDistributionByDifficulty() {
|
||||
const scores = LeaderboardManager.getAllScores();
|
||||
const distribution = {};
|
||||
|
||||
Object.keys(DIFFICULTY_MODES).forEach(difficulty => {
|
||||
distribution[difficulty] = scores.filter(s => s.difficulty === difficulty).length;
|
||||
});
|
||||
|
||||
return distribution;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtenir la tendance temporelle
|
||||
*/
|
||||
static getTimelineTrend(days = 7) {
|
||||
const scores = LeaderboardManager.getAllScores();
|
||||
const now = new Date();
|
||||
const timeline = {};
|
||||
|
||||
for (let i = 0; i < days; i++) {
|
||||
const date = new Date(now);
|
||||
date.setDate(date.getDate() - i);
|
||||
const dateStr = date.toISOString().slice(0, 10);
|
||||
timeline[dateStr] = scores.filter(s => s.date.slice(0, 10) === dateStr).length;
|
||||
}
|
||||
|
||||
return timeline;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtenir la moyenne de temps par difficulté
|
||||
*/
|
||||
static getAverageTimeByDifficulty() {
|
||||
const scores = LeaderboardManager.getAllScores();
|
||||
const averages = {};
|
||||
|
||||
Object.keys(DIFFICULTY_MODES).forEach(difficulty => {
|
||||
const diffScores = scores.filter(s => s.difficulty === difficulty);
|
||||
if (diffScores.length > 0) {
|
||||
const totalTime = diffScores.reduce((a, b) => a + b.timeSeconds, 0);
|
||||
averages[difficulty] = Math.round(totalTime / diffScores.length);
|
||||
}
|
||||
});
|
||||
|
||||
return averages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Taux de réussite global
|
||||
*/
|
||||
static getGlobalSuccessRate() {
|
||||
const scores = LeaderboardManager.getAllScores();
|
||||
if (scores.length === 0) return 0;
|
||||
|
||||
const perfectGames = scores.filter(s => s.isPerfect).length;
|
||||
return Math.round((perfectGames / scores.length) * 100);
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// INITIALISATION
|
||||
// ============================================
|
||||
|
||||
// Exporter pour utilisation globale
|
||||
window.LeaderboardManager = LeaderboardManager;
|
||||
window.AdvancedStats = AdvancedStats;
|
||||
|
||||
DEBUG.log('Leaderboard Manager initialized');
|
||||
527
exercices/memory-pictogrammes/assets/js/memory-game.js
Normal file
527
exercices/memory-pictogrammes/assets/js/memory-game.js
Normal file
@@ -0,0 +1,527 @@
|
||||
/* ============================================
|
||||
MEMORY PICTOGRAMMES - GAME ENGINE
|
||||
Logique principale du jeu
|
||||
============================================ */
|
||||
|
||||
class MemoryGameEngine {
|
||||
constructor(difficulty = 'normal') {
|
||||
this.difficulty = difficulty;
|
||||
this.mode = DIFFICULTY_MODES[difficulty];
|
||||
this.cards = [];
|
||||
this.gameState = {
|
||||
flipped: [],
|
||||
matched: 0,
|
||||
moves: 0,
|
||||
score: 0,
|
||||
isProcessing: false,
|
||||
isPaused: false,
|
||||
gameStarted: false
|
||||
};
|
||||
this.startTime = null;
|
||||
this.timerInterval = null;
|
||||
this.scoreEngine = new ScoringEngine();
|
||||
this.analytics = new AnalyticsManager();
|
||||
|
||||
this.init();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialiser le jeu
|
||||
*/
|
||||
init() {
|
||||
this.cards = this.initializeCards();
|
||||
this.renderCards();
|
||||
this.setupEventListeners();
|
||||
this.updateHUD();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialiser le deck de cartes
|
||||
*/
|
||||
initializeCards() {
|
||||
const selectedPictogrammes = PICTOGRAMMES.slice(0, this.mode.paires);
|
||||
const pairs = [];
|
||||
|
||||
// Créer paires (image + texte pour chaque pictogramme)
|
||||
selectedPictogrammes.forEach(pic => {
|
||||
pairs.push({
|
||||
type: 'image',
|
||||
data: pic,
|
||||
id: pic.id,
|
||||
pairId: `${pic.id}-img`
|
||||
});
|
||||
pairs.push({
|
||||
type: 'text',
|
||||
data: pic,
|
||||
id: pic.id,
|
||||
pairId: `${pic.id}-txt`
|
||||
});
|
||||
});
|
||||
|
||||
// Mélanger les cartes
|
||||
return this.shuffle(pairs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Algorithme de shuffling (Fisher-Yates)
|
||||
*/
|
||||
shuffle(array) {
|
||||
const shuffled = [...array];
|
||||
for (let i = shuffled.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(Math.random() * (i + 1));
|
||||
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
|
||||
}
|
||||
return shuffled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rendre les cartes en HTML
|
||||
*/
|
||||
renderCards() {
|
||||
const gameGrid = document.getElementById('game-grid');
|
||||
gameGrid.innerHTML = '';
|
||||
|
||||
this.cards.forEach((card, index) => {
|
||||
const cardElement = document.createElement('div');
|
||||
cardElement.className = 'memory-card';
|
||||
cardElement.setAttribute('data-card-index', index);
|
||||
|
||||
// Face avant (couverture)
|
||||
const frontFace = document.createElement('div');
|
||||
frontFace.className = 'card-face front';
|
||||
frontFace.textContent = '?';
|
||||
|
||||
// Face arrière (contenu)
|
||||
const backFace = document.createElement('div');
|
||||
backFace.className = 'card-face back';
|
||||
|
||||
if (card.type === 'image') {
|
||||
const img = document.createElement('img');
|
||||
img.src = `assets/pictogrammes/${card.data.filename}`;
|
||||
img.alt = card.data.nom;
|
||||
backFace.appendChild(img);
|
||||
} else {
|
||||
const text = document.createElement('span');
|
||||
text.textContent = card.data.texte;
|
||||
backFace.appendChild(text);
|
||||
}
|
||||
|
||||
cardElement.appendChild(frontFace);
|
||||
cardElement.appendChild(backFace);
|
||||
|
||||
cardElement.addEventListener('click', () => this.onCardClicked(index));
|
||||
gameGrid.appendChild(cardElement);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Gestion du clic sur une carte
|
||||
*/
|
||||
onCardClicked(cardIndex) {
|
||||
// Démarrer le timer au premier clic
|
||||
if (!this.gameState.gameStarted) {
|
||||
this.startGame();
|
||||
}
|
||||
|
||||
// Guard clauses
|
||||
if (this.gameState.isProcessing) return;
|
||||
if (this.gameState.flipped.length === 2) return;
|
||||
if (this.cards[cardIndex].isMatched) return;
|
||||
if (this.gameState.flipped.includes(cardIndex)) return;
|
||||
if (this.gameState.isPaused) return;
|
||||
|
||||
// Retourner la carte
|
||||
this.flipCard(cardIndex);
|
||||
this.gameState.flipped.push(cardIndex);
|
||||
|
||||
// Analytics
|
||||
this.analytics.trackFlip(cardIndex, this.gameState.moves);
|
||||
|
||||
// Vérifier si 2 cartes retournées
|
||||
if (this.gameState.flipped.length === 2) {
|
||||
this.gameState.isProcessing = true;
|
||||
this.gameState.moves++;
|
||||
this.updateHUD();
|
||||
|
||||
// Délai pour visualiser les 2 cartes
|
||||
setTimeout(() => this.checkMatch(), 1200);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retourner une carte (animation)
|
||||
*/
|
||||
flipCard(index) {
|
||||
const cardElement = document.querySelector(`[data-card-index="${index}"]`);
|
||||
cardElement.classList.add('flipped');
|
||||
}
|
||||
|
||||
/**
|
||||
* Retourner une carte (inverse l'animation)
|
||||
*/
|
||||
unflipCard(index) {
|
||||
const cardElement = document.querySelector(`[data-card-index="${index}"]`);
|
||||
cardElement.classList.remove('flipped');
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifier si les 2 cartes retournées correspondent
|
||||
*/
|
||||
checkMatch() {
|
||||
const [idx1, idx2] = this.gameState.flipped;
|
||||
const card1 = this.cards[idx1];
|
||||
const card2 = this.cards[idx2];
|
||||
|
||||
if (card1.id === card2.id) {
|
||||
this.onMatchSuccess(idx1, idx2);
|
||||
} else {
|
||||
this.onMatchFailure(idx1, idx2);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Paire correctement matchée
|
||||
*/
|
||||
onMatchSuccess(idx1, idx2) {
|
||||
const card1Element = document.querySelector(`[data-card-index="${idx1}"]`);
|
||||
const card2Element = document.querySelector(`[data-card-index="${idx2}"]`);
|
||||
|
||||
// Marquer comme matched
|
||||
this.cards[idx1].isMatched = true;
|
||||
this.cards[idx2].isMatched = true;
|
||||
card1Element.classList.add('matched');
|
||||
card2Element.classList.add('matched');
|
||||
|
||||
this.gameState.matched++;
|
||||
|
||||
// Augmenter score
|
||||
const points = 100 + (50 * this.mode.scoreMultiplier);
|
||||
this.gameState.score += points;
|
||||
|
||||
// Analytics
|
||||
this.analytics.trackMatch(
|
||||
this.cards[idx1].id,
|
||||
this.gameState.matched,
|
||||
this.gameState.moves
|
||||
);
|
||||
|
||||
// Mettre à jour UI
|
||||
this.updateHUD();
|
||||
|
||||
// Ajouter pulse à la barre de progression
|
||||
const progressContainer = document.querySelector('.progress-container');
|
||||
progressContainer.classList.add('pulse');
|
||||
setTimeout(() => progressContainer.classList.remove('pulse'), 600);
|
||||
|
||||
// Vérifier victoire
|
||||
if (this.gameState.matched === this.mode.paires) {
|
||||
setTimeout(() => this.endGame(true), 600);
|
||||
} else {
|
||||
// Reset pour prochaine tentative
|
||||
this.gameState.flipped = [];
|
||||
this.gameState.isProcessing = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Paire incorrecte
|
||||
*/
|
||||
onMatchFailure(idx1, idx2) {
|
||||
const card1Element = document.querySelector(`[data-card-index="${idx1}"]`);
|
||||
const card2Element = document.querySelector(`[data-card-index="${idx2}"]`);
|
||||
|
||||
// Animation shake
|
||||
card1Element.classList.add('error');
|
||||
card2Element.classList.add('error');
|
||||
|
||||
// Analytics
|
||||
this.analytics.trackMismatch(
|
||||
this.cards[idx1].id,
|
||||
this.cards[idx2].id,
|
||||
this.gameState.moves
|
||||
);
|
||||
|
||||
// Retourner après délai
|
||||
setTimeout(() => {
|
||||
this.unflipCard(idx1);
|
||||
this.unflipCard(idx2);
|
||||
card1Element.classList.remove('error');
|
||||
card2Element.classList.remove('error');
|
||||
this.gameState.flipped = [];
|
||||
this.gameState.isProcessing = false;
|
||||
}, 1200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Démarrer le timer du jeu
|
||||
*/
|
||||
startGame() {
|
||||
this.gameState.gameStarted = true;
|
||||
this.startTime = Date.now();
|
||||
|
||||
this.timerInterval = setInterval(() => {
|
||||
if (!this.gameState.isPaused) {
|
||||
this.updateTimer();
|
||||
}
|
||||
}, 100);
|
||||
|
||||
this.analytics.trackGameStart(this.difficulty);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mettre à jour le timer
|
||||
*/
|
||||
updateTimer() {
|
||||
const elapsed = Math.floor((Date.now() - this.startTime) / 1000);
|
||||
const minutes = Math.floor(elapsed / 60);
|
||||
const seconds = elapsed % 60;
|
||||
|
||||
const timerDisplay = document.getElementById('timer-display');
|
||||
timerDisplay.textContent = `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
|
||||
|
||||
// Animation warning si peu de temps reste
|
||||
if (this.mode.timeLimit && elapsed >= this.mode.timeLimit * 0.8) {
|
||||
timerDisplay.style.color = '#FF9800';
|
||||
timerDisplay.style.animation = 'timerWarning 0.5s infinite';
|
||||
}
|
||||
|
||||
// Game over si temps limite dépassé
|
||||
if (this.mode.timeLimit && elapsed >= this.mode.timeLimit) {
|
||||
this.endGame(false);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mettre à jour le HUD
|
||||
*/
|
||||
updateHUD() {
|
||||
// Score
|
||||
document.getElementById('score-display').textContent = this.gameState.score;
|
||||
|
||||
// Mouvements
|
||||
document.getElementById('moves-display').textContent = this.gameState.moves;
|
||||
|
||||
// Paires trouvées
|
||||
document.getElementById('pairs-display').textContent = `${this.gameState.matched}/${this.mode.paires}`;
|
||||
|
||||
// Barre de progression
|
||||
const progress = (this.gameState.matched / this.mode.paires) * 100;
|
||||
document.getElementById('progress-bar').style.width = `${progress}%`;
|
||||
|
||||
// Modifier le scroll progress bar en haut
|
||||
const scrollProgress = (window.scrollY / (document.body.scrollHeight - window.innerHeight)) * 100;
|
||||
document.getElementById('progress-fill').style.width = `${Math.min(scrollProgress, 100)}%`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fin du jeu
|
||||
*/
|
||||
endGame(isWon) {
|
||||
clearInterval(this.timerInterval);
|
||||
|
||||
const endTime = Date.now();
|
||||
const gameData = {
|
||||
duration: Math.floor((endTime - this.startTime) / 1000),
|
||||
moves: this.gameState.moves,
|
||||
score: this.gameState.score,
|
||||
difficulty: this.difficulty,
|
||||
won: isWon
|
||||
};
|
||||
|
||||
// Calculer score final avec bonus
|
||||
const finalScore = this.scoreEngine.calculateFinalScore(
|
||||
gameData.moves,
|
||||
gameData.duration,
|
||||
this.mode.paires,
|
||||
this.difficulty
|
||||
);
|
||||
|
||||
// Détecter achievements
|
||||
const achievements = this.scoreEngine.detectAchievements(
|
||||
gameData.moves,
|
||||
gameData.duration,
|
||||
this.mode.paires,
|
||||
this.difficulty
|
||||
);
|
||||
|
||||
// Analytics
|
||||
this.analytics.trackGameEnd({
|
||||
...gameData,
|
||||
finalScore: finalScore.totalScore,
|
||||
achievements: achievements.map(a => a.id)
|
||||
});
|
||||
|
||||
// Sauvegarder score
|
||||
LeaderboardManager.addScore({
|
||||
...gameData,
|
||||
score: finalScore.totalScore
|
||||
});
|
||||
|
||||
// Afficher modal victoire
|
||||
this.showVictoryModal(finalScore, achievements, isWon);
|
||||
}
|
||||
|
||||
/**
|
||||
* Afficher la modal de victoire
|
||||
*/
|
||||
showVictoryModal(finalScore, achievements, isWon) {
|
||||
const modal = document.getElementById('victory-modal');
|
||||
const minutes = Math.floor(this.gameState.score / 60);
|
||||
const seconds = this.gameState.score % 60;
|
||||
|
||||
// Remplir les données
|
||||
document.getElementById('victory-title').textContent = isWon ? 'Bravo! 🎉' : 'Temps écoulé! ⏰';
|
||||
document.getElementById('final-score').textContent = finalScore.totalScore;
|
||||
document.getElementById('modal-moves').textContent = this.gameState.moves;
|
||||
document.getElementById('modal-time').textContent = `${String(Math.floor(finalScore.duration / 60)).padStart(2, '0')}:${String(finalScore.duration % 60).padStart(2, '0')}`;
|
||||
document.getElementById('modal-difficulty').textContent = this.mode.name;
|
||||
document.getElementById('modal-bonus').textContent = `+${finalScore.timeBonus}`;
|
||||
|
||||
// Achievements
|
||||
const achievementsList = document.getElementById('achievements-list');
|
||||
achievementsList.innerHTML = '';
|
||||
|
||||
if (achievements.length > 0) {
|
||||
const title = document.createElement('div');
|
||||
title.style.fontSize = '14px';
|
||||
title.style.fontWeight = '600';
|
||||
title.style.marginBottom = '12px';
|
||||
title.textContent = '🏅 Achievements Débloqués';
|
||||
achievementsList.appendChild(title);
|
||||
|
||||
achievements.forEach((ach, index) => {
|
||||
const achievementEl = document.createElement('div');
|
||||
achievementEl.className = 'achievement';
|
||||
achievementEl.style.animationDelay = `${(index * 0.1)}s`;
|
||||
achievementEl.innerHTML = `
|
||||
<div class="achievement-icon">${ach.icon}</div>
|
||||
<div class="achievement-text">
|
||||
<div class="achievement-name">${ach.name}</div>
|
||||
<div class="achievement-desc">${ach.description}</div>
|
||||
</div>
|
||||
`;
|
||||
achievementsList.appendChild(achievementEl);
|
||||
});
|
||||
}
|
||||
|
||||
// Boutons d'action
|
||||
document.getElementById('play-again-btn').onclick = () => this.restart();
|
||||
document.getElementById('view-leaderboard-btn').onclick = () => {
|
||||
modal.classList.add('hidden');
|
||||
document.querySelector('.leaderboard-section').scrollIntoView({ behavior: 'smooth' });
|
||||
};
|
||||
|
||||
// Afficher modal
|
||||
modal.classList.remove('hidden');
|
||||
}
|
||||
|
||||
/**
|
||||
* Redémarrer le jeu
|
||||
*/
|
||||
restart() {
|
||||
document.getElementById('victory-modal').classList.add('hidden');
|
||||
clearInterval(this.timerInterval);
|
||||
|
||||
// Réinitialiser l'état
|
||||
this.gameState = {
|
||||
flipped: [],
|
||||
matched: 0,
|
||||
moves: 0,
|
||||
score: 0,
|
||||
isProcessing: false,
|
||||
isPaused: false,
|
||||
gameStarted: false
|
||||
};
|
||||
|
||||
// Réinitialiser les cartes
|
||||
this.cards = this.initializeCards();
|
||||
this.renderCards();
|
||||
this.updateHUD();
|
||||
|
||||
// Reset timer display
|
||||
document.getElementById('timer-display').textContent = '00:00';
|
||||
document.getElementById('timer-display').style.color = '';
|
||||
document.getElementById('timer-display').style.animation = '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Pause/Reprise
|
||||
*/
|
||||
togglePause() {
|
||||
if (!this.gameState.gameStarted) return;
|
||||
|
||||
this.gameState.isPaused = !this.gameState.isPaused;
|
||||
const pauseBtn = document.getElementById('pause-btn');
|
||||
|
||||
if (this.gameState.isPaused) {
|
||||
pauseBtn.textContent = '▶ Reprendre';
|
||||
pauseBtn.classList.add('paused');
|
||||
} else {
|
||||
pauseBtn.textContent = '⏸ Pause';
|
||||
pauseBtn.classList.remove('paused');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup event listeners
|
||||
*/
|
||||
setupEventListeners() {
|
||||
// Bouton restart
|
||||
document.getElementById('restart-btn').addEventListener('click', () => this.restart());
|
||||
|
||||
// Bouton pause
|
||||
document.getElementById('pause-btn').addEventListener('click', () => this.togglePause());
|
||||
|
||||
// Sélecteur de difficulté
|
||||
document.querySelectorAll('.btn-difficulty').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
const newDifficulty = btn.getAttribute('data-difficulty');
|
||||
if (newDifficulty !== this.difficulty) {
|
||||
this.difficulty = newDifficulty;
|
||||
this.mode = DIFFICULTY_MODES[newDifficulty];
|
||||
this.restart();
|
||||
|
||||
// Marquer comme actif
|
||||
document.querySelectorAll('.btn-difficulty').forEach(b => {
|
||||
b.classList.remove('active');
|
||||
});
|
||||
btn.classList.add('active');
|
||||
|
||||
this.analytics.trackDifficultyChange(newDifficulty);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Tabs du leaderboard
|
||||
document.querySelectorAll('.tab-btn').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
const filter = btn.getAttribute('data-filter');
|
||||
LeaderboardManager.updateDisplay(filter);
|
||||
|
||||
document.querySelectorAll('.tab-btn').forEach(b => {
|
||||
b.classList.remove('active');
|
||||
});
|
||||
btn.classList.add('active');
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// INITIALISATION AU CHARGEMENT
|
||||
// ============================================
|
||||
let game;
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
// Initialiser le jeu
|
||||
game = new MemoryGameEngine('normal');
|
||||
|
||||
// Afficher le leaderboard initial
|
||||
LeaderboardManager.updateDisplay('all');
|
||||
LeaderboardManager.updatePlayerStats();
|
||||
|
||||
// Scroll progress
|
||||
window.addEventListener('scroll', () => {
|
||||
game.updateHUD();
|
||||
});
|
||||
});
|
||||
404
exercices/memory-pictogrammes/assets/js/utils.js
Normal file
404
exercices/memory-pictogrammes/assets/js/utils.js
Normal file
@@ -0,0 +1,404 @@
|
||||
/* ============================================
|
||||
UTILS & CONFIGURATION
|
||||
============================================ */
|
||||
|
||||
// ============================================
|
||||
// PICTOGRAMMES DE DANGER (GHS)
|
||||
// ============================================
|
||||
const PICTOGRAMMES = [
|
||||
{
|
||||
id: 1,
|
||||
nom: "Gaz comprimé",
|
||||
filename: "1-gaz-comprime.png",
|
||||
texte: "Je suis sous pression",
|
||||
danger: "Danger physique",
|
||||
couleur: "teal"
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
nom: "Exclamation",
|
||||
filename: "2-exclamation.png",
|
||||
texte: "Je nuis gravement à la santé",
|
||||
danger: "Danger pour la santé",
|
||||
couleur: "teal"
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
nom: "Explosion",
|
||||
filename: "3-explosion.png",
|
||||
texte: "J'explose",
|
||||
danger: "Danger physique",
|
||||
couleur: "teal"
|
||||
},
|
||||
{
|
||||
id: 4,
|
||||
nom: "Crâne",
|
||||
filename: "4-crane.png",
|
||||
texte: "Je tue",
|
||||
danger: "Danger physique",
|
||||
couleur: "teal"
|
||||
},
|
||||
{
|
||||
id: 5,
|
||||
nom: "Flamme",
|
||||
filename: "5-flamme.png",
|
||||
texte: "Je flambe",
|
||||
danger: "Danger physique",
|
||||
couleur: "teal"
|
||||
},
|
||||
{
|
||||
id: 6,
|
||||
nom: "Comburant",
|
||||
filename: "6-comburant.png",
|
||||
texte: "Je fais flamber",
|
||||
danger: "Danger physique",
|
||||
couleur: "teal"
|
||||
},
|
||||
{
|
||||
id: 7,
|
||||
nom: "Environnement",
|
||||
filename: "7-environnement.png",
|
||||
texte: "Je pollue",
|
||||
danger: "Danger pour l'environnement",
|
||||
couleur: "teal"
|
||||
},
|
||||
{
|
||||
id: 8,
|
||||
nom: "Corrosion",
|
||||
filename: "8-corrosion.png",
|
||||
texte: "Je ronge",
|
||||
danger: "Danger physique",
|
||||
couleur: "teal"
|
||||
},
|
||||
{
|
||||
id: 9,
|
||||
nom: "Santé/Environnement",
|
||||
filename: "9-sante-environnement.png",
|
||||
texte: "J'altère la santé ou la couche d'ozone",
|
||||
danger: "Danger pour la santé/Environnement",
|
||||
couleur: "teal"
|
||||
}
|
||||
];
|
||||
|
||||
// ============================================
|
||||
// MODES DE DIFFICULTÉ
|
||||
// ============================================
|
||||
const DIFFICULTY_MODES = {
|
||||
easy: {
|
||||
name: "Facile",
|
||||
paires: 4,
|
||||
timeLimit: 180,
|
||||
scoreMultiplier: 1,
|
||||
description: "4 paires pour débuter",
|
||||
color: "#4CAF50"
|
||||
},
|
||||
|
||||
normal: {
|
||||
name: "Normal",
|
||||
paires: 9,
|
||||
timeLimit: 300,
|
||||
scoreMultiplier: 2,
|
||||
description: "Tous les 9 pictogrammes",
|
||||
color: "#1D9E75"
|
||||
},
|
||||
|
||||
hard: {
|
||||
name: "Difficile",
|
||||
paires: 9,
|
||||
timeLimit: 120,
|
||||
scoreMultiplier: 4,
|
||||
description: "Défi chronométré (2 min)",
|
||||
color: "#D85A30"
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================
|
||||
// ACHIEVEMENTS
|
||||
// ============================================
|
||||
const ACHIEVEMENTS = {
|
||||
perfectGame: {
|
||||
id: 'perfect_game',
|
||||
name: '🏅 Jeu Parfait',
|
||||
icon: '🏅',
|
||||
description: 'Trouvé toutes les paires sans erreur!',
|
||||
condition: (moves, pairesTotal) => moves === pairesTotal
|
||||
},
|
||||
|
||||
speedrun: {
|
||||
id: 'speedrun',
|
||||
name: '⚡ Vitesse Éclair',
|
||||
icon: '⚡',
|
||||
description: 'Complété en moins de 60 secondes!',
|
||||
condition: (moves, time, pairesTotal, difficulty) => {
|
||||
const threshold = DIFFICULTY_MODES[difficulty].timeLimit * 0.5;
|
||||
return time < threshold;
|
||||
}
|
||||
},
|
||||
|
||||
fastHard: {
|
||||
id: 'fast_hard',
|
||||
name: '🔥 Mode Difficile Maître',
|
||||
icon: '🔥',
|
||||
description: 'Complété le mode difficile!',
|
||||
condition: (moves, time, pairesTotal, difficulty) => difficulty === 'hard'
|
||||
},
|
||||
|
||||
twoMinutes: {
|
||||
id: 'two_minutes',
|
||||
name: '⏱ Contre le Chrono',
|
||||
icon: '⏱',
|
||||
description: 'Terminé avant les 2 minutes!',
|
||||
condition: (moves, time, pairesTotal, difficulty) => time < 120
|
||||
},
|
||||
|
||||
noMistakes: {
|
||||
id: 'no_mistakes',
|
||||
name: '🎯 Tir Précis',
|
||||
icon: '🎯',
|
||||
description: '0 erreur dans le mode Normal!',
|
||||
condition: (moves, time, pairesTotal, difficulty) => {
|
||||
return difficulty === 'normal' && moves === pairesTotal;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================
|
||||
// UTILITY FUNCTIONS
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Générer un UUID
|
||||
*/
|
||||
function generateUUID() {
|
||||
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
|
||||
const r = Math.random() * 16 | 0;
|
||||
const v = c === 'x' ? r : (r & 0x3 | 0x8);
|
||||
return v.toString(16);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Formater le temps en mm:ss
|
||||
*/
|
||||
function formatTime(seconds) {
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const secs = seconds % 60;
|
||||
return `${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formater un nombre avec séparateurs
|
||||
*/
|
||||
function formatNumber(num) {
|
||||
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
||||
}
|
||||
|
||||
/**
|
||||
* Ajouter une classe temporaire
|
||||
*/
|
||||
function addTemporaryClass(element, className, duration = 300) {
|
||||
element.classList.add(className);
|
||||
setTimeout(() => {
|
||||
element.classList.remove(className);
|
||||
}, duration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtenir l'ID utilisateur (avec localStorage)
|
||||
*/
|
||||
function getUserId() {
|
||||
let userId = localStorage.getItem('nextgn_userId');
|
||||
if (!userId) {
|
||||
userId = generateUUID();
|
||||
localStorage.setItem('nextgn_userId', userId);
|
||||
}
|
||||
return userId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtenir le nom du joueur
|
||||
*/
|
||||
function getPlayerName() {
|
||||
let playerName = localStorage.getItem('nextgn_playerName');
|
||||
if (!playerName) {
|
||||
playerName = 'Joueur ' + Math.floor(Math.random() * 9000 + 1000);
|
||||
localStorage.setItem('nextgn_playerName', playerName);
|
||||
}
|
||||
return playerName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Demander le nom du joueur (au premier lancement)
|
||||
*/
|
||||
function promptPlayerName() {
|
||||
const stored = localStorage.getItem('nextgn_playerName');
|
||||
if (stored) return stored;
|
||||
|
||||
const name = prompt('Quel est votre nom?', 'Joueur ' + Math.floor(Math.random() * 9000 + 1000));
|
||||
if (name) {
|
||||
localStorage.setItem('nextgn_playerName', name);
|
||||
return name;
|
||||
}
|
||||
return 'Anonyme';
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtenir la couleur d'une difficulté
|
||||
*/
|
||||
function getDifficultyColor(difficulty) {
|
||||
return DIFFICULTY_MODES[difficulty]?.color || '#1D9E75';
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtenir la couleur de badge difficulté
|
||||
*/
|
||||
function getDifficultyClass(difficulty) {
|
||||
switch(difficulty) {
|
||||
case 'easy': return 'easy';
|
||||
case 'normal': return 'normal';
|
||||
case 'hard': return 'hard';
|
||||
default: return 'normal';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Comparer deux scores
|
||||
*/
|
||||
function compareScores(a, b) {
|
||||
if (b.score !== a.score) {
|
||||
return b.score - a.score;
|
||||
}
|
||||
return a.timeSeconds - b.timeSeconds;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trier les scores par difficulty
|
||||
*/
|
||||
function sortByDifficulty(scores, difficulty) {
|
||||
if (difficulty === 'all') {
|
||||
return scores;
|
||||
}
|
||||
return scores.filter(s => s.difficulty === difficulty);
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtenir le rang d'un score
|
||||
*/
|
||||
function getRank(index) {
|
||||
if (index === 0) return '🥇';
|
||||
if (index === 1) return '🥈';
|
||||
if (index === 2) return '🥉';
|
||||
return `${index + 1}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vérifier si le score est dans le top 10
|
||||
*/
|
||||
function isTopScore(score, difficulty = 'all') {
|
||||
const scores = LeaderboardManager.getLeaderboard(difficulty, 10);
|
||||
return scores.some(s => s.score === score.score && s.userId === score.userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Formater la date d'un score
|
||||
*/
|
||||
function formatDate(isoDate) {
|
||||
const date = new Date(isoDate);
|
||||
const today = new Date();
|
||||
const yesterday = new Date(today);
|
||||
yesterday.setDate(yesterday.getDate() - 1);
|
||||
|
||||
if (date.toDateString() === today.toDateString()) {
|
||||
return 'Aujourd\'hui';
|
||||
} else if (date.toDateString() === yesterday.toDateString()) {
|
||||
return 'Hier';
|
||||
} else {
|
||||
return date.toLocaleDateString('fr-FR', { day: 'numeric', month: 'short' });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtenir les statistiques d'un joueur
|
||||
*/
|
||||
function getPlayerStatistics(userId) {
|
||||
const scores = LeaderboardManager.getAllScores().filter(s => s.userId === userId);
|
||||
|
||||
if (scores.length === 0) {
|
||||
return {
|
||||
totalGames: 0,
|
||||
bestScore: 0,
|
||||
averageScore: 0,
|
||||
averageTime: 0,
|
||||
bestTime: Infinity,
|
||||
winRate: 0,
|
||||
perfectGames: 0
|
||||
};
|
||||
}
|
||||
|
||||
const bestScore = Math.max(...scores.map(s => s.score), 0);
|
||||
const totalScore = scores.reduce((a, b) => a + b.score, 0);
|
||||
const totalTime = scores.reduce((a, b) => a + b.timeSeconds, 0);
|
||||
const bestTime = Math.min(...scores.map(s => s.timeSeconds), Infinity);
|
||||
const perfectGames = scores.filter(s => s.isPerfect).length;
|
||||
const winRate = (perfectGames / scores.length) * 100;
|
||||
|
||||
return {
|
||||
totalGames: scores.length,
|
||||
bestScore: bestScore,
|
||||
averageScore: Math.round(totalScore / scores.length),
|
||||
averageTime: Math.round(totalTime / scores.length),
|
||||
bestTime: bestTime === Infinity ? 0 : bestTime,
|
||||
winRate: Math.round(winRate),
|
||||
perfectGames: perfectGames
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Déboguer : afficher tous les scores en console
|
||||
*/
|
||||
function debugScores() {
|
||||
console.table(LeaderboardManager.getAllScores());
|
||||
}
|
||||
|
||||
/**
|
||||
* Déboguer : nettoyer tous les scores
|
||||
*/
|
||||
function clearAllScores() {
|
||||
if (confirm('Êtes-vous sûr de vouloir supprimer tous les scores?')) {
|
||||
localStorage.removeItem('nextgn_leaderboard');
|
||||
console.log('✓ Tous les scores ont été supprimés');
|
||||
location.reload();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mode développement
|
||||
*/
|
||||
const DEBUG = {
|
||||
enabled: localStorage.getItem('nextgn_debug') === 'true',
|
||||
|
||||
toggle() {
|
||||
this.enabled = !this.enabled;
|
||||
localStorage.setItem('nextgn_debug', this.enabled);
|
||||
console.log(`Debug mode: ${this.enabled ? 'ON' : 'OFF'}`);
|
||||
},
|
||||
|
||||
log(...args) {
|
||||
if (this.enabled) {
|
||||
console.log('[DEBUG]', ...args);
|
||||
}
|
||||
},
|
||||
|
||||
table(data) {
|
||||
if (this.enabled) {
|
||||
console.table(data);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Activer le debug avec Ctrl+Shift+D
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.ctrlKey && e.shiftKey && e.key === 'D') {
|
||||
DEBUG.toggle();
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user