I've been coding a type of tile-based roguelike game, and I have some map generation going on (not for dungeons, but outdoors terrain: hills, forests...) and it's very rudimentary. My problem is that I have a function called Map:placeNode(x, y, range, type) that should place a type of terrain, say forest, on a certain tile and surrounding it. It goes fine, but every few times I regenerate, it gives me this error:
Code: Select all
map.lua:107: attempt to index a nil value
Code: Select all
function Map:placeNode(x, y, range, type)
self.tiles[x][y].type = type
local startx = x - range
local starty = y - range
local endx = x + range
local endy = y + range
for x2 = startx, endx, 1 do
for y2 = starty, endy, 1 do
if self:isWithinBounds(x2, y2) then
local d = (math.abs(x2-x) + math.abs(y2-y))/2
local luck = 0.5^d
if love.math.random() <= luck then self.tiles[x2][y2].type = type end
end
end
end
end
function Map:isWithinBounds(x,y)
if x > 0 and y > 0 and x <= self.width-1 and y <= self.width-1 then
return true
else return false end
end
Code: Select all
function Map:placeNode(x, y, range, type)
self.tiles[x][y].type = type
local startx = x - range
local starty = y - range
local endx = x + range
local endy = y + range
for x2 = startx, endx, 1 do
for y2 = starty, endy, 1 do
if self:isWithinBounds(x2, y2) then
local d = (math.abs(x2-x) + math.abs(y2-y))/2
local luck = 0.5^d
if love.math.random() <= luck then self.tiles[x2][y2].type = type end
end
end
end
end
function Map:isWithinBounds(x,y)
if x > 0 and y > 0 and x <= self.width-1 and y <= self.width-1 then
return true
else return false end
end
- The first tile is at (x, y) = (1, 1) and they go all the way up to (width, height) of the map.
- If you want my .love file, my code isn't optimized and is probably in all honestly a disgusting sight. Prepare barf-bags.