Showing posts with label Algorithm. Show all posts
Showing posts with label Algorithm. Show all posts

Thursday, September 11, 2014

Understand the complexity of the Rubpix game



It took me about 2 weeks to complete the Rubpix puzzles of the dimension 3x3 and 4x4 (the first 100 level), with the best move solutions. However, I immediately realize that it would probably take months to complete the rest - 6x6 and even 8x8. Why?

At first sight, this Rubpix game is indeed deceptively simple, with simply Up, Down, Left and Right movements. For the first few puzzles, you may find them solve-able, as long as you make some additional movements. However, after considering the possible sample sizes more seriously, you will immediately realize that the complexity of these kinds of puzzles has the potential to grow exponentially!
 
To start with a simpler picture, let's consider the simplest form of the Rubpix game - 3x3. Here, assume that there are 9 unique colors in the puzzle (worst case scenario), with some high school maths, you will come out with an answer that it has basically a total of "9 factorial" permutations - aka 362880 patterns! Yep. You are seeing it right - MORE THAN 300 thousands! In a worst case scenario, the solution of the puzzle could be only obtained after a total of 300 thousands moves! (with a naive move)

Of course, the developer of the Rubpix game isn't that brutal. Most of the time (from observation), the unique colors of the puzzle are usually lesser than 6. Hence, with some human's non-naive filtering, the answer can still be found after not more than 50 moves (Alright, if you take more than that, something is really wrong).


Now, back to the harder question. What if it is a puzzle of 6x6 (not to mention, the horrible 8x8 as well). Taking the example of the Rubpix puzzle Level 101, it has 36 blocks with six unique colors. So... can you guess how many unique permutations are there? There are MILLIONS! Playing this kind of game naively would claim your life!

Anyway, I will only play the rest of the Rubpix puzzles when I am free. If you have solved all of them, you have my respect!

Wednesday, May 7, 2014

Block Puzzle 2 - Another Block Puzzle Game

Hey, don't forget that I am an Android Game developer as well. After posting so so much solutions about the Ultimate Block Puzzle, I am inspired to create another block puzzle myself - Block Puzzle 2.


First, it is NOT just a duplication. In fact, to add more variations in the block puzzle game, I specifically added a new mode - Special Mode, in which the grey regions are not a rectangular shape.

It takes about 1 week. And here shows the challenges of making the block puzzle game.


Time-consuming on the Block Puzzles generation


The block puzzle game usually contains hundreds of puzzle. In each puzzle, it has 5 to 12 block pieces to drag and drop. The challenges are to create unique levels for different modes. In fact, I really wonder how much time the original game takes in order to generate more than 6000 block puzzles. Is that an algorithm for that? Generating one by one is gonna claim your weeks or months!

Should the solutions of the block puzzles be made unique?

I believe this is a great challenge. Of course, to make the puzzle game more complicated, somehow the uniqueness of the puzzle solution is critical. However, this requirement poses another question - How to ensure that the solutions are unique? If you have played the original Ultimate Puzzle game, you might observe that there is only single solution for each puzzle. Hence, sometimes you might get mad when your solution is so closed but is still not successful.

Here, this is another difference between the Ultimate Puzzle and my Block Puzzle 2. In my game, you may come across some puzzles that could be solved in several ways, probably due to the symmetrically arrange-able blocks.

Anyway, hope you can enjoy this block puzzle game, and feel free to drop any comment.

Sunday, February 23, 2014

Flappy Bird Algorithm Part 4 - An Android Game Demo (Floppy Balloon)

With the previous Flappy Bird Game Algorithm, I believe you would be able to come out with something similar.

So, here is my published version of the Flappy Bird - Floppy Balloon.

In the Floppy Balloon, i have made the game relatively simpler. And there are 2 modes: Easy and Hard. In the Easy mode, the forward speed of the balloon is slower, and the interval of the obstacles is longer, and you only get 1 score after going through 1 barrier. While in the Hard mode, the pace is increased and you will be rewarded 2 scores for each obstacle that you go through.



Again, to remind that there is a need to perform a 'one-time-only' installation of the latest Adobe AIR app.

Any feedback is welcome~


Thursday, February 20, 2014

Flappy Bird Game Algorithm Part 3 - Collision Detection

So far we managed to make an object flying smoothly with the adjustable gravity and the forward speeds.

