zNumbers level generator

by Arjan Haverkamp

JavaScript

// zNumbers level generator

/*
var fieldSize = {
	rows: 6,
	cols: 6
};
*/

var directions = [
	{x:0, y:1},
	{x:0, y:-1},
	{x:1, y:0},
	{x:-1, y:0},
	{x:1, y:1},
	{x:-1, y:-1},
	{x:1, y:-1},
	{x:-1, y:1}
];

function getRandomInt(min, max) {
	return Math.floor(Math.random() * (max - min + 1)) + min;
}

function isLegalDestination_OLD(p, level)
{
	// it's not legal if it's outside the game field
	if (p.x < 0 || p.y < 0 || p.x >= fieldSize.rows || p.y >= fieldSize.cols) {
		return false;
	}
 
	// it's not legal if there's already a tile
	if(level[p.x][p.y]!=0){
		return false;
	}
 
	// ok, it's legal
	return true
}

function generateRandomLevel(fieldSize, maxAttempts)
{
	function isLegalDestination(p, level)
	{
		// it's not legal if it's outside the game field
		if (p.x < 0 || p.y < 0 || p.x >= fieldSize || p.y >= fieldSize) {
			return false;
		}

		// it's not legal if there's already a tile
		if(level[p.x][p.y]!=0){
			return false;
		}

		// ok, it's legal
		return true
	}

	// we will store the generated level here
	var level = [];
 
	// initializing the array
	for (var y = 0; y < fieldSize; y++){
		level[y] = [];
		for(var x = 0; x < fieldSize; x++){
			level[y][x] = 0;
		}
	}
 
 	// choosing a random start position
	//var startPosition = new Phaser.Point(game.rnd.integerInRange(0, gameOptions.fieldSize.rows - 1), game.rnd.integerInRange(0, gameOptions.fieldSize.cols - 1));
	var startPosition = {x:getRandomInt(0,fieldSize-1), y:getRandomInt(0,fieldSize-1)};
	
	// here we'll store the solution
	var randomTileValue, randomDistination, randomDirection, solution = '';
 
	// we'll execute this process once for each tile in the game
	for(var i = 0; i <= fieldSize * fieldSize; i++) {
 		// keeping count of how many attempts we are doing to place a tile
		var attempts = 0;
 
		// we repeat this loop...
		do {
			// choosing a random tile value from 1 to 4
			randomTileValue = getRandomInt(1,4);
 
			// choosing a random direction
			randomDirection = getRandomInt(0,...