Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
127 lines (125 loc) · 14.2 KB
/
Copy pathscript.js
File metadata and controls
127 lines (125 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
const bank = window.MATIKS_QUESTIONS || [];
const brain = window.MATIKS_BRAIN;
const analytics = window.MATIKS_ANALYTICS;
const labels = { lobby:'PLAY', matchmaking:'FIND OPPONENT', battle:'BATTLE', result:'RESULT', profile:'PROFILE', rivals:'RIVALS', leaderboard:'LEADERBOARD', daily:'DAILY MATIKS', settings:'SETTINGS' };
const views = [...document.querySelectorAll('[data-view]')];
const saved = JSON.parse(localStorage.getItem('matiks-player') || '{}');
const state = {
view: 'lobby', phase: 'LOBBY', battleId: null, questionIndex: 0, questions: [], answers: [], score: 0,
opponentScore: 0, seconds: 239, battleStartedAt: 0, questionStartedAt: 0, timer: null, queue: null,
queueSeconds: 0, rating: saved.rating || 2147, streak: saved.streak || 12,
bestStreak: saved.bestStreak || 18, history: saved.history || [],
brain: brain.createProfile(saved.brain), playerId: saved.playerId || analytics.playerId(), guest: new URLSearchParams(window.location.search).get('guest') === '1', calibration: !saved.brain?.recentForm?.length
};
function persist() {
localStorage.setItem('matiks-player', JSON.stringify({ playerId: state.playerId, rating: state.rating, streak: state.streak, bestStreak: state.bestStreak, history: state.history.slice(-20), brain: state.brain }));
}
function stopTimers() { clearInterval(state.timer); clearInterval(state.queue); state.timer = null; state.queue = null; }
function formatTime(seconds) { return `${String(Math.floor(Math.max(seconds, 0) / 60)).padStart(2, '0')}:${String(Math.max(seconds, 0) % 60).padStart(2, '0')}`; }
function show(view) {
stopTimers(); state.view = view; views.forEach((item) => item.classList.toggle('active', item.dataset.view === view));
document.querySelectorAll('.nav-item').forEach((item) => item.classList.toggle('active', item.dataset.nav === view));
const label = document.querySelector('#view-label'); if (label) label.textContent = labels[view] || view.toUpperCase();
window.scrollTo({ top: 0, behavior: 'smooth' });
}
function toast(message) { const node = document.querySelector('#toast'); if (!node) return; node.textContent = message; node.classList.add('show'); clearTimeout(toast.timer); toast.timer = setTimeout(() => node.classList.remove('show'), 2600); }
function track(event, payload = {}) { const events = JSON.parse(localStorage.getItem('matiks-events') || '[]'); events.push({ event, at: new Date().toISOString(), ...payload }); localStorage.setItem('matiks-events', JSON.stringify(events.slice(-100))); }
function randomId() { return Math.random().toString(36).slice(2, 8).toUpperCase(); }
function startMatchmaking() {
track('matchmaking_started'); show('matchmaking'); state.phase = 'SEARCHING'; state.queueSeconds = 0;
const time = document.querySelector('#queue-time'); const range = document.querySelector('#range');
state.queue = setInterval(() => {
state.queueSeconds += 1;
if (time) time.textContent = formatTime(state.queueSeconds);
if (range) range.textContent = `+/- ${brain.matchmakingRange(state.queueSeconds)}`;
if (state.queueSeconds >= 5) { stopTimers(); track('match_found'); startBattle(state.calibration ? 'calibration' : 'ranked'); }
}, 1000);
}
function startBattle(mode = 'ranked') {
state.phase = 'ACTIVE'; state.battleId = randomId(); state.questionIndex = 0; state.answers = []; state.score = 0; state.opponentScore = 0; state.seconds = 239;
if (mode === 'calibration') { track('CALIBRATION_STARTED'); toast('CALIBRATION · 5 quick questions to find your edge'); }
state.questions = brain.selectQuestions(bank, state.brain, mode === 'calibration' ? 5 : 8, Math.random, analytics.allQuestionAnalytics());
state.battleStartedAt = Date.now(); state.questionStartedAt = Date.now(); track('battle_started', { battleId: state.battleId, mode, questionCount: state.questions.length });
show('battle'); renderQuestion(); updateScores();
state.timer = setInterval(() => { state.seconds -= 1; const clock = document.querySelector('#clock'); if (clock) clock.textContent = formatTime(state.seconds); if (state.seconds <= 20) document.body.classList.add('final-seconds'); if (state.seconds <= 0) finishBattle('timeout'); }, 1000);
}
function renderQuestion() {
const question = state.questions[state.questionIndex]; if (!question) return;
analytics.recordBrainEvent('QUESTION_SHOWN', { playerId: state.playerId, battleId: state.battleId, questionId: question.id, currentEdge: state.brain.currentEdge });
const set = (selector, value) => { const node = document.querySelector(selector); if (node) node.textContent = value; };
set('#q-type', question.type.toUpperCase()); set('#q-topic', `${question.domain.toUpperCase()} / ${question.tags[0].toUpperCase()}`); set('#q-number', String(state.questionIndex + 1).padStart(2, '0')); set('#q-prompt', question.question); set('#q-code', question.code || '');
set('#progress-label', `QUESTION ${state.questionIndex + 1} / ${state.questions.length}`); const progress = document.querySelector('#progress-fill'); if (progress) progress.style.width = `${((state.questionIndex + 1) / state.questions.length) * 100}%`;
const answers = document.querySelector('#answers'); if (!answers) return;
const options = question.options || [question.correctAnswer, 'Not enough information', 'All of the above', 'None of the above'];
answers.innerHTML = options.map((answer, index) => `<button class="answer" type="button" data-answer="${index}"><b>${String.fromCharCode(65 + index)}</b>${answer}</button>`).join('');
document.querySelectorAll('[data-answer]').forEach((button) => button.addEventListener('click', () => answerQuestion(Number(button.dataset.answer))));
const feedback = document.querySelector('#answer-feedback'); if (feedback) { feedback.textContent = ''; feedback.className = 'answer-feedback'; }
}
function updateScores() { const yours = document.querySelector('#your-score'); const opponent = document.querySelector('#opp-score'); if (yours) yours.textContent = state.score; if (opponent) opponent.textContent = state.opponentScore; }
function answerQuestion(index) {
if (state.phase !== 'ACTIVE') return;
const question = state.questions[state.questionIndex]; const timeTakenMs = Date.now() - state.questionStartedAt; const options = question.options || [];
const selected = options[index]; const correct = selected === question.correctAnswer; const buttons = [...document.querySelectorAll('[data-answer]')];
buttons.forEach((button) => { button.disabled = true; if (button.textContent.slice(1) === question.correctAnswer) button.classList.add('correct'); });
if (!correct && buttons[index]) buttons[index].classList.add('wrong');
const edgeBefore = state.brain.currentEdge; const ratingBefore = state.rating;
analytics.recordBrainEvent('ANSWER_SUBMITTED', { playerId: state.playerId, battleId: state.battleId, questionId: question.id, currentEdge: state.brain.currentEdge });
const result = { questionId: question.id, selected, correct, timeTakenMs, timestamp: Date.now(), tabHidden: document.hidden };
state.answers.push(result); state.brain = brain.update(state.brain, question, result); analytics.recordBrainEvent(correct ? 'ANSWER_CORRECT' : 'ANSWER_WRONG', { playerId: state.playerId, battleId: state.battleId, questionId: question.id, currentEdgeBefore: edgeBefore, currentEdgeAfter: state.brain.currentEdge }); if (correct) state.score += 1; updateScores(); updateLobbyStats();
analytics.recordAttempt({ playerId: state.playerId, questionId: question.id, startedAt: state.questionStartedAt, answeredAt: Date.now(), responseTimeMs: timeTakenMs, correct, skipped: false, questionDifficulty: brain.levelForQuestion(question), topic: question.topic || question.domain, questionType: question.type, currentEdgeBefore: edgeBefore, currentEdgeAfter: state.brain.currentEdge, ratingBefore, ratingAfter: state.rating });
analytics.calculateQuestionAnalytics(question.id, brain.levelForQuestion(question), question.topic || question.domain); track('question_answered', { battleId: state.battleId, ...result });
const feedback = document.querySelector('#answer-feedback');
if (feedback) { feedback.className = `answer-feedback ${correct ? 'correct-feedback' : 'wrong-feedback'}`; feedback.innerHTML = `<strong>${correct ? '✓ CORRECT' : '✕ WRONG'}</strong> <span>${correct ? `+${Math.round(question.ratingWeight * (100 + Math.max(0, question.estimatedTimeMs - timeTakenMs) / 100))} pts` : `Correct answer: ${question.correctAnswer}`}</span><small>${question.explanation}</small>`; }
if (!feedback) toast(correct ? `CORRECT · ${question.explanation}` : `WRONG · ${question.explanation}`);
setTimeout(() => { state.questionIndex += 1; state.questionStartedAt = Date.now(); if (state.questionIndex >= state.questions.length) finishBattle('completed'); else renderQuestion(); }, 700);
}
function calculateRating(result) {
const expected = 1 / (1 + Math.pow(10, (result.opponentRating - result.rating) / 400));
const outcome = result.score > result.opponentScore ? 1 : result.score === result.opponentScore ? 0.5 : 0;
const performance = result.answers.length ? result.answers.filter((answer) => answer.correct).length / result.answers.length : 0;
const k = 28; return Math.round(k * (outcome - expected) + (performance - 0.5) * 8);
}
function finishBattle(reason) {
if (state.phase === 'RESULT') return; stopTimers(); state.phase = 'RESULT'; document.body.classList.remove('final-seconds');
const opponentRating = 2182; const ratingChange = calculateRating({ rating: state.rating, opponentRating, score: state.score, opponentScore: state.opponentScore, answers: state.answers });
const won = state.score >= Math.ceil(state.questions.length / 2); const actualChange = won ? Math.max(8, Math.abs(ratingChange)) : -Math.max(8, Math.abs(ratingChange));
const previousRating = state.rating; state.rating += actualChange; state.streak += 1; state.bestStreak = Math.max(state.bestStreak, state.streak);
const accuracy = state.answers.length ? Math.round(state.answers.filter((answer) => answer.correct).length / state.answers.length * 100) : 0;
if (state.calibration) { state.calibration = false; track('CALIBRATION_COMPLETED', { currentEdge: state.brain.currentEdge }); }
state.history.push({ battleId: state.battleId, opponent: 'RIVAL_07', result: won ? 'W' : 'L', ratingChange: actualChange, accuracy, at: new Date().toISOString() }); persist(); updateLobbyStats(); track('battle_completed', { battleId: state.battleId, reason, won, ratingChange: actualChange }); updateResult({ won, previousRating, actualChange, accuracy }); show('result');
}
function updateLobbyStats() {
const rating = document.querySelector('.rating-card > strong'); if (rating) rating.textContent = state.rating;
const streak = document.querySelector('.streak strong'); if (streak) streak.textContent = `${state.streak} day streak`;
const edge = document.querySelector('#current-edge'); if (edge) edge.textContent = `CURRENT EDGE ${state.brain.currentEdge} / 200`;
const profileRating = document.querySelector('.profile-stats > b:first-child'); if (profileRating) profileRating.innerHTML = `${state.rating}<small>Rating</small>`;
const profileStreak = document.querySelector('.profile-stats > b:last-child'); if (profileStreak) profileStreak.innerHTML = `${state.streak}<small>Day streak</small>`;
}
function updateResult(result) {
const title = document.querySelector('.result-head h1'); if (title) title.textContent = result.won ? 'YOU WON.' : 'YOU LOST.';
const subtitle = document.querySelector('.result-head p'); if (subtitle) subtitle.textContent = result.won ? 'You made the better decisions under pressure.' : 'The arena found an edge. Run it back.';
const rating = document.querySelector('.result-rating > div'); if (rating) rating.innerHTML = `<span>${result.previousRating}</span> -> <strong>${state.rating}</strong>`;
const gain = document.querySelector('.result-rating > b'); if (gain) gain.innerHTML = `${result.actualChange > 0 ? '+' : ''}${result.actualChange} <small>MATIKS rating</small>`;
const breakdown = document.querySelector('.breakdown-grid'); if (breakdown) breakdown.innerHTML = `<b>${result.accuracy}%<small>Accuracy</small></b><b>${Math.round((state.answers.length ? state.answers.reduce((sum, answer) => sum + Math.max(0, 1 - answer.timeTakenMs / 10000), 0) / state.answers.length : 0) * 100)}%<small>Speed</small></b><b>${state.score} / ${state.questions.length}<small>Correct</small></b><b>${formatTime(Math.round((Date.now() - state.battleStartedAt) / 1000))}<small>Time used</small></b>`;
}
async function shareChallenge() {
const link = `${window.location.origin}${window.location.pathname}?challenge=${state.battleId || randomId()}&guest=1`; track('challenge_created', { link });
try { await navigator.clipboard.writeText(link); toast('Challenge link copied'); } catch { toast(link); }
}
function handleVisibility() { if (document.hidden && state.phase === 'ACTIVE') { track('tab_hidden', { battleId: state.battleId }); toast('FOCUS LOST — stay in the battle'); } }
document.addEventListener('visibilitychange', handleVisibility);
document.addEventListener('click', (event) => {
const nav = event.target.closest('[data-nav]'); if (nav) { event.preventDefault(); show(nav.dataset.nav); track(`${nav.dataset.nav}_viewed`); return; }
const action = event.target.closest('[data-action]')?.dataset.action;
if (action === 'find-match') { track('play_clicked'); startMatchmaking(); }
if (action === 'cancel-match') show('lobby');
if (action === 'abandon-battle') { stopTimers(); state.phase = 'ABANDONED'; toast('Battle abandoned. No rating change.'); show('lobby'); }
if (action === 'challenge-rival' || action === 'challenge-friend') shareChallenge();
const target = event.target.closest('[data-toast]'); if (target) toast(target.dataset.toast);
const toggle = event.target.closest('[data-toggle]'); if (toggle) toggle.classList.toggle('active');
});
document.querySelectorAll('.tabs button').forEach((button) => button.addEventListener('click', () => { document.querySelectorAll('.tabs button').forEach((item) => item.classList.remove('active')); button.classList.add('active'); toast(`${button.textContent} leaderboard selected`); track('leaderboard_viewed', { scope: button.textContent }); }));
const challenge = new URLSearchParams(window.location.search).get('challenge');
if (challenge) toast(`Challenge ${challenge} ready — play as a guest`);
show('lobby');
updateLobbyStats();