previous

page 4

next
checking for XXX

Lots to learn here. You'll probably admire the elegance of my code below but please understand that it was arrived at after several poor efforts. My first attempt was perhaps three times as long. It worked BUT it broke one of the guides to good design. When it found an XXX, it did the colouring-in that you saw in the demo. This is known as a side effect.
In general, a function should do one thing and one thing only.
This function's job is just to check for XXX.
I introduced the global g_result to store the results of its deliberations.

check function
function check() {
g_result=[];
var arr=[
[0,1,2],[3,4,5],[6,7,8], // rows
[0,3,6],[1,4,7],[2,5,8], // columns
[0,4,8],[2,4,6] // diagonals
];
for (var i=0;i<arr.length;i++) {
var trio=arr[i]; var t=0;
for (var j=0;j<3;j++) {
var id=trio[j];
t+=g_squares[id];
}
if (t==3) g_result.push(trio);
}
if (g_result.length>0) return true; else return false;
}
the colouring-in

As you've no doubt guessed, we're going to need another function to do the colouring in.

previous
next