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';
}
1
2
3
4
5
6
7
8
9
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.

Bookmark and Share:
  • Digg
  • Furl
  • del.icio.us
  • StumbleUpon
  • MisterWong
  • DZone
  • Technorati

Tags: , , , , ,

33 Comments to “JS Game: Creating a Simple Game Board in Javascript”

  1. JS Game: Making a Real Game Board from a Concept | Web Cash said this on

    [...] 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 [...]

  2. Creating a Simple JavaScript Game Board | Ajaxonomy said this on

    [...] Read the full first tutorial here. [...]

  3. objeraAllorge said this on

    Good
    site.

  4. Aaron said this on

    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

  5. Walkere said this on

    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.

  6. writillotHe said this on

    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 :-D

  7. Quoryrare said this on

    Hi, just saying a blated hello ;)

  8. JoRDANA said this on

    can you help me? I don’t know whay should i do
    i dont noob!

  9. AlexStivenson said this on

    How you think, in our situation whis crisis its actual?

  10. boobEdids said this on

    Продаются земельные участки от собственника
    20-25 соток, от 100.000 руб за сотку
    Назначение – ИЖС, без подряда
    70 км от МКАД, Чеховский район (Симферопольское ш.), р.Лопасня
    Заказать показ участка можно по телефону (495) 967-5678

  11. government_cash_grants_bcl said this on

    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!

  12. чyпи said this on

    Удачи вам! Я думаю у вас все получится :)

  13. Javascript Gaming: Making a Game Board - Tutorial Collection said this on

    [...] 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. [...]

  14. Flibly said this on

    72]Free Ringtones!

    http://fastloannow.ru/ringtones/ringtones-6.jpg

    72]Download Ringtones!

    totally free boost mobile ringtones
    no mercy ringtone
    alltell cell phone ringtone
    free polyphonic cellphone ringtones
    motorola star wars ring tones
    free ringtones for samsung instinct
    forum free ringtones
    futuristic ringtone
    ringtones hearing impaired
    legend ringtones

    Sprint Pcs Ringtone Sanyo
    Bob Sheppard Derek Jeter Ringtones
    Free Samsung A800 Polyphonic Ringtones
    Cingular Razr Ringtone
    Stars Go Blue Ringtone
    Free I95cl Ringtones
    Free Ringtone And Graphics
    Waves Ringtone Motorola
    Tmobile Twisted Nerve Ringtone
    Free Polyphonic Ringtones Motorola C332
    Liam Lynch Ringtones
    Mobile Phone Ringtones Midi
    Free Ringtones For Cricket Communications
    Tmobile Togo Ringtones
    Free Ring Tones For Nokia 3586i
    Cell Phone Ringtones For 2pac Shakur
    Christian Ringtones Sweden
    Ringtones To My Computer
    Rave Ringtones Free Kyocera
    Simple Freedom Ringtones For Nokia
    Ringtones For Us Cellular Prepaid Phones
    Online Ringtone Maker
    Free Ringtone For Alltel User
    Hedwig’s Theme Ring Tone
    Free Mmf Polyphonic Ringtones
    Real Free Katt Williams Ringtones
    Nextel Rocky Top Ring Tones
    Ringtone Chile
    Country Cellphone Ringtones
    Free Ringtones For Ut Starcom Slice
    Cracked Iphone Ringtones
    Lg 1300 Ringtones
    Verizon Phones Ringtones
    Danger Will Robinson Ringtone
    Wheel Of Fortune Ringtone
    Northern Exposure Downloadable Ringtone
    Boost Mobile Ringtone I285
    Add Ringtones To Verizon Voyager
    Sprint Ringtones Com
    Gilmore Girls Ring Tones
    Ringtone Payday Cash Advance Cashpool Safetys
    Cingular Razr Ringtone
    Say Ok Ringtone
    Free And Long Mosquito Ringtone
    Union Underground Ringtones
    Free R220 Ringtone Samsung
    Army Motorolla Ringtones Free
    Free Ringtone Txt Community
    Cellular One Free Mp3 Ringtones
    Hockey Ringtone
    Siemens Cellular Phone Ringtone
    Free Sprint Sanyo Music Ringtones
    Mobile Nokia Phone Ringtone
    Composing Siemens A50 Mobile Phone Ringtones
    Sprint Madonna Ring Tones
    Polyphonic Ringtone For Sprint
    Free Ringtones And Nokia 3586i
    Free Ringtones No Pay
    Fleetwood Mac Ringtone
    Telus Ringtone Block

    lg ringtones florida gators
    ncis phone ring tone
    top ringtones top ring tones
    how do you get free ringtones
    free cd ripper ringtones edtiors
    1100 tamil ringtones
    panasonic kx-tg5583 ring tones download
    country hi fi ringtones
    rich mullins if i stand ringtone
    how to sell ringtones on myspace
    free bollywood cell phone ringtones
    free nextel i730 polyphonic ringtone
    savage and swing and ringtone
    nokia 1100 free keypress ringtones
    free ring tone for verizon wireless
    tv 24 ringtone
    sending tmobile ringtones
    web graphics christian free ringtone
    free music ringtone for nextel 710i
    ringtones cow mooo
    version wireless lg ring tones
    randy orton ring tone
    motorola ringtones free mototola ring tones

  15. Audrey Phillips said this on

    every girl on Gilmore Girls is pretty. i kind of admire them and have a great crush.-.:

  16. Victoria Young said this on

    I just thought that NCIS is a copy cat of CSI.:’”

  17. Taylor Lewis said this on

    the cast of Gilmore Girls are very pretty, i wish i could marry one of them.,;`

  18. Finlay Richardson said this on

    i think NCIS is much better than CSI because they solve much harder cases.;.;

  19. Maya Brooks said this on

    well, what can i say, the girls on Gilmore Girls are just damn pretty.`.

  20. Arianna Torres said this on

    NCIS is much better than CSI in my own opinion, it has more drama and twists on the story***

  21. Carli Abegg said this on

    indian movies are now facing another steps for depression . just look at it on http://www.indianmovieshows.com

  22. Kitchen Cupboards  said this on

    NCIS is much like CSI but there is more action and drama in it~.”

  23. RFID Chip : said this on

    ther are lots of free ringtone sites on the internet if you just keep on searching on google’`-

  24. Floating Shelves · said this on

    most of the best ringtone sites are pay sites, does anyone know of a good free ringtone site? `’.

  25. Hemorrhoid Treatment said this on

    the Gilmore Girls are really gorgeous, and that is the main reason why i watch that tv show ~~”

  26. Anti Aging Products said this on

    i love to watch NCIS, the story is great and i love the special effects too `;;

  27. Rosena Hibbs said this on

    Some days ago I discussed that matter with one other guy just with a different result. It s a topic challenging for discussions again and again. Nice points you took into consideration for argumentation

  28. phicyfeefly said this on

    почему я не худею

  29. swarni said this on

    Loving the info on this web site , you have done outstanding job on the blog posts.

  30. Business Cash Flow Loan said this on

    Great article, I’ve bookmarked this page and have a feeling I’ll be returning to it frequently.

  31. bir cocuk sevdim dizisi said this on

    dy as an app, which is a great start, but it i

  32. Collin Lafoe said this on

    Everyone loves it when we bond along with reveal viewpoints, superb weblog, thanks.

  33. Bennett Reitmeyer said this on

    Odd , this page shows up with a black color to it, what color is the primary color on your webpage?

Leave a Reply