- Home /
Pattern Detection
If I was making a tetris style game but when certain colored balls touched each other in a specific pattern, how would I check to see if that pattern was reached?
Example: Four balls make an "L" shape. How do you check if that certain pattern was formed?
Answer by Jesse Anders · Sep 22, 2010 at 04:35 AM
To keep things simple, we'll use your 'L' shape as an example. (I'm assuming that we're talking about an 'L' shape in its 'default' configuration; if the shape can be mirrored and/or oriented differently, a little more work will be required, but the concepts are the same.)
I'm assuming that the game board is (or could be) represented as a 2-d array; I'll also assume that row numbers increase upwards. For any given cell (i, j), you can determine if there's a corresponding L shape by checking the colors of cells (i, j-1), (i, j-2), and (i+1, j-2). The query needn't be performed for cells in the last column and in the first two rows, since the query would go outside the array bounds. If the colors of the three checked cells are the same as the query cell, you've found an 'L' pattern.
Similarly, you can check to see if any specific ball is part of an 'L' pattern by performing four checks similar to the one described above, one for each of the four positions the ball can have relative to the L.
The ideas described above can be generalized to handle different shapes, and different configurations of those shapes. When and how the tests should be performed depends on the game mechanics. Depending on the circumstances, you might be able to get away with performing a brute-force search for all patterns every time the board changes. Or, you could perform searches 'on demand' as needed. (Again, the details depend on the context.)
Is there anyway to run it against a template of the shapes? Like to compare it with the shape?
Sure, you would just generalize the approach I described for the 'L'; it would most likely involve creating a 'shape definition' class, storing an array of shape definitions, and then perfor$$anonymous$$g the test described above for each shape. (I can't really fit a detailed description into a comment, but feel free to ask any specific questions you might have. Alternatively, you could post a thread to the forums on the specific topic of how to make the pattern detection generic.)