everyone! Yesterday, I started making a tic-tac-toe game for a website I wanted to make. After about 10 hours of working on it, I came up with about 150 lines of code just for the simple game. As usual when I make a large chunk of code, something, which I can't identify, went wrong. My whole entire code didn't work. Because of the large chunk of code, I copy pasted my code into a jsFiddle project, url shown below. My question is: can I use arrays or something of that type to lessen the number of if statements and redundancies? If anyone one can also help me create a faster, more efficient, code, I would be very thankful. Thanks in advance!
jsfiddle.net/justinpchang/3L6tp/
Why not have something like this :
/* This represents the current game, declare it upon starting a new game*/
var board = [['-','-','-'],['-','-','-'],['-','-','-']];
function notTaken(board,row,col) {
return (board[row][col] == '-');
}
function hasX(board,row,col) {
return (board[row][col] == 'x');
} // have a similar function for O
This eliminates a lot of redundancy in your code. Also, with HTML5 you can add custom attributes to your div elements which will specify the row and column of the cell. So top-mid div for example would have attributes "data-row" and "data-col" and values 0 and 1 respectively. I think the attribute names have to start with "data-" but I'm not sure.
Oh and one other thing: Never compare booleans to true or false, it is redundant. instead of doing: (some_bool != false) Just do: (some_bool)
Since booleans can only be true or false anyways. Similarly: (some_bool == false) Can just be written as: !(some_bool)
Hope this helps.