-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
325 lines (279 loc) · 11 KB
/
Copy pathindex.html
File metadata and controls
325 lines (279 loc) · 11 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
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Morpion — Humain vs Minimax</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
.cell {
width: 80px; height: 80px;
font-size: 2rem; font-weight: bold;
font-family: monospace;
}
.tree-level { overflow-x: auto; }
.board-node {
display: inline-block;
margin: 8px 8px;
font-family: monospace;
font-size: 0.85rem;
vertical-align: top;
}
.board-node table { border-collapse: collapse; }
.board-node td {
width: 28px; height: 28px;
text-align: center; vertical-align: middle;
border: 1px solid #999;
}
.played { background-color: #dee2e6; }
.score-victoire { color: #198754; font-weight: bold; }
.score-nul { color: #fd7e14; }
.score-defaite { color: #dc3545; }
.optimal { outline: 2px solid #0d6efd; }
</style>
</head>
<body class="bg-light">
<div class="container py-4">
<div class="d-flex justify-content-between align-items-center mb-4">
<h1 class="mb-0">Morpion — Analyse Minimax</h1>
<a href="about.html" class="text-muted text-decoration-none fs-4" title="À propos">ⓘ</a>
</div>
<div class="d-flex gap-5 align-items-start flex-wrap">
<!-- Plateau de jeu -->
<div>
<table id="plateau"></table>
<!-- Statut -->
<div class="mt-3" id="statut"></div>
<div class="mt-2 d-flex gap-2">
<button class="btn btn-primary" onclick="analyser()">Analyser</button>
<button class="btn btn-secondary" onclick="recommencer()">Recommencer</button>
</div>
</div>
<!-- Analyse du dernier coup de O -->
<div id="analyse"></div>
</div>
<!-- Arbre Minimax -->
<div id="arbre-container"></div>
</div>
<script>
// ── Moteur ───────────────────────────────────────────────────────────────────
const LIGNES_GAGNANTES = [
[0, 1, 2], [3, 4, 5], [6, 7, 8],
[0, 3, 6], [1, 4, 7], [2, 5, 8],
[0, 4, 8], [2, 4, 6],
];
function verifierVictoire(plateau, joueur) {
return LIGNES_GAGNANTES.some(c => c.every(i => plateau[i] === joueur));
}
class MoteurMorpion {
constructor() { this.reinitialiser(); }
reinitialiser() {
this.plateau = Array(9).fill(' ');
this.joueurActuel = 'X';
this.gagnant = null;
}
jouerCoup(pos) {
if (pos >= 0 && pos <= 8 && this.plateau[pos] === ' ' && !this.gagnant) {
this.plateau[pos] = this.joueurActuel;
if (verifierVictoire(this.plateau, this.joueurActuel)) {
this.gagnant = this.joueurActuel;
} else {
this.joueurActuel = this.joueurActuel === 'X' ? 'O' : 'X';
}
return true;
}
return false;
}
}
// ── Minimax ──────────────────────────────────────────────────────────────────
function _construireSousArbre(noeud, p, estMax, joueur, profondeur) {
const adv = joueur === 'X' ? 'O' : 'X';
if (verifierVictoire(p, joueur)) return 10 - profondeur;
if (verifierVictoire(p, adv)) return profondeur - 10;
if (!p.includes(' ')) return 0;
const joueurCourant = estMax ? joueur : adv;
const scores = [];
for (let i = 0; i < 9; i++) {
if (p[i] === ' ') {
p[i] = joueurCourant;
const enfant = { plateau: [...p], positionJouee: i, score: 0, estMax: !estMax, enfants: [] };
noeud.enfants.push(enfant);
const s = _construireSousArbre(enfant, [...p], !estMax, joueur, profondeur + 1);
enfant.score = s;
scores.push(s);
p[i] = ' ';
}
}
return estMax ? Math.max(...scores) : Math.min(...scores);
}
function construireArbre(plateau, joueur) {
const racine = { plateau: [...plateau], positionJouee: null, score: 0, estMax: true, enfants: [] };
racine.score = _construireSousArbre(racine, [...plateau], true, joueur, 0);
return racine;
}
function obtenirMeilleurCoup(plateau, joueur) {
const arbre = construireArbre(plateau, joueur);
const meilleur = arbre.enfants.reduce((best, n) => n.score > best.score ? n : best);
return { position: meilleur.positionJouee, arbre };
}
function bfsNiveaux(racine) {
const niveaux = [];
let courant = [racine];
while (courant.length) {
niveaux.push(courant);
courant = courant.flatMap(n => n.enfants);
}
return niveaux;
}
// ── État global ──────────────────────────────────────────────────────────────
let jeu = new MoteurMorpion();
let dernierArbre = null;
// ── Actions ──────────────────────────────────────────────────────────────────
function jouer(pos) {
jeu.jouerCoup(pos);
dernierArbre = null;
rendu();
}
function analyser() {
if (jeu.gagnant || !jeu.plateau.includes(' ')) return;
const conseil = obtenirMeilleurCoup(jeu.plateau, jeu.joueurActuel);
dernierArbre = conseil.arbre;
rendu();
}
function recommencer() {
jeu.reinitialiser();
dernierArbre = null;
rendu();
}
// ── Helpers rendu ────────────────────────────────────────────────────────────
function scoreInfo(score) {
if (score > 0) return { label: 'victoire', cls: 'score-victoire' };
if (score < 0) return { label: 'défaite', cls: 'score-defaite' };
return { label: 'nul', cls: 'score-nul' };
}
function miniBoard(noeud) {
const table = document.createElement('table');
for (let r = 0; r < 3; r++) {
const tr = document.createElement('tr');
for (let c = 0; c < 3; c++) {
const i = r * 3 + c;
const td = document.createElement('td');
if (i === noeud.positionJouee) td.className = 'played';
td.textContent = noeud.plateau[i] !== ' ' ? noeud.plateau[i] : '·';
tr.appendChild(td);
}
table.appendChild(tr);
}
return table;
}
// ── Rendu ────────────────────────────────────────────────────────────────────
function rendu() {
renduPlateau();
renduStatut();
renduAnalyse();
renduArbre();
}
function renduPlateau() {
const table = document.getElementById('plateau');
table.innerHTML = '';
const peutJouer = !jeu.gagnant && jeu.plateau.includes(' ');
for (let r = 0; r < 3; r++) {
const tr = document.createElement('tr');
for (let c = 0; c < 3; c++) {
const i = r * 3 + c;
const val = jeu.plateau[i];
const td = document.createElement('td');
const btn = document.createElement('button');
if (val === ' ' && peutJouer) {
btn.className = 'cell btn btn-outline-secondary';
btn.textContent = i;
btn.addEventListener('click', () => jouer(i));
} else {
btn.className = 'cell btn ' + (val === 'X' ? 'btn-primary' : val === 'O' ? 'btn-danger' : 'btn-outline-secondary');
btn.textContent = val !== ' ' ? val : '';
btn.disabled = true;
}
td.appendChild(btn);
tr.appendChild(td);
}
table.appendChild(tr);
}
}
function renduStatut() {
const div = document.getElementById('statut');
if (jeu.gagnant) {
div.innerHTML = `<div class="alert alert-success">Le joueur ${jeu.gagnant} a gagné !</div>`;
} else if (!jeu.plateau.includes(' ')) {
div.innerHTML = '<div class="alert alert-warning">Match nul !</div>';
} else {
div.innerHTML = `<p class="text-muted">Tour de ${jeu.joueurActuel}</p>`;
}
}
function renduAnalyse() {
const div = document.getElementById('analyse');
if (!dernierArbre) { div.innerHTML = ''; return; }
const tries = [...dernierArbre.enfants].sort((a, b) => b.score - a.score);
let html = `<h5>Analyse pour ${jeu.joueurActuel}</h5>`;
html += '<table class="table table-sm table-bordered w-auto"><thead><tr><th>Position</th><th>Résultat</th><th class="text-end">Score</th></tr></thead><tbody>';
const scoreOptimal = tries[0].score;
tries.forEach((enfant) => {
const { label, cls } = scoreInfo(enfant.score);
const estOptimal = enfant.score === scoreOptimal;
const rowCls = estOptimal ? ' class="table-primary fw-bold"' : '';
html += `<tr${rowCls}><td class="font-monospace">${enfant.positionJouee}</td><td class="${cls}">${label}</td><td class="text-end font-monospace">${enfant.score}</td></tr>`;
});
html += '</tbody></table>';
div.innerHTML = html;
}
function renduArbre() {
const container = document.getElementById('arbre-container');
if (!dernierArbre) { container.innerHTML = ''; return; }
container.innerHTML = '<hr class="my-4"><h4>Arbre Minimax</h4>';
bfsNiveaux(dernierArbre).slice(1).forEach((niveau, idx) => {
const niveauNum = idx + 1;
const adv = jeu.joueurActuel === 'X' ? 'O' : 'X';
const label = !niveau[0].estMax ? `Coups de ${jeu.joueurActuel}` : `Coups de ${adv}`;
const terminaux = niveau.filter(n => !n.enfants.length);
const nonTerminaux = niveau.filter(n => n.enfants.length);
const nbSlotsNonTerminaux = Math.max(100 - terminaux.length, 0);
const noeudsAffiches = [...terminaux.slice(0, 100), ...nonTerminaux.slice(0, nbSlotsNonTerminaux)];
const nbMasques = niveau.length - noeudsAffiches.length;
const divNiveau = document.createElement('div');
divNiveau.className = 'mb-3';
const info = document.createElement('p');
info.className = 'text-muted small mb-1';
info.textContent = `Niveau ${niveauNum} — ${label}`;
divNiveau.appendChild(info);
const treeLevel = document.createElement('div');
treeLevel.className = 'tree-level';
noeudsAffiches.forEach(noeud => {
const divNoeud = document.createElement('div');
divNoeud.className = 'board-node';
if (!noeud.enfants.length) {
if (noeud.score > 0) divNoeud.classList.add('border', 'border-success');
else if (noeud.score < 0) divNoeud.classList.add('border', 'border-danger');
}
divNoeud.appendChild(miniBoard(noeud));
if (!noeud.enfants.length) {
const { label: scoreLabel, cls } = scoreInfo(noeud.score);
const scoreDiv = document.createElement('div');
scoreDiv.className = cls + ' text-center';
scoreDiv.textContent = `${scoreLabel} (${noeud.score})`;
divNoeud.appendChild(scoreDiv);
}
treeLevel.appendChild(divNoeud);
});
divNiveau.appendChild(treeLevel);
if (nbMasques > 0) {
const elision = document.createElement('p');
elision.className = 'text-muted small mt-1';
elision.textContent = `… ${nbMasques} position(s) masquée(s)`;
divNiveau.appendChild(elision);
}
container.appendChild(divNiveau);
});
}
rendu();
</script>
</body>
</html>