Match3 - How can I ensure the board starts with no matches?

I have followed a couple of tutorials and have gotten the basics down on how to create a “match 3” game:

  • Build a grid x*y and populate each ‘cell’ with random prefab
  • Detect click/tap to select object to move and which cell to move to
  • Check 2 switched objects for adjacent matching objects
  • Destroy if 3+ adjacent
  • Repopulate empty cells

This is all working fine (needs some cosmetic tweaks) but I almost always start off with matches in place on my grid.

I would like to check for matches post-repopulate - for combos and the like - so need some insight as to how to do that, but also I would like the first board the players sees to be match-free (rather than the game start and matches get made for you to clear any matches).

I have looked at Grim Grin’s tutorials on Youtube but even that appears to be subject to this.

Thanks

You can build the board so it doesn’t have matches. As you move from lower left corner to upper right corner adding pieces to the board, simply check that the two pieces to the left or two pieces down are not the same color as the piece you are adding. If they are, choose another color.

Code below is straight from a game I’m working on so some parts of it might look weird. colorTypes is a List and represents the final output board (as 1D array):

//Generate the random board
        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                ColorType colorType = ColorType.None;
                do
                {
                    int randomIndex = Random.Range(0, gemList.PrefabCount);
                    GameObject gemPrefab = gemList.GetPrefabFromIndex(randomIndex);
                    Gem gem = gemPrefab.GetComponent<Gem>();
                    colorType = gem.colorType;
                }
                while ((x >= 2 &&
                        colorTypes[(x - 1) + (y * width)] == colorType &&
                        colorTypes[(x - 2) + (y * width)] == colorType)
                    ||
                        (y >= 2 &&
                        colorTypes[x + ((y - 1) * width)] == colorType &&
                        colorTypes[x + ((y - 2) * width)] == colorType));
                colorTypes.Add(colorType);
            }
        }

Algorithm from: https://www.raywenderlich.com/66877/how-to-make-a-game-like-candy-crush-part-1

Your overall strategy needs to be something like this.

  • Set up a virtual board
  • Iterate through all positions of the board, checking for matches
  • Replace any matches with another random tile
  • Repeat until the board is valid
  • Make the board visible to the player

An alternative way to keep generating random boards until one with no matches is found. This depends on the cost of generating a new board, and the likelihood of a random board being valid.