I'm generating simple game maps using a method described in this post. I'm using the second method of starting with a seed tile and randomly growing out. I'm testing it in a Swift playground on a 30x30 array. The problem is my method takes several minutes to generate a 30x30 map, and maps in my real game might exceed 100x100 tiles. How can I optimize the following code to run faster?
import UIKit
import SpriteKit
var map = [[String]](count: 30, repeatedValue:[String](count: 30, repeatedValue:" "))
var landTiles = [(y: Int,x: Int)]()
landTiles.append((15,x: 15))
let minX = 3
let maxX = 28
let minY = 3
let maxY = 28
var coastTiles = [(y: Int,x: Int)]()
var hasReachedBounds = false
while !hasReachedBounds {
coastTiles = []
for tile in landTiles {
let coastal = isCoastal(tile.y, x: tile.x)
if coastal {
coastTiles.append(tile)
}
}
let numTiles = UInt32(coastTiles.count)
print(map)
let randomTile = coastTiles[Int(arc4random_uniform(numTiles))]
if randomTile.x <= minX || randomTile.x >= maxX || randomTile.y <= minY || randomTile.y >= maxY {
hasReachedBounds = true
break
}
let coastal = isCoastal(randomTile.y, x: randomTile.x)
if !coastal{
continue
}
let randomPosition = arc4random_uniform(4) + 1
switch randomPosition {
case 1:
landTiles.append((randomTile.y + 1, randomTile.x))
map [randomTile.y + 1][randomTile.x] = "&"
case 2:
landTiles.append((randomTile.y, randomTile.x + 1))
map [randomTile.y][randomTile.x + 1] = "&"
case 3:
landTiles.append((randomTile.y - 1, randomTile.x))
map [randomTile.y - 1][randomTile.x] = "&"
case 4:
landTiles.append((randomTile.y, randomTile.x - 1))
map [randomTile.y][randomTile.x - 1] = "&"
default: break
}
}
func isCoastal (y: Int, x: Int) -> Bool{
if map[y + 1][x] == " " || map[y][x + 1] == " " || map[y - 1][x] == " " || map[y][x - 1] == " "{
return true
} else {
return false
}
}
print(map)