Summing up the last post: we can now identify the gems on the board and produce an array containing color indices.
The move class
I love writing ‘simple’ code that speaks for itself. Does it make the code slower? Maybe, but until I don’t experience any sluggishness on my 3 years old low end laptop then I don’t care! Clarity comes first, then comes optimization if it’s needed.
Here is the whole move class (and an extra enum):
Moving the tiles
Let’s say that the above is the array we consider (and ignore elements with 0 value). If this was our game board we would have two valid moves:
Move element (0,2)[row,column] down
Move element (3,5) left
I look for matches separately in two directions; horizontally and vertically. Here is roughly what the algorithm I created does:
Select row and column
Checks 8 neighbours (2 elements up, down, left, right) of a selected row and column to see if there are any elements with matching value
If there are elements with matching values in the neighbourhood then algorithm proceeds further by iterating through them
If the matching neighbour is far from the selected row and column then I look for matches either horizontally or vertically
If the two matching elements are one close to the other then things get a bit more complicated:
We then check all close neighbours of the element marked in pink to see if any of them have the value we are interested in. We are doing the same operation on the neighbour to the bottom of the group (in this case not shown on the picture).
Enough talking, let’s see some code!
Here is the function for matching neighbours in one direction:
The distance allows me to specify what is the range of tiles I’m interested in. In case of point 2 the distance will be 2. In case of point 5 the distance will be 1.
TryGetValue is an extension method that ensures that I never try to check the array for a value out of bonds. Here is the code:
More codeeeeeee
OK, there is some more code. I promise this is the last snippet and then I will shut up! Since we have some code for matching neighbours now we can put together the last final function(s). The code to follow returns the list of Moves, so we know which tiles to move where to score some shiny points!
Summing up
So here it is! Now you can get the valid moves for the bejeweled game. In the last post I will show you how I handle keyboard events and simulate mouse clicks. Stay tuned!
Or if you can’t wait then just grab the source code.
In this blog post, I will highlight some of the updates since my last blog and offer some advice that I hope will be useful for anyone looking to get into technical consulting. Continue reading