When creating a level we randomly select fruit for a tile. This “randomness” causes matches to pre-exist in a level when presented to a player. This would reduce the challenge of the puzzle and should not be the case. We can easily eliminate these match chains by updating the Level class.
In the Level class we have a createInitialFruits() method that just picks a random fruit for the fruit type in the fruits 2D array. Before assigning the fruit type we’ll need to check its neighbors to the left and below to ensure we aren’t creating a chain. We only need to check that we aren’t creating a chain of three to the left (column – 1 & column – 2) and below (row – 1 & row – 2) because we are building up the game grid from the left / bottom up. We’ll implement a repeat-while loop to repeat the random picking of a fruit until no match exists. Once we get a fruit that doesn’t introduce a match chain we assign it.
This easily eliminates any pre-existing match chains of three and building and running the updated code gives us the results we are looking for:
Next, we’ll look at at defining and validating whether a swap results in a three-match. This is needed in order to prevent swaps that do not result in a three-match.