As a little exercise for using Animations in DukeScript, I’ve created a little sorting Game.
The aim is to sort 15 numbered tiles. You probably remember the mechanical version of this
game from your childhood. Here’s a description in Wikipedia.
And here’s what we’ll create in this blog post:
Positioning the Tiles with CSS
I’ll start with very little styling for a tile:
Nothing fancy here, tile position is absolute, and the Tile with id ‘tile-0’ is the empty space.
We’ll care about a nicer look and responsive design in another blog entry.
Now we need to set the absolute positions of the tiles:
I’ve only added ‘-webkit-transform’. If you want to run it in a non-webkit Browser,
you should also add “-moz-transform: translate(…px, …px);” and “transform: translate(…px, …px);’”
The View Model
Now we need to create the view model. We need a list of Tile Objects, and for
convenience we’ll store the empty tile separately. The tiles themselves have a
target position p, which is also the number displayed on the Tile, and the current
position. To make it easier to check valid moves in the grid I’ve split
the current position into an x ynd y coordinate.
The main “game logic” is in a single function called move that will be called
when someone clicks a Tile:
The function first checks if the Tile is valid (not the empty Tile), and then
if it is adjacent to the empty Tile. If so, positions are swapped.
Initializing the Game
Now we’ll initialize the Tiles in random order in the main method:
The View
That’s it for the View Model. What’s missing now is the HTML for the View:
We just iterate over the Tiles with a foreach-loop. Then we use data binding to
set the text (text: p), the id (attr: { id: ‘tile-‘+ p() }), the css class of the current position
( css: ‘tile-position-‘+ (y()+1) +’-‘+(x()+1) ) and we bind the click to the move method (click: $parent.move).
Now you can run the game and play it.
Adding Animations
But I promised you some animation. Now that part is a bit disappointing, because
we only need to add a single line in the CSS for the ‘tile’ class:
That’s it for this time. We’ve created a little game in just a couple of lines of code
and we added animations with a single line of CSS.
Stay tuned for the next part, when we’ll store the Games state locally on the device
and add a Function for resetting the game.
P.s.: Don’t be frustrated if you can’t solve the puzzle. When doing random shuffling
like we do, sometimes the puzzle is unsolvable. We’ll fix that also in the next blog.