blog

  • Home
  • blog
  • Practical CoffeeScript: Making a Tic-Tac-Toe Game

Practical CoffeeScript: Making a Tic-Tac-Toe Game

CoffeeScript is a tiny little language that compiles to JavaScript. There is no interpretation at runtime since you write CoffeeScript, compile it to JavaScript and use the resulting JavaScript files for your app. You can use any JavaScript library (e.g. jQuery) from within CoffeeScript, just by using its features with the appropriate CoffeeScript syntax. CoffeeScript can be used both for writing JavaScript on the front-end and JavaScript on the back-end.

So Why CoffeeScript?

Less Code

According to the Little Book on CoffeeScript, CoffeeScript’s syntax reduces the amount of characters you need to type to get your JS working by around 33% to 50%. I will be presenting a simple Tic-Tac-Toe game created using CoffeeScript (you probably already guessed this from the title) which in its raw CoffeeScript format contains 4963 characters, whereas the compiled JavaScript code contains 7669 characters. That is a difference of 2706 characters or 36%!

Faster Development Time

Because you write shorter, less error-prone (e.g. variables are auto-scoped, meaning you can’t accidentally overwrite globals by omitting var) you can finish your projects quicker. CoffeeScript’s terse syntax also makes for more readable code, and ultimately code which is easier to maintain.

Getting Started

In this article, we will be building a simple Tic-tac-toe game with CoffeeScript and jQuery. If you want to read up on the syntax before examining a practical case, I suggest my Accelerate Your JavaScript Development with CoffeeScript article here at SitePoint. This also details how to install CoffeeScript via npm (the Node Package manager).

As ever, all of the code from this tutorial is available on GitHub and a demo is available on CodePen or at the end of the tutorial.

The most common CoffeeScript commands you will be using are:

coffee -c fileName will compile the CoffeeScript file to a file with the same name but with a .js extension (CoffeeScript files typically have .coffee extension).

coffee -cw fileName will watch for changes in a file (whenever you save the file) and compile it.

coffee -cw folderName/ will watch for changes to all .coffee files in the folder and compile them in the same directory when there are any changes.

Finally, it is handy to compile CoffeeScript from a folder with .coffee files to a folder containing only .js files.

coffee -o js/ -cw /coffee will watch for changes in all .coffee files located in the coffee folder and place the output (JavaScript) in the js folder.

If you are not into terminals, you can use a tool with a GUI to handle your CoffeeScript files. For instance, you can try Prepros on a free unlimited trial (although you have to buy it if you like it). The image below shows some of the options it provides:

Screen shot of Prepros

You can see that Prepros does all the work for you—it sets up watchers so your .coffee files will be compiled to JS, it allows you to use Uglify JS which will minify/compress your code, it can automatically mangle variables and it supports Iced CoffeeScript. Prepros can also be used for CSS preprocessors such as Less and Sass and template engines like Jade.

The Game

Let’s start with the markup:

[code language=”html”]

Tic Tac Toe




[/code]

The game’s interface consists of the following:

  • A header which briefly describes the game
  • A div element with the id of board which is where the 3×3 squares will be located
  • A div element with a class of alerts which is where the game status will be shown
  • A div element with a class of notifications which will show who is playing X and O, along with the general player statistics.
  • A form which will be displayed only when the game loads and will prompt the players to enter their names.

In accordance with best practice, both jQuery and the script that makes our app tick are loaded before the closing body tag.

The Styling

Using CSS, we can make the nine squares involved appear in a 3×3 grid by floating each square and clearing every 4th one.

[code language=”css”]
.square:nth-of-type(3n + 1) {
clear: both;
}
[/code]

We can also add a different color to the squares depending on whether they have the class x or o (which is added using JavaScript).

[code language=”css”]
.square.x {
color: crimson;
}

.square.o {
color: #3997ff;
}
[/code]

CoffeeScript in Action

Fore reference, you can find the main CoffeeScript file here.

You can see our Tic-Tac-Toe app starts with $ ->, this is equivalent to the shorthand for jQuery’s function that executes code when the DOM is ready: $(function() { ... });.

CoffeeScript does not rely on semicolons and braces but on indentation. -> tells CoffeeScript that you are defining a function so you can start the body of the function on the next line and indent the body with two spaces.

Next, we create an object called Tic which itself contains an object called data. You can see that braces or commas are not obligatory when creating objects, as long as you indent the properties correctly.

[code language=”js”]
$ ->
Tic =
data:
turns: 0
x: {}
o: {}
gameOver: false
[/code]

The turns property will hold the total number of turns taken in the game. We can check whether it holds an even or uneven number and in that way determine whether it is the turn of X or O.

The x and o properties are objects and will contain data relating to the number of X’s or O’s on the three axes that are important for the game: horizontal, vertical and diagonal. They will be updated on every move through the checkEnd method to represent the distribution of X and O on the board. The checkEnd method will then call checkWin to determine if there is a winner.

After that we have a method inside the Tic object that will get everything up and running:

[code language=”js”]
initialize: ->
@data.gameOver = false
@.setPlayerNames()
@.retrieveStats()
@.assignRoles()
@.prepareBoard()
@.updateNotifications()
@.addListeners()
[/code]

Notice the use of @ which compiles to the JavaScript keyword this. As illustrated in the first property of initialize, you can skip the dot after the @ keyword when setting or calling a property or method.

By giving the methods sensible names, we have a fair idea of what they are doing:

  • setPlayerNames stores the values entered by users in the inputs into the data object.
  • retrieveStats retrieves the player’s statistics from localStorage and sets them up in the data object.
  • assignRoles determines who is playing X and who is playing O.
  • prepareBoard hides the form, removes any notifications, empties the board and fills it with nine empty squares.
  • updateNotifications updates the UI with information about who is playing X and who is playing O, as well as the player’s statistics.
  • addListeners attaches the event listeners, so that we can respond to players making a move.

Continue reading %Practical CoffeeScript: Making a Tic-Tac-Toe Game%

LEAVE A REPLY