JS Game: Creating a Simple Game Board in Javascript
A thorough knowledge of Javascript can give you tremendous control over what happens on a website. Combined with PHP through an AJAX request, you can make some pretty nifty browser-based games.
This tutorial will focus on the first part of making a basic board game – creating a board. The end result will be a three by three game board suitable for use in developing a tic-tac-toe game.
Game Development with JS, AJAX, and PHP
How can we use JS and PHP – connected through AJAX – to develop an online game?
Javascript’s main use for us is to create an interface for the game. Through Javascript we can capture user input – i.e. mouse clicks and text. We can also alter the game’s output – changing the HTML of the page, adding images, and moving things around. Javascript will provide a lot of the front end work.
PHP, on the other hand, is a more robust language for dealing with the logic of the game. PHP could be useful for developing an AI and evaluating winning conditions. It also offers a great way to store information for later use through flat files or database integration.
If we’re going to use both Javascript and PHP, we’ll need to use AJAX. This is the glue that holds the whole thing together. It will send input from the main Javascript to the PHP processing scripts. The PHP script will then send info back to the Javascript and it will alter the page’s layout accordingly.
Step One: Building a Game Board
The first step in creating a graphical online game is to build a game board. The most basic board I could think of – and therefore a good starting point – is a tic-tac-toe board.
First, we should define and create our basic building block. A square.
In terms of HTML/CSS, our square will be a div tag. We’ll be able to position and style it to our liking, and we can add javascript triggers like “onClick” to help run our Javascript.
Our first box is going to be a simple 50px x 50px square. When you click it, it will change background colors to black.
Here’s the CSS we’ll use for the square.
.box { width: 50px; height: 50px; border: thin solid black; }
Inside the html body we can create our box like this.
<div class="box" id="box" onClick="makeBlack();"></div>Finally, we need to define our Javascript function makeBlack(). We’ll access the div element through it’s ID (‘box’) and change it’s background style to be black.
function makeBlack() { var box = document.getElementById('box'); box.style.background = 'black'; }
Now we’ve got a building block! We just successfully used Javascript and DOM to create a click-able box. With some tweaking, we can turn this into a nifty 3×3 grid for Tic Tac Toe.
Step Two: Build a Grid
For Tic Tac Toe, we’re going to need a 3×3 grid. We can modify our CSS a bit and create 9 separate divs to accomplish this. Add the following lines to the CSS for .box, and create a new class .break.
.box { float: left; } .break { clear: bloth; }
This way our boxes line up in a row. If we include a “break” class in our div, we can start a new line. Therefore we should update the html like this.
<div class="box break" id="one" onClick="makeBlack('one');">1</div> <div class="box" id="two" onClick="makeBlack('two');">2</div> <div class="box" id="three" onClick="makeBlack('three');">3</div> <div class="box break" id="four" onClick="makeBlack('four');">4</div> <div class="box" id="five" onClick="makeBlack('five');">5</div> <div class="box" id="six" onClick="makeBlack('six');">6</div> <div class="box break" id="seven" onClick="makeBlack('seven');">7</div> <div class="box" id="eight" onClick="makeBlack('eight');">8</div> <div class="box" id="nine" onClick="makeBlack('nine');">9</div>
Notice that each box has it’s own unique ID – one to nine. I also changed the makeBlack() function to include a parameter – an ID. Let’s update the makeBlack() function to utilize this to change the specific box that we click on.
function makeBlack (boxId) { var box = document.getElementById(boxId); box.style.background = 'black'; }
Step Three: Use a Background Image Instead of a Background Color
Turning a box to a black background color isn’t that impressive. But it’s easy to use as a demonstration.
For a game, it would be much more useful to make an image appear in our div. We can do that by editing the “background” style of the div in the makeBlack() function. Note: You might also want to change the name of the function to something more descriptive, like changeBackground().
Here’s how to do it.
function changeBackground (boxId) { var box = document.getElementById(boxId); box.style.background = 'transparent url(image.png) top left no-repeat'; }
The property “box.style.background” accesses the “background” css style for the “box” id. Give it a value just like you would in a css stylesheet. In this case, we’re giving it a background of “image.png.” You might want to change this to a “circle.png” or a “cross.png” that you create for your game.
Step Four: Changing the onClick Event
The last thing we want to look at in this introduction is how to change the onClick event for our div. You might want to get rid of it altogether – or maybe change it to a new function. For example, after turning the box black, you might want to make the onClick call a new function – makeWhite().
We can do this through another DOM method, similar to the way we accessed the styles before. Assuming we have the same variable box that refers to our div, here’s what we need to do in our function.
// Get rid of onClick altogether box.removeAttribute('onClick'); // Change onClick to a new function box.setAttribute('onClick', 'makeWhite();');
Where To Go From Here?
Now that you’ve got a basic 3×3 grid and you know how to make it respond to user input, you can get started on making a game.
Here are a few of the things you’ll want to think about next.
- I need some images to place in my boxes.
- How Can I Alternate Players (and images)?
- How Can I Determine Who Wins?
- How Can I Make the Computer Play (AI!)?
You can go ahead and get started on your own – but I’ll certainly return to this topic within 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.
JS Game: Making a Real Game Board from a Concept | Web Cash said this on February 20th, 2008 at 11:09 pm
[...] 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 [...]
Creating a Simple JavaScript Game Board | Ajaxonomy said this on February 21st, 2008 at 12:44 am
[...] Read the full first tutorial here. [...]
objeraAllorge said this on February 22nd, 2008 at 11:46 am
Good
site.
Aaron said this on October 25th, 2008 at 8:15 pm
Thanks for the article. I’m having a problem getting the boxes into three rows. All I can get is one big row.
Cheers,
Aaron
Walkere said this on October 26th, 2008 at 10:22 am
Aaron,
Check that you gave the first box in each row the “break” class as well as the “box” class. The break class gives it the “clear: both” attribute, so that it should break and start a new line.
I initially used floating divs because it seemed simple enough, but there are some browser differences in how they are displayed. It may be better to use the position attribute to array them inside a larger div, guaranteeing that they appear just the way you want them.
writillotHe said this on December 17th, 2008 at 7:09 pm
Hi all!
As a fresh http://www.earn-web-cash.com user i just wanted to say hi to everyone else who uses this board
Quoryrare said this on December 27th, 2008 at 10:16 pm
Hi, just saying a blated hello
JoRDANA said this on February 4th, 2009 at 8:09 am
can you help me? I don’t know whay should i do
i dont noob!
AlexStivenson said this on February 14th, 2009 at 9:37 pm
How you think, in our situation whis crisis its actual?
boobEdids said this on February 27th, 2009 at 4:50 am
Продаются земельные участки от собственника
20-25 соток, от 100.000 руб за сотку
Назначение – ИЖС, без подряда
70 км от МКАД, Чеховский район (Симферопольское ш.), р.Лопасня
Заказать показ участка можно по телефону (495) 967-5678
government_cash_grants_bcl said this on April 23rd, 2009 at 10:40 pm
So I have been looking at all these get government grants web pages and I would like to get all your opinions on them…
Do they work?
Does anyone know someone that got one?
I am currently going a blog series about the government grant, and certainly can use any help I receive!
чyпи said this on May 23rd, 2009 at 12:39 am
Удачи вам! Я думаю у вас все получится
Javascript Gaming: Making a Game Board - Tutorial Collection said this on June 7th, 2009 at 3:36 pm
[...] View Tutorial No Comment var addthis_pub=”izwan00″; BOOKMARK This entry was posted on Monday, June 8th, 2009 at 2:10 am and is filed under Javascript Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. [...]