-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.lua
85 lines (69 loc) · 1.95 KB
/
generator.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
local generator = { }
--- Generate a random seed
-- @return number: a random seed
local function randomSeed()
local seed = os.clock() * 100000000000
return seed
end
--- Generate a random number
-- @param from number: a lower bound of range
-- @param to number: a higher bound of range
-- @param seed number: an optional seed
-- @return number: a random number
local function randomInt(from, to, seed)
local seed = seed or randomSeed()
math.randomseed(seed)
local result = math.random(from, to)
return result
end
--- Generate a random map
-- @param size table: a size table like { width = 32, height = 32 }
-- @param dense number: a percent of walls from 0.0 to 1.0
-- @return table: a map
function generator.randomMap(size, dense)
local grid = { }
for x = 1, size.width do
local row = { }
for y = 1, size.height do
local isWall = randomInt(0, 100) < 100 * dense
row[y] = isWall
end
grid[x] = row
end
local map = {
['grid'] = grid,
['size'] = size
}
return map
end
--- Find a random free point on the map grid
-- @param grid table: a map grid
-- @param excluded table: an array of excluded points
-- @return table: a random free point like { x = 3, y = 5 }
function generator.randomFreePoint(grid, excludedPoints)
local excludedPoints = excludedPoints or { }
local freePoints = { }
-- Find free points
for x, row in ipairs(grid) do
for y, isWall in ipairs(row) do
local isExcluded = false
for _, excludedPoint in ipairs(excludedPoints) do
if x == excludedPoint.x and y == excludedPoint.y then
isExcluded = true
end
end
if not isWall and not isExcluded then
local point = {
['x'] = x,
['y'] = y
}
table.insert(freePoints, point)
end
end
end
-- Select a random free point
local randomIndex = randomInt(1, #freePoints)
local result = freePoints[randomIndex]
return result
end
return generator