/JSTicTacToe

Primary LanguageJavaScript

How JSTicTacToe Works?

  • There are three files: an HTML, a CSS and a JavaScript, which cleanly separate their respective functions. Take note that the HTML file deals only with the content and there is no script nor style embedded.
  • The HTML page puts up a 3x3 table of 9 cells, each with a unique id. It also include a button for creating a new game.
  • The CSS define the presentation style for the HTML elements. A special class-selector called ".winningCell" is defined to change the background color of the 3 winning cells.
  • The init() function, which is the onload handler, resets the game variables and cell contents via resetGame(), and attaches the function resetGame() as the button's onclick handler. Take note that clicking the "New Game" button does not involve refreshing of the page (which requires a costly access to the server), but simply reseting all the game variables and cell contents.
  • We use window.onload=init to ensure that init() is run after the page is fully loaded, so as to access the elements defined in the page.
  • We define a global array WINNING_PATTERNS, to keep the eight 3-in-a-row winning patterns. Each pattern is a 9-bit number, with bit-x represents cell-x. For example, the binary number 000000111 indicates that cells 0, 1, and 2 are occupied. The numbers are expressed in octal with a leading zero. (JavaScript does not seen to support binary number with a leading 0b, like C/C++/Java.) Similarly, we define two global variables, crossPattern and noughtPattern to keep track of the crosses and noughts placed on the game board so far.
  • A boolean flag crossPlaying is used to keep track of the current player.
  • The resetGame() function resets the game variables (empty the crossPattern and noughtPattern and set the current player to "cross"). It also clears the contents of the cells, and attaches play() function as the onmousedown event handler, so that the user can click on the cell to play the game.
  • Whenever the user clicks on a cell, the play() event handler triggers with the mousedown event object as the argument. It first identifies the cell-clicked (with different methods for IE and non-IE browsers). It places the current player's symbol on the game board, and updates the player's pattern. It then calls the checkWin() to check if the current player wins the game. If not, it disables this cell by removing the onmousedown handler, and toggles the current player.
  • The chcekWin() function checks the current player's pattern against the eight winning patterns. If the current player wins, it highlights the three winning cells by changing the cells' class attribute. The CSS class-selector will automatically display the cell with a different background color. It also disables all the cells. User has to click the "New Game" button to start a new game.