-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.py
More file actions
426 lines (355 loc) · 16.1 KB
/
engine.py
File metadata and controls
426 lines (355 loc) · 16.1 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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
import json
import random
from dataclasses import dataclass, field
from typing import Optional
# ---------------------------------------------------------------------------
# DATACLASS: rappresenta una singola risposta
# ---------------------------------------------------------------------------
# Un dataclass è come una classe normale ma pensata per contenere dati.
# Python genera automaticamente __init__, __repr__ ecc.
@dataclass
class Answer:
text: str # testo della risposta, es. "<class 'float'>"
is_correct: bool # True se è la risposta corretta
# ---------------------------------------------------------------------------
# DATACLASS: rappresenta una domanda completa
# ---------------------------------------------------------------------------
@dataclass
class Question:
id: str # es. "basi_001"
category_id: str # es. "basi"
text: str # testo della domanda
difficulty: int # 1, 2 o 3
answers: list[Answer] # lista di oggetti Answer
explanation: str # spiegazione mostrata dopo la risposta
code_example: str # codice di esempio
# ---------------------------------------------------------------------------
# DATACLASS: tiene traccia di una risposta data dall'utente durante il quiz
# ---------------------------------------------------------------------------
@dataclass
class UserAnswer:
question: Question # la domanda a cui ha risposto
# indice della risposta scelta (0-3) DOPO il mescolamento
chosen_index: int
# testo della risposta scelta (robusto al mescolamento)
chosen_text: str
is_correct: bool # True se ha risposto correttamente
# punti guadagnati/persi (+difficoltà o -difficoltà)
points: int
# ---------------------------------------------------------------------------
# CLASSE PRINCIPALE: QuizEngine
# ---------------------------------------------------------------------------
class QuizEngine:
"""
Gestisce tutta la logica del quiz.
Flusso di utilizzo:
1. engine = QuizEngine("questions.json")
2. engine.start_quiz(category_id, num_questions)
3. while not engine.is_finished():
q = engine.current_question()
engine.answer(chosen_index)
4. results = engine.get_results()
"""
def __init__(self, json_path: str):
"""
Carica il file JSON e prepara le strutture dati interne.
Args:
json_path: percorso al file questions.json
"""
self.json_path = json_path
# Dizionario {category_id -> dict con nome e description}
# es. {"basi": {"id": "basi", "name": "Basi ...", ...}, ...}
self.categories: dict[str, dict] = {}
# Dizionario {category_id -> lista di oggetti Question}
# es. {"basi": [Question(...), Question(...), ...], ...}
self.questions_by_category: dict[str, list[Question]] = {}
# --- Stato del quiz in corso ---
# domande selezionate per il quiz
self._quiz_questions: list[Question] = []
self._current_index: int = 0 # indice domanda corrente
self._user_answers: list[UserAnswer] = [] # risposte dell'utente
self._quiz_active: bool = False # True se il quiz è in corso
# Carica i dati dal JSON
self._load_data()
# -----------------------------------------------------------------------
# METODI PRIVATI (uso interno)
# -----------------------------------------------------------------------
def _load_data(self):
"""
Legge il file JSON e popola self.categories e self.questions_by_category.
Ogni domanda viene convertita in un oggetto Question (con oggetti Answer dentro).
"""
with open(self.json_path, "r", encoding="utf-8") as f:
raw = json.load(f) # raw è un dizionario Python
# 1) Carica le categorie in un dizionario indicizzato per id
for cat in raw["categories"]:
self.categories[cat["id"]] = cat
# inizializza lista vuota
self.questions_by_category[cat["id"]] = []
# 2) Carica le domande e le converte in oggetti Question
for q_raw in raw["questions"]:
# Converte ogni risposta da dict a oggetto Answer
answers = [
Answer(text=a["text"], is_correct=a["is_correct"])
for a in q_raw["answers"]
]
# Crea l'oggetto Question
question = Question(
id=q_raw["id"],
category_id=q_raw["category_id"],
text=q_raw["text"],
difficulty=q_raw["difficulty"],
answers=answers,
explanation=q_raw["explanation"],
code_example=q_raw["code_example"],
)
# Inserisce la domanda nel bucket della sua categoria
self.questions_by_category[question.category_id].append(question)
# -----------------------------------------------------------------------
# METODI PUBBLICI - INFORMAZIONI SULLE CATEGORIE E DOMANDE
# -----------------------------------------------------------------------
def get_categories(self, difficulty: int | None = None) -> list[dict]:
"""
Restituisce la lista delle categorie come lista di dizionari.
Aggiunge anche il conteggio delle domande disponibili per ciascuna.
Se difficulty è specificato, conta solo le domande di quella difficoltà
ed esclude le categorie con 0 domande disponibili.
Returns:
Lista di dict con chiavi: id, name, description, question_count
Esempio di output:
[{"id": "basi", "name": "Basi ...", "description": "...", "question_count": 8}, ...]
"""
result = []
for cat_id, cat_info in self.categories.items():
questions = self.questions_by_category[cat_id]
if difficulty is not None:
questions = [q for q in questions if q.difficulty == difficulty]
count = len(questions)
if count > 0:
result.append({
# copia tutte le chiavi originali (id, name, description)
**cat_info,
"question_count": count
})
return result
def get_max_questions_for(self, category_ids: list[str], difficulty: int | None = None) -> int:
"""
Restituisce il numero massimo di domande selezionabili
data una lista di categorie (somma delle domande disponibili).
Se difficulty è specificato, conta solo le domande di quella difficoltà.
Esempio: ["basi", "oop"] → 8 + 6 = 14
Args:
category_ids: lista di id categoria, es. ["basi", "oop"]
difficulty: se specificato (1, 2 o 3), filtra per difficoltà
Returns:
Somma delle domande disponibili in tutte le categorie richieste
"""
total = 0
for cat_id in category_ids:
questions = self.questions_by_category.get(cat_id, [])
if difficulty is not None:
questions = [q for q in questions if q.difficulty == difficulty]
total += len(questions)
return total
# -----------------------------------------------------------------------
# METODI PUBBLICI - GESTIONE DEL QUIZ
# -----------------------------------------------------------------------
def start_quiz(self, category_ids: list[str], num_questions: int, difficulty: int | None = None):
"""
Avvia un nuovo quiz multi-categoria.
Seleziona num_questions domande pescando proporzionalmente
da ogni categoria nella lista category_ids, poi mescola tutto.
Se difficulty è specificato (1, 2 o 3), usa solo le domande di quella difficoltà.
Esempio con category_ids=["basi","oop"] e num_questions=7:
basi ha 8 domande → peso 8/(8+6) ≈ 57% → 4 domande
oop ha 6 domande → peso 6/(8+6) ≈ 43% → 3 domande
totale: 4+3 = 7 ✓
"""
# Reset immediato: garantisce che le vecchie risposte non persistano
# anche in caso di eccezione durante la computazione successiva
self._quiz_questions = []
self._current_index = 0
self._user_answers = []
self._quiz_active = False
# --- Validazioni ---
if not category_ids:
raise ValueError("Seleziona almeno una categoria.")
for cat_id in category_ids:
if cat_id not in self.questions_by_category:
raise ValueError(f"Categoria '{cat_id}' non trovata.")
# Pool di domande per categoria (filtrato per difficoltà se specificata)
pool: dict[str, list[Question]] = {}
for cat_id in category_ids:
questions = self.questions_by_category[cat_id]
if difficulty is not None:
questions = [q for q in questions if q.difficulty == difficulty]
pool[cat_id] = questions
min_q = len(category_ids) # almeno 1 per categoria
max_q = sum(len(pool[cat_id]) for cat_id in category_ids)
if num_questions < min_q:
raise ValueError(
f"Con {len(category_ids)} categorie servono almeno {min_q} domande "
f"(1 per categoria)."
)
if num_questions > max_q:
raise ValueError(
f"Richieste {num_questions} domande ma le categorie scelte "
f"ne hanno solo {max_q} in totale."
)
# --- Distribuzione proporzionale ---
# Calcola quante domande prendere da ogni categoria.
sizes = {cat_id: len(pool[cat_id]) for cat_id in category_ids}
total_available = sum(sizes.values())
# Quote ideali (float)
ideal = {
cat_id: num_questions * size / total_available
for cat_id, size in sizes.items()
}
# Parte intera (floor), minimo 1 per categoria
allocation = {cat_id: max(1, int(q)) for cat_id, q in ideal.items()}
# Correzione: aggiusta il totale se non corrisponde a num_questions
diff = num_questions - sum(allocation.values())
if diff > 0:
# Ordina per resto decrescente e distribuisce i posti rimasti
remainders = sorted(
category_ids,
key=lambda c: ideal[c] - int(ideal[c]),
reverse=True,
)
for i in range(diff):
cat_to_bump = remainders[i % len(remainders)]
# Non superare il numero di domande disponibili
if allocation[cat_to_bump] < sizes[cat_to_bump]:
allocation[cat_to_bump] += 1
elif diff < 0:
# Riduco le categorie con più domande
for cat_id in sorted(category_ids, key=lambda c: allocation[c], reverse=True):
if diff == 0:
break
if allocation[cat_id] > 1:
allocation[cat_id] -= 1
diff += 1
# --- Selezione casuale per ogni categoria ---
selected: list[Question] = []
for cat_id, n in allocation.items():
available = pool[cat_id]
# random.sample non modifica la lista originale
selected.extend(random.sample(available, n))
# Mescolo le domande di tutte le categorie insieme
random.shuffle(selected)
# Mescolo le risposte di ogni domanda per ovviare alla prevedibilità.
shuffled: list[Question] = []
for q in selected:
answers_copy = q.answers.copy()
random.shuffle(answers_copy)
shuffled.append(Question(
id=q.id,
category_id=q.category_id,
text=q.text,
difficulty=q.difficulty,
answers=answers_copy,
explanation=q.explanation,
code_example=q.code_example,
))
self._quiz_questions = shuffled
# Reset stato
self._current_index = 0
self._user_answers = []
self._quiz_active = True
def current_question(self) -> Optional[Question]:
"""
Restituisce la domanda corrente del quiz.
"""
if not self._quiz_active or self.is_finished():
return None
return self._quiz_questions[self._current_index]
def answer(self, chosen_index: int) -> UserAnswer:
"""
Registra la risposta dell'utente alla domanda corrente.
"""
if not self._quiz_active or self.is_finished():
raise RuntimeError("Nessun quiz attivo o quiz già terminato.")
question = self.current_question()
if chosen_index < 0 or chosen_index >= len(question.answers):
raise IndexError(f"Indice risposta {chosen_index} non valido.")
chosen_answer = question.answers[chosen_index]
is_correct = chosen_answer.is_correct
# Calcolo punti:
# corretta → +difficulty (es. difficoltà 3 → +3 pt)
# sbagliata → 0 punti
points = question.difficulty if is_correct else 0
user_answer = UserAnswer(
question=question,
chosen_index=chosen_index,
chosen_text=chosen_answer.text,
is_correct=is_correct,
points=points,
)
self._user_answers.append(user_answer)
# NON incrementiamo _current_index qui — lo fa next_question()
return user_answer
def next_question(self):
"""
Avanza alla domanda successiva.
Da chiamare DOPO aver mostrato il feedback all'utente (answered=True)
"""
if len(self._user_answers) <= self._current_index:
raise RuntimeError(
"Rispondi prima alla domanda corrente prima di avanzare."
)
self._current_index += 1
def is_finished(self) -> bool:
"""
Restituisce True se tutte le domande del quiz sono state risposte.
"""
return self._current_index >= len(self._quiz_questions)
def progress(self) -> tuple[int, int]:
"""
Restituisce lo stato di avanzamento del quiz.
"""
return (self._current_index + 1, len(self._quiz_questions))
# -----------------------------------------------------------------------
# METODI PUBBLICI - RISULTATI FINALI
# -----------------------------------------------------------------------
def get_results(self) -> dict:
"""
Calcola e restituisce i risultati finali del quiz.
Da chiamare solo quando is_finished() è True.
Returns:
Dizionario con tutte le statistiche del quiz:
{
"total_questions": int,
"correct": int,
"wrong": int,
"score": int, # punteggio netto (può essere negativo)
"max_score": int, # punteggio massimo ottenibile
"percentage": float, # % risposte corrette (0-100)
"answers": list[UserAnswer] # dettaglio ogni risposta
}
"""
correct = sum(1 for ua in self._user_answers if ua.is_correct)
wrong = len(self._user_answers) - correct
score = sum(ua.points for ua in self._user_answers)
# Punteggio massimo = somma delle difficoltà di tutte le domande
max_score = sum(q.difficulty for q in self._quiz_questions)
# Percentuale di risposte corrette (evita divisione per zero)
total = len(self._user_answers)
percentage = (correct / total * 100) if total > 0 else 0.0
return {
"total_questions": total,
"correct": correct,
"wrong": wrong,
"score": score,
"max_score": max_score,
"percentage": round(percentage, 1),
"answers": list(self._user_answers),
}
def reset(self):
"""
Resetta completamente lo stato del quiz.
Utile per tornare alla schermata iniziale senza ricaricare il JSON.
"""
self._quiz_questions = []
self._current_index = 0
self._user_answers = []
self._quiz_active = False