iio.js Tic-Tac-Toe Tutorial

This tutorial shows how to create a simple interactive game with JavaScript, HTML5, and iio.js.

Setup

If you want a local copy of iio.js, download the iio.min.js build file. You can get that file here or get it on Github.

Otherwise, you can load the file from the web:

"http://iio.js.org/iio.min.js"

Initialize the App

Create a new HTML file called TicTacToe.html in a folder with the iio.min.js JavaScript file.

Open the HTML file in a text editor and input this code:

<!doctype html>
  <body>
    <script type="text/javascript" src="iio.min.js"></script>
    <script type="text/javascript">

        TicTacToe = function( app ){

          // application code...

        }

        // start TicTacToe fullscreen
        iio.start( TicTacToe );
    
    </script>
  </body>
</html>

This code defines an HTML document, loads in iio.js, then opens up the script area where the application can be programmed.

TicTacToe is a main application function containing code to run with iio.start which creates or takes control of a canvas element.

Let's start by adding a grid. We can use iio's QuadGrid class and add it to the app for quick results.

Put the following code where the "application code" comment is:

// change the background color to black
app.set({ color: 'black' });

// add a 300px 3x3 grid to app center
var grid = app.add( new iio.QuadGrid({
  pos: app.center,
  color: 'white',
  width: 300,
  lineWidth: 10,
  R:3,
  C:3,
}));

var grid - a variable to associate with the QuadGrid object.

add - an app function that adds an object to its management system and draws it on the view.

In order to let players place Xs and Os, we'll need to know when the grid is clicked.

All iio objects have an onClick handler that we can assign for this purpose. QuadGrid also has access to an extended Grid.onClick function that returns the grid cell that was clicked

Put this code after where the grid has been created.

// handler called when the grid is clicked
grid.onClick = function( obj, event, pos, cell ){

  // input handling code...

}

event - a JavaSctipt Event object

pos - the position of the click, relative to app 0,0

cell - the cell object of the grid that was clicked