-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
434 lines (357 loc) · 15.6 KB
/
script.js
File metadata and controls
434 lines (357 loc) · 15.6 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
427
428
429
430
431
432
433
434
/**
* script.js
* Gestisce l'interfaccia utente (DOM), gli eventi e coordina Solver e Tactics.
* Dipende da: solver.js, tactics.js
*/
// --- GLOBAL VARS (UI ONLY) ---
// Nota: players, grid, constraints, etc. sono definiti in solver.js
let myName = "";
let myExpectedCount = 0;
let currentTurnIndex = 0;
let fullGameLogs = [];
// --- SETUP FUNCTIONS ---
function handleEnter(e) {
if(e.key === 'Enter') addPlayer();
}
function addPlayer() {
// 'players' è definita globalmente in solver.js
if (players.length >= 6) return;
const input = document.getElementById('new-player');
const name = input.value.trim();
if (name && !players.includes(name)) {
players.push(name);
document.getElementById('player-list').innerHTML += `<span class="player-tag">${players.length}. ${name}</span>`;
const meSelect = document.getElementById('who-am-i');
const opt1 = document.createElement('option');
opt1.value = name;
opt1.text = name;
meSelect.appendChild(opt1);
input.value = '';
input.focus();
if (players.length >= 6) {
input.disabled = true;
input.placeholder = "Max players reached";
}
} else if (players.includes(name)) {
alert("Giocatore già presente!");
}
}
function goToHandSelection() {
if (players.length < 2) return alert("Minimo 2 giocatori!");
myName = document.getElementById('who-am-i').value;
if(!myName) return alert("Chi sei tu?");
// Calcolo matematico distribuzione carte
const myIndex = players.indexOf(myName);
const baseCount = Math.floor(CARDS_IN_DECK / players.length);
const remainder = CARDS_IN_DECK % players.length;
myExpectedCount = baseCount + (myIndex < remainder ? 1 : 0);
updateHandCountUI(0);
const createChecks = (list, containerId) => {
const div = document.getElementById(containerId);
div.innerHTML = "";
list.forEach(c => {
div.innerHTML += `<label class="check-card"><input type="checkbox" value="${c}" class="init-card-check" onchange="updateHandCountUI()"><span>${c}</span></label>`;
});
};
createChecks(suspects, 'hand-suspects');
createChecks(weapons, 'hand-weapons');
createChecks(rooms, 'hand-rooms');
switchView('view-setup', 'view-hand');
}
function updateHandCountUI() {
const current = document.querySelectorAll('.init-card-check:checked').length;
const badge = document.getElementById('hand-counter-badge');
badge.innerText = `Selezionate: ${current} / ${myExpectedCount}`;
if (current === myExpectedCount) {
badge.classList.add('valid');
} else {
badge.classList.remove('valid');
}
}
function finalizeSetup() {
const checks = document.querySelectorAll('.init-card-check:checked');
if (checks.length !== myExpectedCount) {
alert(`Attenzione! Dovresti avere ${myExpectedCount} carte. Ne hai selezionate ${checks.length}.`);
return;
}
// 1. Inizializzazione Variabili Gioco (Solver)
// Usa la nuova funzione resetGameVars per pulire cache e griglia
if (typeof resetGameVars === 'function') {
resetGameVars();
} else {
// Fallback (non dovrebbe servire se solver.js è aggiornato)
allCards.forEach(c => { grid[c] = { SOL: 0 }; players.forEach(p => grid[c][p] = 0); });
}
// 2. Imposta le mie carte come "Viste" (2)
checks.forEach(chk => setFact(chk.value, myName, 2));
// 3. Calcola i limiti carte per tutti
const baseCount = Math.floor(CARDS_IN_DECK / players.length);
const remainder = CARDS_IN_DECK % players.length;
players.forEach((p, index) => {
limits[p] = baseCount + (index < remainder ? 1 : 0);
});
// 4. Configurazione UI
populateSelect('turn-asker', players);
populateSelect('turn-responder', players, true);
populateSelect('turn-suspect', suspects, false, "👤 Sospettato");
populateSelect('turn-weapon', weapons, false, "🔫 Arma");
populateSelect('turn-room', rooms, false, "🏰 Stanza");
populateSelect('current-position', rooms);
if(typeof initPathfinding === 'function') initPathfinding();
currentTurnIndex = 0;
updateTurnUI();
switchView('view-hand', 'view-game');
// 5. Prima esecuzione Motori
runSolver();
updateTacticalSuggestions();
}
// --- TURN MANAGEMENT ---
function updateTurnUI() {
document.getElementById('turn-asker').value = players[currentTurnIndex];
checkSpecialInput();
checkBluffUI();
}
function checkBluffUI() {
const s = document.getElementById('turn-suspect').value;
const w = document.getElementById('turn-weapon').value;
const r = document.getElementById('turn-room').value;
const asker = document.getElementById('turn-asker').value;
const indicator = document.getElementById('bluff-indicator');
if (!asker) {
indicator.innerHTML = "";
return;
}
// Controlla se l'asker possiede già una delle carte che chiede
let bluffs = [s, w, r].filter(c => c && grid[c] && grid[c][asker] === 2);
if (bluffs.length > 0) {
if (asker === myName) {
indicator.style.color = "var(--success)";
indicator.innerHTML = `🤫 Stai bluffando su: <b>${bluffs.join(', ')}</b>`;
} else {
indicator.style.color = "var(--accent)";
indicator.innerHTML = `⚠️ <b>${asker}</b> sta bluffando! Ha: <b>${bluffs.join(', ')}</b>`;
}
} else {
indicator.innerHTML = "";
}
}
function checkSpecialInput() {
const asker = document.getElementById('turn-asker').value;
const responder = document.getElementById('turn-responder').value;
const box = document.getElementById('private-reveal-box');
const select = document.getElementById('turn-card-shown');
// Mostra il box "Che carta hai visto?" solo se IO ho chiesto e QUALCUNO ha risposto
if (asker === myName && responder !== 'none' && responder !== '' && responder !== myName) {
box.classList.remove('hidden');
const s = document.getElementById('turn-suspect').value;
const w = document.getElementById('turn-weapon').value;
const r = document.getElementById('turn-room').value;
const currentVal = select.value;
select.innerHTML = '<option value="" disabled selected>-- Seleziona carta vista --</option>';
[s, w, r].forEach(c => {
if(c) {
let opt = document.createElement('option');
opt.value = c; opt.text = c;
if(c === currentVal) opt.selected = true;
select.appendChild(opt);
}
});
} else {
box.classList.add('hidden');
select.value = "";
}
}
function submitTurn() {
const s = document.getElementById('turn-suspect').value;
const w = document.getElementById('turn-weapon').value;
const r = document.getElementById('turn-room').value;
const asker = document.getElementById('turn-asker').value;
const responder = document.getElementById('turn-responder').value;
if(!asker || !s || !w || !r) return alert("Compila tutti i campi!");
if(asker === responder) return alert("Domanda e risposta dalla stessa persona!");
if (asker === myName && responder !== 'none' && responder !== '' && responder !== myName) {
if (!document.getElementById('turn-card-shown').value) {
return alert("Non hai specificato quale carta ti ha mostrato " + responder + "!");
}
}
// Salva History per Undo (deep copy)
history.push({
grid: JSON.parse(JSON.stringify(grid)),
constraints: JSON.parse(JSON.stringify(constraints)),
turnIndex: currentTurnIndex,
limits: JSON.parse(JSON.stringify(limits))
});
const involved = [s, w, r];
log(`🔎 <b>${asker}</b> chiede: ${s}, ${w}, ${r}`);
// 1. Logica dei "PASS": chi sta tra asker e responder non ha le carte
let currentIdx = (players.indexOf(asker) + 1) % players.length;
let loops = 0;
while(loops < players.length) {
const p = players[currentIdx];
if(p === responder) break;
if(responder === 'none' && p === asker) break;
involved.forEach(c => setFact(c, p, 1));
currentIdx = (currentIdx + 1) % players.length;
loops++;
}
// 2. Logica Risposta
if (responder !== 'none') {
log(`💡 <b>${responder}</b> ha mostrato una carta.`);
if (asker === myName) {
const seen = document.getElementById('turn-card-shown').value;
if (seen && involved.includes(seen)) {
log(`👁️ Hai visto: <span class="log-highlight">${seen}</span>`);
setFact(seen, responder, 2);
} else {
addConstraint(responder, involved);
}
} else if (responder !== myName) {
addConstraint(responder, involved);
}
} else {
log(`❌ Nessuno ha risposto!`);
}
// Reset UI per prossimo turno
document.getElementById('turn-responder').value = "none";
document.getElementById('turn-suspect').value = "";
document.getElementById('turn-weapon').value = "";
document.getElementById('turn-room').value = "";
currentTurnIndex = (players.indexOf(asker) + 1) % players.length;
updateTurnUI();
// Core Engine Execution
runSolver();
// Avvia la simulazione Monte Carlo per aggiornare i suggerimenti tattici
// Nota: Potrebbe causare un micro-freeze impercettibile (2000 iterazioni)
updateTacticalSuggestions();
}
// --- LOGGING & RENDERING ---
function log(m) {
const textOnly = m.replace(/<[^>]*>/g, '');
const time = new Date().toLocaleTimeString();
fullGameLogs.push(`[${time}] ${textOnly}`);
const el = document.getElementById('log-area');
el.innerHTML = `<div class="log-entry">${m}</div>` + el.innerHTML;
}
function renderGrid() {
const table = document.getElementById('main-grid');
// Recupera probabilità (se disponibili)
const probs = (typeof getProbabilities === 'function') ? getProbabilities() : null;
let html = `<thead><tr><th>Carte</th>`;
players.forEach(p => html += `<th>${p}</th>`);
html += `</tr></thead><tbody>`;
const buildRows = (title, list) => {
html += `<tr><td colspan="${players.length+1}" class="grid-section-title"><b>${title.toUpperCase()}</b></td></tr>`;
list.forEach(c => {
const isSol = grid[c].SOL === 2;
const isNoSol = grid[c].SOL === 1;
// Colora il nome della carta se è probabile soluzione
let cardStyle = "";
let solPctDisplay = "";
if (!isSol && !isNoSol && probs && probs.solution[c] > 0) {
// Sfondo sfumato leggero sul nome
const solProb = probs.solution[c];
const pct = Math.round(solProb * 100);
if (pct > 0) {
cardStyle = `style="background: linear-gradient(90deg, rgba(245, 158, 11, ${Math.min(0.4, solProb * 0.5)}) 0%, transparent 100%);"`;
solPctDisplay = `<span class="prob-text-sol">${pct}%</span>`;
}
}
const rowClass = isSol ? 'c-sol' : '';
html += `<tr><td class="${rowClass}" ${cardStyle}>${c} ${solPctDisplay}</td>`;
players.forEach(p => {
const val = grid[c][p];
let content = '';
let cellClass = 'c-unk'; // Classe base per la cella (td)
if (val === 2) {
content = '✔';
cellClass = 'c-yes';
}
else if (val === 1) {
content = '✘';
cellClass = 'c-no';
}
else {
// Logica Probabilità Unificata
if (probs && probs.distribution) {
const rawProb = probs.distribution[c][p];
if (rawProb !== undefined && rawProb !== null) {
let pct = Math.round(rawProb * 100);
let textToShow = `${pct}%`;
// Gestione <1%
if (pct === 0 && rawProb > 0) textToShow = "<1%";
// Calcolo opacità sfondo: min 0.1 (per gli 0%), max 0.8 (per il 100%)
// Usiamo l'indaco (var(--primary)) come base
// Se è 0% esatto (matematicamente impossibile che ce l'abbia, ma non ancora segnato come NO), lo teniamo molto spento.
let alpha = 0.1;
if (rawProb > 0) {
alpha = 0.15 + (rawProb * 0.65);
}
// Se la probabilità è 0 assoluta (dalla simulazione) o molto bassa, il testo è grigio scuro, altrimenti bianco
const textColor = (rawProb < 0.3) ? '#9ca3af' : '#fff';
// O se preferisci sempre bianco per uniformità, usa sempre #fff e alza l'alpha minimo.
// Costruiamo il badge usando lo stile CSS unificato
// Nota: lo style inline definisce SOLO il colore dinamico
content = `<span class="prob-badge" style="background-color: rgba(99, 102, 241, ${alpha}); color: ${textColor}">${textToShow}</span>`;
}
}
}
html += `<td class="${cellClass}">${content}</td>`;
});
html += `</tr>`;
});
};
buildRows("Sospettati", suspects);
buildRows("Armi", weapons);
buildRows("Stanze", rooms);
table.innerHTML = html + "</tbody>";
}
// --- UTILS ---
function switchView(f, t) {
document.getElementById(f).classList.add('hidden');
document.getElementById(t).classList.remove('hidden');
}
function populateSelect(id, list, addNone=false, label=null) {
const s = document.getElementById(id);
s.innerHTML = '';
if(label) {
const o = document.createElement('option');
o.value=""; o.text=label; o.disabled = true; o.selected = true;
s.appendChild(o);
}
if(addNone) {
const o = document.createElement('option');
o.value="none"; o.text="❌ NESSUNO (Tutti passano)";
s.appendChild(o);
}
list.forEach(i => {
const o = document.createElement('option');
o.value=i; o.text=i;
s.appendChild(o);
});
}
function exportGameLogs() {
if (fullGameLogs.length === 0) return alert("Nessun dato da esportare.");
let content = "CLUEDO SOLVER PRO - REGISTRO PARTITA\n";
content += "====================================\n\n";
content += fullGameLogs.join("\n");
content += "\n\n====================================\n";
content += "STATO GRIGLIA FINALE\n";
content += JSON.stringify(grid, null, 2);
const blob = new Blob([content], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `cluedo_logs_${new Date().toISOString().slice(0,10)}.txt`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
// Prevenzione chiusura accidentale
window.addEventListener('beforeunload', function (e) {
if (history.length > 0) {
e.preventDefault();
e.returnValue = '';
return '';
}
});