a_pleasant_stroll/mapgen.lua

68 lines
2.0 KiB
Lua

--- Procedural generation methods
function init_mapgen()
uid_seed = 2229 -- arbitrarily chosen number
block_size = 64
-- Sprite ratios for different biomes, of the form { "biome_name": {frequency, sprite index} ... } }
-- frequencies don't have to add up to 100, but they should by convention
--
-- Sprites are:
-- * 2 - grass
-- * 3 - bush
-- * 4 - tree
-- * 5 - red flowers
-- * 6 - pink flowers
-- * 7 - mushrooms
biomes = { grassland = { {40, 2}, {28, 5}, {28, 6}, {3, 3}, {1, 4} },
forest = { {50, 2}, {40, 4}, {5, 3}, {4, 5}, {1, 7} } }
build_biome("forest")
end
-- use biome1 if mix == false
function build_biome(biome1, biome2, mix)
if mix == true then
else
frequencies = biomes[biome1]
end
-- global variable used for lookup during mapgen
-- build_biome() writes the biome_lookup table such
-- that biome_lookup[uid] returns a sprite index,
-- weighted by the frequency information for current biome.
biome_lookup = {}
for i=1,#frequencies do
local tuple=frequencies[i]
for j=1,tuple[1] do
add(biome_lookup, tuple[2])
end
end
end
-- generates a unique identifier for a position
-- uses srand() and rand() to get an unpredictable value (is this too slow?)
function generate_uid(pos)
srand((pos[1] + uid_seed) * (pos[2] + (uid_seed^2)))
return flr(rnd(-1))
end
-- determine what sprite to render for a given position
function get_tile(pos)
return biome_lookup[(generate_uid(pos) % #biome_lookup) + 1]
end
-- generate the map and writes to the map area from 0 - block_size,
-- assuming 'start' as the top-left corner of the map area to generate.
-- writes block_size x block_size tiles
-- after a call to generate_map you should always center the camera/player over the map, i.e.
-- camera at { (block_size / 2) - 8, (block_size / 2) - 8 }
function generate_map(start)
for x=0,block_size-1 do
for y=0,block_size-1 do
mset(x, y, get_tile({start[1]+x, start[2]+y}))
end
end
end