Next, it comes the major part of the game: Obstacles generation and Collision Detection

Note that the obstacles (tunnels/pipes) can be generated in the similar ways as the background movement. Now the thing is, how to know if our flying object hits them?

To put it in a better picture, let's have a look at the analogy below:


Here, to investigate whether the object hits both the pipes (upward and downward), it is to check  whether the object is not successfully contained 'inside' the green box region (on the right side).

With this understanding, we only require a few information to complete the task:
a) Coordinates of the flying object + its Width and Height
b) Coordinates of the green box region  + its Width and Height

Luckily, the Width and the Height of the object and the green box are constants. All we need to perform, is a fundamental collision checking, as shown in the function below (Again, it is inside the onEnterFrame function):

public function collisionDetection(_obj1:FlyingObject, _obj2:GreenBox):Boolean
{
     //*Note that my flying object is pivoted in the center
     //check if it is within the pipes
     if(
_obj1.x + obj1.width/2 >= _obj2.x &&
        _
obj1.x + obj1.width/2 <= _obj2.x + _obj2.width)
     {

         //hit upper pipe
         if( _
obj1.y - _obj1.height/2 <= _obj2.y)   return true;
           
         //hit lower pipe
         if( _y1 + _
obj1.height/2 >= _obj2.y + _obj2.height) return true;
     }

}

Straightforward enough. Hopefully with these ideas, you can design and customize the Flappy Bird Game in anyway you want.

Next : Flappy Bird Game Algorithm Part 4 - An Android Game Demo (Floppy Balloon)

Flappy Bird Game Algorithm Part 2 - Background movement

With the ability to make the gravity, now let's enable the background movement.

Just FYI, in the Flappy Bird Game (or any spaceship game), it is the background that moves at the opposite direction which causes the illusion that the main object is flying. It is the typical way of creating such an effect.

Here, i am taking a Super Mario-like background image from here. To make it move smoothly at the back, we need at least 2 background images, which i crop the originals into 2 pieces, as shown below (bg1 and bg2):

Bg1 and Bg2, each pivoted at the top left red point.

At the beginning, the first part of the image (bg1) is shown (filling the device), while the second part (bg2) is placed just after the first image.

Then, with the Event.ENTER_FRAME again, both background images are moved slowly to the left. When the bg1 is completely vanished from the screen, its location (x) is moved to the end of the screen again. The same process is repeated to the image bg2 as well. And the entire process is looping forever.

Not surprisingly, in the onEnterFrame function of the background object, the function is as brief as below:

private function onEnterFrame():void
{
      this.x -= GamePlay.GAME_SPEED;
           
      if(this.x < -
DEVICE_WIDTH)   this.x = DEVICE_WIDTH;
 }

Next: Flappy Bird Game Algorithm Part 3 - Collision Detection

Wednesday, February 19, 2014

Flappy Bird Game Algorithm Part 1 - Gravity and flying



Normally, to create the games involving Physics (eg: gravity), the use of Physics Engine such as Box2D would be a boost for complicated run-time computations. However, in the Flappy Bird game, since the only requirements are to:
  • Make the bird fly upwards while touching
  • Make the bird fall while not flying (with gravity)
the algorithms could be performed easily with few lines of codes without Box2D.

Here, to remind, I am using AS3, Starling Framework and a latest version of Adobe AIR (4.0).

First, I am taking the advantage of Event.ENTER_FRAME to allow the flying object to animate/fly on each frame. In the onEnterFrame function, a gravity is implemented. At the same time, we allow the player to touch any space on the device to activate a 'jump'.

private const UPWARD_SPEED:int = 5;
private const MAX_FLOOR:int = 800; //an indication that it hits the ground
private const GRAVITY:Number = 0.5;
private var objFlying:FlyingObject = new FlyingObject();//and addChild
private var speed:Number = 0; 
private var isJump:Boolean = false;
private function onEnterFrame(e:EnterFrameEvent):void
{
     if(isJump)
     {
         speed = -
UPWARD_SPEED; //negative relative to the normal gravity
         isJump = false; //once a jump is activated, we disable the flag
     }
     speed += (
GRAVITY); //physics ya, the speed is affected by gravity
    
objFlying.y += speed;
           
     if(
objFlying.y > MAX_FLOOR) //if it hits the wall
     {
         speed = 0;
        
objFlying.y = MAX_FLOOR;
     }  

}

