“zNumbers” game level generator commented source code released

Are you enjoying znumberz game, the remake of zNumbers? It’s free with no ads both for iOS and Android and you should definitively download and install it, or at least play online on triqui.com.

One of the most interesting features in my opinion is the random level generator, which allows you to generate new levels and add them to the 10 levels of the original zNumbers game.

Have a look at it:

Check previous posts of the series to know how to play, and let’s focus on level generation. Just hit “Restart” button to generate a new level, and look at the console to see the solution.

The core is on generateRandomLevel(maxAttempts) method which has an argument called maxAttempts. The higher maxAttempts, the harder the level.

Basically it works this way:

* Start with an empty level

* Pick a start position in a randomly choosen tile

* There is a loop which is executed n times, where n is the number of tiles in the game

* From start position, try maxAttempts times to generate a valid move – which means is landing on an empty tile – going in a random direction for a random (1 to 4) number of steps

* If you find a valid move before maxAttempts attempts, set start position to the destination of valid move.

* No matter if you found or not the valid move, execute the loop again.

It’s easy to see The higher maxAttempts, the harder the level, and the more tiles already placed, the harder to find a valid move in less than maxAttempts attempts.

The interesting thing is you can also write down the moves to solve the level.

Look at the source code:

Download the source code and play with it, in my opinion the best levels are generated with maxAttemtps ranging from 40 to 80.

And don’t forget to get znumberz for iOS or Android.