JS Game: Making a Real Game Board from a Concept
In a recent post, I sketched out how to use Javascript to build a gameboard for a browser-based game - specifically Tic Tac Toe. After a little tweaking, I’ve worked this into a functioning Tic Tac Toe board.
In this post, we’ll explore the code used to set up this board. Once that’s done, the next step will be to create a php script to evaluate some of the game’s logic.
Recap: The Game Board Concept
First, let’s take a step back and recap our Javascript game board concept.
The basic building block of our game board is a div element. This div element is styled with a CSS stylesheet - 50px by 50px. By using floats and clearss strategically, we can stack 9 of these div elements into a 3×3 box.
Javascript is added to make these boxes functional. An “onClick” handler is used to call a Javascript function that changes the background image of the div. This effectively marks the square as either a “Circle” or “Cross” for Tic Tac Toe.
To alter the div - and also to add textual output - we’ll be using Javascript’s powerful DOM functions. These allow us to grab a specific element by it’s ID and change it.
Creating Graphics
I created two images in Inkscape to use for this board. Each is a 50×50 png file - with a gray background and a black border. The actual token (the circle or cross) is red and laid on top of the gray background.
I’m no great artist, but these should work for a functional demo. We can worry about making nice circle and cross tokens later. I think getting the game working is more important than making it pretty from the get-go.
Turning Our .js Script into a Class
In making this a functional board, I also converted the script into an actual class. The script may end up being somewhat large and unwieldy - and an object oriented approach may help us keep it tidy and clean. Or it may add a lot of overhead… but I like objects.
In our HTML file, we’ll create the object like this.
<script type="text/javascript"> var tictactoe = new game(); </script>
In the attached .js file, we actually define the game object. Here’s part of the object definition.
function game() { // Array to hold the bgImgs this.bgImgs = new Array(); this.bgImgs[0] = 'tttcircle.png'; this.bgImgs[1] = 'tttcross.png'; // Player information this.currentPlayer = 0; this.players = new Array(); this.players[0] = "Player One"; this.players[1] = "Player Two"; return true;
This class constructor does some of the initialization for us.
First, it creates an array with background images. At the moment we’re only using two images. However, this technique would be useful if you had a more complex map - with 10-15 images you could lay over a div.
Second, we create some player information variables. The ‘currentPlayer’ property is going to track whether the ‘cross’ or ‘circle’ player is currently taking a turn. The ‘players’ array will just hold the names of those players for now.
The Background Image Changing Function
One of the major methods of this class will be changeBackground(). Just like in the previous example, this method will change the background style of a given div tag. This way we can change it from an open square to a circle or cross token.
this.changeBackground = function (boxId) { var box = document.getElementById('box-' + boxId); box.style.background = 'transparent url(' + this.bgImgs[this.currentPlayer] + ') top left no-repeat'; box.removeAttribute('onClick'); this.changePlayer(); }
This should be pretty straightforward. We’re storing the ‘div’ element in the ‘box’ variable. We’re then setting the ‘background’ style as we would in a css style. Remember that we stored the background images in an array (this.bgImgs) and this.currentPlayer corresponds to a key in the this.bgImgs array (either 0 or 1).
The ‘box.removeAttribute()’ method is removing ‘onClick’ from that div. We can’t use a square a second time, so we might as well eliminate the onClick handler altogether.
Finally, this.changePlayer() is calling a new method. This is going to help us switch from Player One’s turn to Player Two’s turn.
One Turn to Another - this.changePlayer()
The last method we need to declare for this class at the moment is changePlayer.
This will toggle the active player - which in turn affects whether a circle or cross is placed on the board. For some added effect, we’ll also create a new html element to display a message that says who’s turn it is.
this.changePlayer = function () { // Switch the active player if (this.currentPlayer == 0) { this.currentPlayer = 1; } else { this.currentPlayer = 0; } // Get a reference to our 'message' element and create the message var box = document.getElementById('message'); var msg = "It is " + this.players[this.currentPlayer] + "'s turn."; var txt = document.createTextNode(msg); // Erase any existing text while (box.hasChildNodes()) { box.removeChild(box.lastChild); } // Add the text node (our message) to our element box.appendChild(txt); }
Again, this is pretty straightforward. The DOM functions are amazingly simple - once you see how they work.
‘box’ is a reference to our element (id = message). The msg variable is a temp variable I created to hold the string. The ‘createTextNode’ method creates a new block of text (with our msg) that we can then insert into an HTML element.
The while() loop is simply there to erase any old text. As long as our ‘box’ element has any child nodes inside of it (text or other HTML tags), the loop will execute and delete one of those child nodes each time. This way we have a clean slate on which to write down who’s turn it is.
Seeing It In Action
Well, that’s really all there is to it. Have a look at this functioning demo. If you had trouble piecing together the example code, you can download the source files (.js, .css, and two .png) from the list below.
Good luck, and be sure to check back soon. Our next task is going to be a real challenge. We need to add some logic to this game - evaluating victoary conditions and creating AI!
Source code files:







JS Game: Creating a Simple Game Board in Javascript | Web Cash said this on February 21st, 2008 at 5:06 pm
[…] the next week or two with some more examples. After the next tutorial, we’ll have a working Tic-Tac-Toe board driven solely by Javascript. Bookmark and Share: These icons link to social bookmarking sites where readers can share and […]
Imargeovere said this on April 10th, 2008 at 10:00 pm
Hello my friends
