Thursday, August 25, 2011

DDTe3 Hour 9 Twist puzzle

While it has been a while since the last post in this series due to a family tragedy, I am now back to posting weekly and am continuing my series of articles on the creation of Dozen Days of Tiles episode 3. This is a game in a day challenge in which instead of developing a game in under 24 hours (development time) I am instead seeing how many games can be created in 24 hours of development time. Today the creation of the twist puzzle is covered.
The twist puzzle takes a 2x2 block of tiles and rotates them counter-clockwise. The only new game mechanic revolves around the rotation of tiles, which can be handled using existing BasePuzzleModel classes. There are no changes needed to the view class making this is a very quick project. 

The game mechanic that needs to be implemented is a performTwist method. This could be done using three swaps as outlined in the following pseudo-code:
    swap x,y with x+1,y
    swap x+1,y with x+1,y+1
    swap x+1,y+1 with x,y+1

However this results in six tile moves. Because I already knew which game I was going to develop right after this one was finished, I decided to use a more efficient four-way swap as the next game in the series would be better able to utilize this code. Having long-term plans is always nice, even if they don't come to fruition they are giving you a path to follow.

PuzzleGallery.TwistPuzzleGame.prototype.performTwist = function(p)
   var temp = this.puzzle.getPuzzlePiece(p.x, p.y);
   this.puzzle.setPuzzlePiece(p.x, p.y, this.puzzle.getPuzzlePiece(p.x+1, p.y));
   this.puzzle.setPuzzlePiece(p.x+1, p.y, this.puzzle.getPuzzlePiece(p.x+1, p.y+1));
   this.puzzle.setPuzzlePiece(p.x+1, p.y+1, this.puzzle.getPuzzlePiece(p.x, p.y+1));
   this.puzzle.setPuzzlePiece(p.x, p.y+1, temp);

This still leaves the problem that tiles along the right and bottom edges are not valid to click on so the onTileClick callback method has to be slightly changed.

PuzzleGallery.TwistPuzzleGame.prototype.onTileClick = function(p)
   if (( p.x < (this.puzzle.puzzleWidth-1)) && (p.y < (this.puzzle.puzzleHeight-1)))

The game scrambling likewise needs to be changed. As with the sliding puzzle game, a scramble method that randomly selects a valid tile and performs a twist on that tile is all that was needed.

PuzzleGallery.TwistPuzzleGame.prototype.scramble = function()
   var p = new BGLayers.Point();
   var w = this.puzzle.puzzleWidth;
   var h = this.puzzle.puzzleHeight;
   var n = w * h * 10;
   for (var cntr = 0; cntr < n; ++cntr) {
       p.x = Math.floor(Math.random() * (w-1));
       p.y = Math.floor(Math.random() * (h-1));

While I try to focus on writing about the theory behind the code and try only to show the relevant bits of code, almost all the code that I wrote is in this article. Still, finishing a game in well under an hour (though I am still counting the time as an hour to simplify my time-keeping) is great.

No comments: