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?

1 comment:

  1. Enjoying the match 3 series so far, these stuffs are really helpful

    ReplyDelete