Karla News

Designing Web Games with Javascript, PHP, and AJAX

DIV, Tic Tac Toe

Javascript’s DOM functions give you powerful control over the display of a website. With a deep understanding of DOM, you can dynamically re-create a website as if it were a blank canvas. If you were so inclined, you could use these skills to build a browser-based game.

Approaching the Javascript Game: How Do the Parts Fit Together?

Before you dive in to a project like this, it helps to understand how the individual parts will fit together. What programming skills are you going to need to build a browser-based game run by Javascript and PHP?

Javascript is a perfect option for the interface. You can rig elements to capture input – mouse clicks, button presses, etc. This input can then be used to dynamically alter the face of the site – redrawing the game’s canvas.

A PHP script would be better suited for handling the logic of the game. You could use this to interface with files or a database (for game saving), evaluating victory conditions, and programming an artificial intelligence. This also shields some of your code from the viewer – so they don’t know what the answer is to the quiz show, or what the computer is going to do next.

Finally, you need a way to join the Javascript and the PHP. The solution? AJAX. After your script captures some input, it fires off an AJAX request to the PHP script and then uses the response to determine how to alter the output.

If you’re unfamiliar with some of these things, check out this list of AJAX and DOM resources. You can also check out some of these PHP Tutorials for guidance in that direction.

See also  Detailed Information on Different Types of 1099 Forms

Where to Start? Building a Tic Tac Toe Board

A good first project would be to build a Tic Tac Toe board. It’s a simple visual design, the choices are limited enough to make an AI possible, and the user-input is fairly straightforward.

How should we design a graphical interface for this? Using HTML and CSS, we can build our board out of div tags. Each div is a square with a fixed height/width. These are then stacked into a 3×3 board using floats and clears where needed.

Each div can have a javascript function attacked to its onClick attribute. This calls a piece of Javascript to give it a certain background – therefore marking it as circle or square. Here’s a good article about the idea behind this type of Javascript game board.

To finalize the functionality, you’ll have to add some logic to your Javascript. It should track the current player – which determines which background image (circle or cross) is added to the div. You can also use some more DOM trickery to add a message to the user – printing the current player’s term.

You could dive right in and try to develop this yourself, or check out this example script with working game demo.