Loading levels from images

Today I was working on a snippet that will allow you to load png files into löve2d, in a format accepted by YellowAfterLife’s Platformer engine (Although with minor edits, you could make it export to any format).  Without further ado, here is the code:

function imgtolvl(file, key)
    local lvl = {}
    local lvltxt = ''
    local img = love.image.newImageData(file)
    for y=1, img:getHeight(), 1 do
        for x=1, img:getWidth(), 1 do
            local r, g, b, a = img:getPixel(x-1, y-1)
            for c=1, #key, 1 do
                if key[c][1] == r..'.'..g..'.'..b then
                    lvltxt = lvltxt..key[c][2]
    table.insert(lvl, img:getWidth())
    table.insert(lvl, img:getHeight())
    table.insert(lvl, file)
    table.insert(lvl, lvltxt)
    return lvl

All you will need is a array (key) and a image (file)  The array should look like this:

key = {
     {'0.0.0', 'x'},
     {'0.255.0', 'g'},
     {'10.10.10', 'w'},
     {'100.100.100', 'p'},
     {'255.255.255', ' '},

The numbers that you see are RGB pairs, so ‘255.255.255’ would be white.  the second string is the character that it will use in the final array.  In the engine, a space is air, so a white pixel would be air.

You will also need to update your level.next function.  Replace this:

d = level.levels[level.current]

with this:

d = imgtolvl(level.levels[level.current], level.key)

I hope that you find this snippet as useful as I do!


7 thoughts on “Loading levels from images

  1. If you search and look well anything official you won’t see Love2D applied anywhere. Only the domain is love2d because simple love should be already registered. For what I read and understand isn’t authors/maintainers/older community desire. But unfortunately some new members started to badly applying love2d everywhere so… Anyway Löve seems a bad chosen name for several reasons.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s