I decided to make Tic Tac Toe using jsfiddle, and it was much more of a challenge that what I expected. I originally wanted to use a canvas element, but quickly realized that creating all of my elements would be too much work. I also decided (foolishly) to create a board that had the ability to create any number of playing boards. I probably should have started with a 3x3 and then moved up, but I finished (and before the day was over).
One of the more fun aspects of this project was determining how one wins. I figured out a couple algorithms (I think) that explain all of the combinations for any board type. I have a single while
loop that make the boardSize*2+2
number of combinations. In order to compare them, I decided to turn this data into an array of RegExp
expressions. There could also be numbers in between the different values, so I also accounted for that. The for
loop for creating the "win" combos is as follows:
var rdiagWin = "";
var ldiagWin = "";
var ldiagStart = ticTac.boardSize - 1;
for (i=0;i<ticTac.boardSize;i++) {
rdiagWin = rdiagWin + String(i*ticTac.boardSize+i) + "[0-9]?";
ldiagWin = ldiagWin + String(ldiagStart + i*(ticTac.boardSize-1))+"[0-9]?";
var rowStart = ticTac.boardSize*i;
var rowWin = "";
var colWin = "";
for (j=0;j<ticTac.boardSize;j++) {
rowWin = rowWin + String(rowStart+j)+"[0-9]?";
var colNext = j*ticTac.boardSize;
colWin = colWin + String(i+colNext)+"[0-9]?";
}
ticTac.wins.push(RegExp(rowWin));
ticTac.wins.push(RegExp(colWin));
}
ticTac.wins.push(RegExp(rdiagWin));
ticTac.wins.push(RegExp(ldiagWin));
The board does not have any special logic for the computer, although I might try to add that in at some point. As expected, the actual game controls were fairly easy to implement, and just required a little css to get things working properly. I made all of the event listeners in jquery, and I think I figured out all of the problems I had with creating accidental infinite loops. The code is here and below.