private function onTouch(e:TouchEvent):void
{
     ...
     var touch:Touch = e.getTouch(stage);
               
     if(touch.phase == TouchPhase.BEGAN)
     {
          isJump = true; //a touch enables a slight jump
     }   

}

Note that the upward speed, gravity and the floor location are tunable according to your needs. With the Event.ENTER_FRAME, the animation is an easy job.

Next: Flappy Bird Game Algorithm Part 2 - Background Movement

How to create the game like Flappy Bird?


Flappy Bird, another popular game based on the 'simplicity', topped the chart not only in the Apple App Store, but also the Google Play Store before it was removed.

From the perspectives of the game play experience, the Flappy Bird is designed to challenge the consistency of the distance judgement of the players, with very high accuracy. Only 1 Hit Point, one highscore and infinite tries, no Mana Point, no magic, no checkpoint, no multiplayer.

From the views of the game development, the Flappy Bird simply relies on the gravity for the movement, and a simple collision detection while the background is moving at a linear speed.

To be honest, I have no idea why this game becomes so popular, other than the 'simplicity'. And yes, after the tutorial on the Match 3 Game last time, here i would like to create this similar game myself, out of the curiosity. To summarize, i divide the game algorithms into several parts:

a) Flappy Bird Game Algorithm Part 1 - Gravity and flying
  •  Alright, no box2d or other libraries. Only a few lines of codes will do.
b) Flappy Bird Game Algorithm Part 2 - Background movement
  • Is trivial as well. Just need a good image.
c) Flappy Bird Game Algorithm Part 3 - Collision Detection
  • A simple algorithm used to detect the collision of the object with the tunnels/walls.
d) Flappy Bird Game Algorithm Part 4 - An Android Game Demo
  • Apart from the basics, let's demo a self-customized version
Note:
  • I would be using other images to replace the original Flappy Bird.
  • The game requires the Adobe AIR 4.0. You need to upgrade it if prompted.

Saturday, January 4, 2014

Workaround for adjusting image brightness in the Starling Framework

In the Starling Framework, there isn't a property of 'brightness' for the Image Class. As a result, there is no straightforward approach when adjusting the image brightness.

However, we tend to have the feature of image glowing or flickering to attract the users, especially in the games. How to achieve the effects? Fortunately, with the understanding of the onEnterFrame function, there is a simple workaround here.

First, you need to define another class (extending Sprite) in which the images (that you want to flicker) are added. Here, ONLY 2 images are required: a normal image and a brighter image of the identical objects, as shown below:




Then, inside the onEnterFrame function, all you need to do, is to add a harmonic function (sine, cosine or tangent) to adjust the transparency (alpha) of the either one image, as stated here:

      public const FLICKER_FREQUENCY:int = 1000;
      public var yourImage1:Image = new Image(...);
   public var yourImage2:Image = new Image(...);
   
   private function onEnterFrame():void
   {
        var curDate:Date = new Date();
        yourImage.alpha = (Math.cos(curDate.getTime()*(1/
FLICKER_FREQUENCY)));
   }

Simple enough. You can adjust the flickering frequency at any rate you want :)

Wish to see a real example? There you go. The effects of adjusting the image brightness is applied in my Match 3 Pop Saga game. The flickering balloons are formed when you perform matching of 4 balloons in a row.

Sunday, December 29, 2013

Match 3 Game algorithm Part 6 - A real Android Match 3 Game demo

Sorry for the late. The release date for the Match 3 Game as stated last time might be delayed a bit.

HORRAY! The Match 3 Pop Saga is now available in the Google Play Store Now!



After several weeks of hard work, i have finally come out with a 'sample' of the Match 3 Game, with the Candy Crush Saga as the main reference, and the algorithms stated previously. (The "Saga" is imitated to gain some SEO points, hopefully... oops)

However, different from the Candy Crush, my Match 3 Pop Saga only has a total of 9 stages. Furthermore, it includes a bit of RPG elements: Level up. Basically, the more you play (popping more balloons), the higher levels you are. And the higher levels will reward you a higher score per pop (and time too!). Interesting huh? :)


Note that it is a balloon, not a colorful Easter egg.
I am not a graphic designer. The pictures are obtained from devianart.

Something to note is that, the 'striped candy' now is a glowing balloon (right, simple animation), while the 'wrapped candy' is something like this (bordered):

The maximum level in the Match 3 Pop Saga is 15 (which i think you won't need that for completing all the stages with 3 stars).

Finally, thanks for trying this game. Feel free to drop some feedback, either on the game flow, or the game experiences~

Friday, December 20, 2013

Creating a timer with the Actionscript onEnterFrame

For those who are Actionscript-savvy, the "onEnterFrame" Event is a familiar term. It is in fact an elegant way of handling the animations in the game.

This post, is particularly a demo of how do i use the AS3 "onEnterFrame" to replace the class Timer (which is in the package flash.utils). You might think that this is redundant. But i really favor the way the "onEnterFrame" perform this with ease, while you can implement the other animations simultaneously.

Here's a snippet of the "onEnterFrame" function. What it does is that, the object is able to perform an animation A on each frame, while performing another animation B at an interval of one second (adjustable).

private var timePassed:Number = 0;
private var startInt:int = 1;
private function onEnterFrame(e:EnterFrameEvent):void
{
     timePassed += e.passedTime;
     if(startInt < 10)
    {

         //doAnimationA();
         if(Math.floor(timePassed) == startInt)
        {
             startInt++;

             //doAnimationB();
        }
     }
     else
    {

        this.removeEventListeners(Event.ENTER_FRAME); //clean the event
     }
 }

One thing to note is that, the data type of the timePassed has to be "Number", but not "integer". In the code, after passing 10 seconds, the enterframe event is removed.

Sunday, November 10, 2013

Generate non-repeating random numbers for games in actionscript AS3

When creating games, the random number generation is one of the important elements to avoid a monotonous game play experience.

Generally, it is straightforward to create a random number in actionscript AS3 (Simply use the built-in Math.random() function). But the question is, how to generate a list of random numbers, without any repetition? I used to be a PHP programmer. With PHP, it has an elegant approach with just 2 lines:

$numbers = range(m, n); //manually generate an array storing a list of numbers ranging from m to n
shuffle($numbers); //yes, we have it shuffled already~

Unfortunately, we don't have a similar solution in AS3...
Instead, the solution is:

var arrWanted:Array = [m, m+1, m+2, ... , n]; //manually generate an array storing a list of wanted numbers
var arrRandom:Array = new Array();
while(arrWanted.length > 0)
{
   var intRandom:int = Math.random()*arrWanted.length;
   arrRandom.push(arrWanted[intRandom]);
   arrWanted.splice(intRandom,1);
}

The idea is that, from the wanted list of number, we randomly pick any of them, while reducing them at the same time. In the end, we have our arrRandom filled with a list of random numbers.

I realize that this problem has been solved by others. In this post, particularly, i would like to add a real example of using the non-repeating random numbers generation as well.

Generate random non-repeating cards in Big 2 (Big Two) Card Game



Big 2 (Big Two) is a popular Poker Card Game involving 4 players. At the beginning of each round, each player is provided 13 cards (which total up to 52). In reality, the cards are distributed one by one, clock-wise. However, when dealing with the cards distribution in coding, we could simply apply the random numbers generation stated above.

Let's rewind the codes (AS3 part). With a little bit modification, we would have our jobs done easily.

var arrWanted:Array = new Array();
for(var i:int=0;i<52;i++)
{
  arrWanted.push(i);
}
 

var arrRandom:Array = new Array();
while(arrWanted.length > 0)
{
   var intRandom:int = Math.random()*arrWanted.length;
   arrRandom.push(tmpArr[intRandom]);
   arrWanted.splice(intRandom,1);
}

var arrPlayer1:Array = new Array(); 
var arrPlayer2:Array = new Array();
var arrPlayer3:Array = new Array();
var arrPlayer4:Array = new Array();
for(i=0;i<arrRandom.length;i++)
{
  if(i<13)
  {
    arrPlayer1.push(i);
  }
  else if(i<26)
  {
    arrPlayer2.push(i);
  }
  else if(i<39)
  {
    arrPlayer3.push(i);
  }
  else
  {
    arrPlayer4.push(i);
  }
}

At the end, we have our arrays ready. Each array stores a list of 13 numbers which represent the Poker Cards.

Friday, November 8, 2013

Match 3 Game Algorithm Part 5 - Miscellaneous (Special Combinations)

By following the algorithms stated here, I believe you almost get the ideas of how a Match 3 game would look like in terms of logic. A little naive (as i didn't use any built in library or framework, or referring to the popular flood fill algorithm). But since it is from scratch, it has the flexibility of any customization. Furthermore, based on those solid understanding, you would be able to add more variations in your game.

Performance-wise, as long as you have followed the statements strictly, we could ensure a decent working solution. (I will demo a working one in the future post)

In this post, particularly, i would like to recap a number of features on the Candy Crush Saga that make the Match 3 game much more interesting - Special Candy Combinations, as stated below:


a) Color Bomb - formed by a match involving 5 candies in a uni-direction


b) Striped Candy - formed by a match involving 4 candies in a uni-direction


c) Wrapped Candy - formed by a match involving 5 candies in a "T", "+" or "L" shape.


Technically speaking, to detect these special candy combinations, it isn't that hard since we could make some checking in the results of the matching detection algorithm.



For example, in the picture above, after the node of 35th is exchanged with the 43rd, we would obtain a match of 5 nodes (33rd, 34th, 35th, 36th and 37th) according to the 1st statement.

However, the problem does not just end here. Since we are going to 'generate' the special 'candy' (item) ourselves, you might further pose some questions:

Q1: How to determine at where does the special candy reside?
Q2: How to enable those special effects formed by the special candies matches?

To answer the Q1, you would need to take some efforts remembering the index of the nodes touched by the player. If it takes place through random falling, you may take the smallest index of the matches to be the index of the special candy.

In the case of Q2, on the other hand, it is likely more complicated that we have to look into the special combinations one by one.

Consider the nodes exchange of Color Bomb:
a) 1 Color Bomb with 1 normal node
    Effect: All the nodes which are identical to the normal node will explode.
b) 1 Color Bomb with 1 Color Bomb
    Effect: All the nodes in the matrix explode.
c) 1 Color Bomb with 1 Striped Candy
    Effect: All the nodes having the same color become stripped candies and explode.
d) 1 Color Bomb with 1 Wrapped Candy
    Effect: All the nodes having the same color explode. And then, all the nodes with a random color explode.

Apart from that, we have to consider the exchange of Striped candy and Wrapped candy:
a) 1 Striped Candy with 1 Striped Candy
   Effect: Both Striped Candies explode
b) 1 Striped Candy with 1 Wrapped Candy
   Effect: Both candies explode, along with 3x3 matrix crossing both horizontally and vertically
c) 1 Wrapped Candy with 1 Wrapped Candy
   Effect: Both candies explode, along with 5x5 matrix surrounding both candies.

No pseudo-code? I believe with the basic algorithms in the previous posts, you would be able to construct the logic here. In case you really want, please leave a message here and i would update this :)

Note:
In my Match 3 game, i don't care about the orientation of the striped candy. Instead, i randomly explode either a horizontal or a vertical line.

Next: A real Android Match 3 Game Demo

Tuesday, November 5, 2013

Match 3 Game algorithm Part 4 - How to enable the user interaction?

Until now, we manage to come out with a fundamental match 3 game with the matches detection and a deadlock detection. So far so good :)

But the thing is, something is still missing: user interaction. This is the crucial part that lets the players get hooked on the game. The players are required to make some moves to proceed with the games, either through forming more matches, or completing some special missions. (In the case of the candy crush, the missions are forming matches to clear the jelly, or achieving a threshold score with minimum moves, and etc)

Here, the basic user interaction tutorial would be: move the nodes/items, either horizontally or vertically.

At first sight, this is pretty straightforward. In fact, since the each node/item in my match 3 game is coupled with an integer index, it isn't hard to make a rule such that, if the first node touched is a neighbor of the second, both the nodes are exchangeable, and hence we could perform some matching detection algorithm.


For example, the picture shows a matrix of 8x8. At the nodes indexed at 10th, 17th, 18th, 19th and 26th, it is easily observed that, the node of 18th can be only exchanged with its neighbor which has the absolute index difference of 1 or 8. With this understanding, we could conveniently generalize the algorithm...

However, let's consider 1 more case:

Here, the node indexed 15th, despite being able to exchange with the node 7th, 14th, 23rd, it is unable to interact with the node 16th (because they are not directly connected). Therefore, this special case has to be addressed in our algorithm, which is stated in the next statement:

Statement 4:
- Two nodes are exchangeable, provided that their absolute index difference is 1 or 8, AND if one of them is in the column 0th or 7th, the other one is NOT in the column 7th or 0th.

Forgive my poor explanation in the last part. It simply means that, the node in the column 0th cannot be exchanged with the one in the column 7th.

Coming up next: Miscellaneous (Special Combinations)

Friday, November 1, 2013

Match 3 Game algorithm Part 3 - How to determine whether there is no more match?

From the previous post, we learnt that to detect if there is a match in the match 3 game matrix, we could scan the nodes 1 by 1, each with the vertical and the horizontal direction.

Then, it must be natural to think that, if to do the opposite: "How to determine whether there is no more match?", we could simply apply the same concept, couldn't we?

To some extent, it is true that we could perform the similar technique. However, we haven't really defined the problem yet. Precisely, the puzzle to be solved is: "How to check whether there is no match, EVEN THOUGH after the players have made all the possible moves?" In other word, a match 3 game deadlock, in which the game couldn't proceed due to no more possible match.

There we go, with the condition added, the problem is way more troublesome than expected, and that's the reason i separated this topic.

Before the start of the algorithm, it would be better to have a look at some scenarios:


The picture shows a matrix with an extreme case such that, if the node of 35th and 36th (horizontal exchange) is exchanged, it could lead to the most matches (Here, let's just consider a match of 3 nodes only):
a) node 19th - vertical black
b) node 20th - vertical red
c) node 27th - vertical black
d) node 28th - vertical red
e) node 33rd - horizontal black
f) node 35th - vertical black
g) node 36th - vertical red, and horizontal red

With this understanding, it enlightens us on another statement:

Statement 2:
- For a horizontal exchange node of (nth) and (n+1)th, a matching detection algorithm is necessarily to be executed on the nodes:
a)  (n-2*8)th vertical
b)  (n+1 - 2*8)th vertical
c)  (n-8)th vertical
d) (n+1 - 8)th vertical
e) (n-2)th horizontal
f) (n)th vertical
g) (n+1)th vertical, horizontal


Similarly, this applies to the vertical nodes exchange as well:


 The picture shows that, if the node 35th is exchanged with the node 43th, it will trigger the matches:
a) node 19th - vertical black
b) node 33rd - horizontal black
c) node 34th - horizontal black
d) node 35th - horizontal black
e) node 41st - horizontal red
f) node 42nd - horizontal red
g) node 43rd - horizontal red, vertical red

Hence, not surprisingly, we have our 3rd statement:

Statement 3:
- For a vertical exchange node of (nth) and (n+8)th, a matching detection algorithm is necessarily to be executed on the nodes:
a)  (n-2*8)th vertical
b)  (n-2)th horizontal
c)  (n-1)th horizontal
d) (n)th horizontal
e) (n-2 + 8)th horizontal
f) (n-1 + 8)th vertical
g) (n + 8)th vertical, horizontal

Cool. Now we can apply the algorithm based on the statements. Here's the pseudo-code:
- foreach node nth
 manually exchange the node with (n+1)th, perform matching detection algorithm, 
 manually exchange the node with (n+8)th, perform matching detection algorithm.
 

 The pseudo code is as brief as possible. The thing to point out is that, although each could be exchanged in 4 directions (up, down, left, right), we only consider "right", and "down" while scanning each node. Again, this systematic checking avoids redundancy effectively.

There are several situations in which you could deploy the algorithm:
a) At the initial stage - when the game starts, you could check if the matrix encounters a deadlock or not
b) After the player have made a move - to check if the interaction is effective or not
c) After the items regenerated and have fallen down - to check if the fallen items would form some matches or not.

Coming up next: How to enable the user interaction?

Wednesday, October 30, 2013

Match 3 Game algorithm Part 2 - How to detect there is a match?

With the game element terminology, we are ready to jump into the core of the game - Matches detection. It is the most fundamental yet critical puzzle.

So, the question: Provided a matrix of 8x8 consisting of random items, how to detect if there is a match?

And here comes the 1st statement (from androidgamify blogspot :) )
Statement 1:
- Every match (vertical or horizontal) is detected at the node located at the smallest nth of tile.

What does that mean?

For example, the picture below shows a matrix with a number of matches. (Assume that you design your match-3 game in such a way that there could be matches at the initial stage)


