
previous

page 6
next
"teaching" the computer to play
Before we start, I found it convenient to make a function to draw the X.
the do_x function
function do_x(id) {
var el=document.getElementById(id);
el.textContent='X';
g_squares[id]=1;
}
var el=document.getElementById(id);
el.textContent='X';
g_squares[id]=1;
}
I can now show you my computer function. You'll see I've broken the one thing guideline - I'll explain why later.
function computer() {
var ids=[];
for (var i=0;i<9;i++) ids[i]=i;
Shuffle(ids);
for (var i=0;i<9;i++) {
var id=ids[i];
if (g_squares[id]==0) { // try this square
g_squares[id]=1;
if (check()) { // no good - it's a loser!
var id_loser=id; // save it in case we have to use it
g_squares[id]=0; // undo move
} else {
do_x(id);
return; // all done
}
}
}
// no good move found - make id_loser move & lose
do_x(id_loser);
check();
show_result();
}
var ids=[];
for (var i=0;i<9;i++) ids[i]=i;
Shuffle(ids);
for (var i=0;i<9;i++) {
var id=ids[i];
if (g_squares[id]==0) { // try this square
g_squares[id]=1;
if (check()) { // no good - it's a loser!
var id_loser=id; // save it in case we have to use it
g_squares[id]=0; // undo move
} else {
do_x(id);
return; // all done
}
}
}
// no good move found - make id_loser move & lose
do_x(id_loser);
check();
show_result();
}
previous
next