treeData = ({
id: "A", type: "MAX",
children: [
{
id: "B", type: "MIN",
children: [
{
id: "C", type: "MAX",
children: [
{ id: "G", value: -1 },
{ id: "H", value: 3 }
]
},
{
id: "D", type: "MAX",
children: [
{ id: "I", value: 5 },
{ id: "J", value: 1 }
]
}
]
},
{
id: "E", type: "MIN",
children: [
{
id: "F", type: "MAX",
children: [
{ id: "K", value: -6 },
{ id: "L", value: -4 }
]
},
{
id: "M", type: "MAX",
children: [
{ id: "N", value: 0 },
{ id: "O", value: 9 }
]
}
]
}
]
})
// 2. Précalcul de la trace d'exécution
trace = {
const steps = [];
const state = {}; // nodeId -> { alpha, beta, val, status }
const prunedEdges = new Set(); // "parentId->childId"
const fmt = (v) => (v === Infinity ? "+∞" : v === -Infinity ? "-∞" : v);
function snap(activeId, msg) {
steps.push({
activeId,
msg,
state: structuredClone(state),
prunedEdges: new Set(prunedEdges)
});
}
function alphabeta(node, alpha, beta) {
state[node.id] = { alpha, beta, val: null, status: "active" };
if (!node.children) {
state[node.id].val = node.value;
state[node.id].status = "done";
snap(node.id, `Évaluer la feuille ${node.id} = ${node.value}`);
return node.value;
}
const isMax = node.type === "MAX";
let best = isMax ? -Infinity : Infinity;
snap(node.id, `Entrer dans ${node.id} (${node.type}) avec α=${fmt(alpha)}, β=${fmt(beta)}`);
for (let i = 0; i < node.children.length; i++) {
const child = node.children[i];
const v = alphabeta(child, alpha, beta);
if (isMax) {
best = Math.max(best, v);
alpha = Math.max(alpha, best);
} else {
best = Math.min(best, v);
beta = Math.min(beta, best);
}
state[node.id] = { alpha, beta, val: best, status: "active" };
snap(node.id, `Mettre à jour ${node.id} : val=${best}, α=${fmt(alpha)}, β=${fmt(beta)}`);
if (beta <= alpha) {
for (let j = i + 1; j < node.children.length; j++) {
prunedEdges.add(`${node.id}->${node.children[j].id}`);
}
snap(node.id, `Élaguer les enfants restants de ${node.id} (β=${fmt(beta)} ≤ α=${fmt(alpha)})`);
break;
}
}
state[node.id].status = "done";
snap(node.id, `Terminer ${node.id} avec la valeur ${best}`);
return best;
}
snap(null, "Arbre initial");
alphabeta(treeData, -Infinity, Infinity);
return steps;
}
// 3. Commandes de navigation (boutons Précédent / Suivant + curseur)
viewof step = {
const form = html`<div style="display:flex; gap:10px; align-items:center; font-size:0.75em; margin-bottom:6px;">
<button type="button" id="prev">◀ Précédent</button>
<button type="button" id="next">Suivant ▶</button>
<input type="range" id="slider" min="0" max="${trace.length - 1}" value="0" style="width:220px;">
<span id="counter" style="font-weight:600;"></span>
</div>`;
const prev = form.querySelector("#prev");
const next = form.querySelector("#next");
const slider = form.querySelector("#slider");
const counter = form.querySelector("#counter");
const update = (val) => {
form.value = Math.max(0, Math.min(trace.length - 1, val));
slider.value = form.value;
prev.disabled = form.value === 0;
next.disabled = form.value === trace.length - 1;
counter.textContent = `Étape ${form.value} / ${trace.length - 1}`;
form.dispatchEvent(new Event("input", { bubbles: true }));
};
prev.onclick = () => update(form.value - 1);
next.onclick = () => update(form.value + 1);
slider.oninput = () => update(+slider.value);
update(0);
return form;
}
// 4. Rendu SVG de l'arbre avec D3 (étiquettes fixes à l'intérieur, valeurs/bornes à l'extérieur, feuilles révélées à la visite)
chart = {
const width = 900, height = 390, margin = { top: 40, right: 90, bottom: 45, left: 60 };
const current = trace[step];
const fmt = (v) => (v === Infinity ? "+∞" : v === -Infinity ? "-∞" : v);
const root = d3.hierarchy(treeData);
d3.tree().size([width - margin.left - margin.right, height - margin.top - margin.bottom])(root);
// Recueillir tous les nœuds et arêtes situés dans un sous-arbre élagué
const prunedNodeIds = new Set();
const prunedSubtreeEdges = new Set();
function markPrunedDescendents(d3Node) {
prunedNodeIds.add(d3Node.data.id);
if (d3Node.children) {
for (const ch of d3Node.children) {
prunedSubtreeEdges.add(`${d3Node.data.id}->${ch.data.id}`);
markPrunedDescendents(ch);
}
}
}
root.descendants().forEach(d3Node => {
if (d3Node.parent && current.prunedEdges.has(`${d3Node.parent.data.id}->${d3Node.data.id}`)) {
markPrunedDescendents(d3Node);
}
});
const isCutEdge = (d) =>
current.prunedEdges.has(`${d.source.data.id}->${d.target.data.id}`);
const isPrunedSubtreeEdge = (d) =>
prunedSubtreeEdges.has(`${d.source.data.id}->${d.target.data.id}`);
const isPrunedSubtreeNode = (d) =>
prunedNodeIds.has(d.data.id);
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height])
.style("width", "100%")
.style("max-height", "410px")
.style("font-family", "sans-serif");
const g = svg.append("g").attr("transform", `translate(${margin.left},${margin.top})`);
// Arêtes
g.selectAll("line")
.data(root.links())
.join("line")
.attr("x1", d => d.source.x)
.attr("y1", d => d.source.y)
.attr("x2", d => d.target.x)
.attr("y2", d => d.target.y)
.attr("stroke", d => (isCutEdge(d) || isPrunedSubtreeEdge(d)) ? "#d62728" : "#666")
.attr("stroke-width", d => (isCutEdge(d) || isPrunedSubtreeEdge(d)) ? 2 : 2)
.attr("stroke-dasharray", d => {
if (isCutEdge(d)) return "6,4";
if (isPrunedSubtreeEdge(d)) return "2,4";
return null;
})
.attr("stroke-linecap", d => isPrunedSubtreeEdge(d) ? "round" : "butt");
// Nœuds
const node = g.selectAll("g.node")
.data(root.descendants())
.join("g")
.attr("transform", d => `translate(${d.x},${d.y})`);
// Triangle vers le haut (MAX), triangle vers le bas (MIN), cercle (feuille)
node.append("path")
.attr("d", d => {
if (!d.children) return d3.symbol().type(d3.symbolCircle).size(950)();
return d.data.type === "MAX"
? "M 0,-20 L 20,15 L -20,15 Z"
: "M 0,20 L 20,-15 L -20,-15 Z";
})
.attr("fill", d => {
const id = d.data.id;
if (current.activeId === id) return "#ffeb99";
if (current.state[id]?.status === "done") return "#d9f0d3";
return "#f4f4f4";
})
.attr("stroke", d => {
if (isPrunedSubtreeNode(d)) return "#d62728";
if (current.activeId === d.data.id) return "#d97706";
return "#333";
})
.attr("stroke-width", d => {
if (isPrunedSubtreeNode(d)) return 2;
if (current.activeId === d.data.id) return 3;
return 1.5;
})
.attr("stroke-dasharray", d => isPrunedSubtreeNode(d) ? "2,4" : null)
.attr("stroke-linecap", d => isPrunedSubtreeNode(d) ? "round" : "butt");
// Identifiant persistant du nœud à l'intérieur de la forme
node.append("text")
.attr("text-anchor", "middle")
.attr("dy", d => !d.children ? "0.35em" : (d.data.type === "MAX" ? "0.62em" : "-0.22em"))
.attr("font-size", "13px")
.attr("font-weight", "bold")
.text(d => d.data.id);
// Valeur d'utilité sous la feuille : révélée uniquement une fois visitée
node.filter(d => !d.children)
.append("text")
.attr("text-anchor", "middle")
.attr("y", 28)
.attr("font-size", "13px")
.attr("font-weight", "600")
.attr("fill", "#222")
.text(d => {
if (isPrunedSubtreeNode(d)) return "";
const s = current.state[d.data.id];
return s && s.val !== null && s.val !== undefined ? `v=${d.data.value}` : "v=?";
});
// Valeur courante du nœud interne et fenêtre [alpha, beta] à droite
node.filter(d => d.children)
.append("text")
.attr("x", 24)
.attr("y", 4)
.attr("font-size", "12px")
.attr("fill", "#1f77b4")
.text(d => {
const s = current.state[d.data.id];
if (!s) return "";
const valStr = s.val !== null && s.val !== undefined ? `val=${s.val} ` : "";
return `${valStr}[${fmt(s.alpha)}, ${fmt(s.beta)}]`;
});
return svg.node();
}
// 5. Zone de message fixe en bloc aside sous l'arbre
asideStatus = {
const current = trace[step];
return htl.html`<aside style="margin-top:8px; padding:8px 12px; border-left:4px solid #1f77b4; background:#f8fafc; font-size:0.78em;">
${current.msg}
</aside>`;
}