From the observation, there is a horizontal match of the green nodes located at the tile 8th, 9th and 10th, and a vertical match of the blue nodes located at the tile 35th, 43th, 51th. (Just focus on these two first).

Based on the statement, while scanning the matrix nodes 1 by 1, the green match has to be detected at the 8th, while the blue match is to be detected at the 35th. With this systematic checking, we can effectively avoid redundancy.

Hence, generally speaking we can deduce the matching algorithm as below:
To detect the vertical matching, we only need to scan the nodes which are from the row 0th to 5th.


And to detect the horizontal matching, the nodes to be scanned are from the column 0th to 5th.




These make sense, considering the fact that only at the green nodes we are able to detect the matching of the specified orientation.

Here's the pseudo-code:
a) Vertical matching
- foreach node nth
  if it is at more than 5th row, skip
  else check if nth equal to (n+8)th, (n+2*8)th, (n+3*8)th, (n+4*8)th to determine how many nodes in  the matching.

b) Horizontal matching
- foreach node nth
  if it is at more than 5th column, skip
  else check if nth equal to (n+1)th, (n+2)th, (n+3)th, (n+4)th to determine how many nodes in  the matching.

Coming up next: How to detect if there is no more match?

Sunday, October 27, 2013

Match 3 Game algorithm Part 1 - Game elements terminology and analogy

Generally, a Match 3 Game consists of a matrix of nodes with the dimension M x N. Here i prefer a square one (M x M), specifically 8 x 8.

Terminology:
a) Tile: The location at which the 'node' resides. In a matrix of M x M, each tile is representable by a number from 0 to (M x M - 1), at ith row and jth column.
b) Node: The item of the matching. In the Candy Crush Saga, it is analogous to the candy.
c) Matches: The matching of 3 to 5 nodes, could be horizontal or vertical, but not diagonal.

* To conveniently setup the Match 3 Game, I use colors as the type to differentiate the nodes. Similar to the tile number, i will start counting my row and column from 0 to (M-1).

For example, the picture shows a matrix of 8 x 8 - consisting of 64 tiles.
 The crossed tile:
a) resides at 1st row, 1st column. OR
b) belongs to the 9th tile.

Apart from that, there are a number of matches observed. For example, a matches of 5 blue squares at 33th, 34th, 35th, 36th, 37th tiles.

Coming up next: How to detect a match?

Friday, October 25, 2013

How to create a match 3 Android Game like Candy Crush Saga?

As mentioned before, the Candy Crush Saga, with the basic concept of the Match 3 game, stands out to be an extraordinarily successful game.

Then, instinctively, you will ask yourselves, "Can I become similarly successful if i make another Match 3 game?" And the most importantly, what is the basic algorithm behind the Match 3 game that powers the Candy Crush Saga? By understanding and constructing those skeletons, you may design your own attractive graphics, sound effects, and animations to package your game.

To your delight, for the next couple of blog posts, the contents will touch about the algorithm of the Match 3 game. Curiosity makes me learn to create this kind of game as well :) . After some research from the search engines, I came out with my own solution (ok, + reference) which I wish you can find it useful for your basic understanding.

No fuzzy codes. It is mainly about the algorithm, with intuitive picture description and lines of pseudo-code.

To summarize, I break down the Match 3 Game algorithm into several parts:


a) Match 3 Game algorithm Part 1 - Game elements terminology and analogy

- A quick understanding of how I define the game elements. It will help a lot before you read the others.

b) Match 3 Game algorithm Part 2 - How to detect if there is a match?

- Basically it is the core part of the game. No third-party framework or library. Everything is from scratch.

c) Match 3 Game algorithm Part 3 - How to determine whether there is no more match?

- An important checking to see whether the game can proceed or not.

d) Match 3 Game algorithm Part 4 - How to enable the user interaction?

- There are a number of approaches. Here I simply use the index difference, with an exception handling.

e) Match 3 Game algorithm Part 5 - Miscellaneous (Special Combinations)

- Include some interesting parts which make the game more impressive and fun.

f) Match 3 Game algorithm Part 6 - A real Android Match 3 Game demo

- The whole tutorial is not convincing without a real game demo. However, the graphics are not emphasized. Yay! It is now in the Google Play Store - Match 3 Pop Saga

Kindly drop a feedback if you find any typo.