Skip to content

Instantly share code, notes, and snippets.

@luizbills
Last active January 23, 2025 18:59
Show Gist options
  • Save luizbills/bf329b0c798401940c0d9209cf7fae20 to your computer and use it in GitHub Desktop.
Save luizbills/bf329b0c798401940c0d9209cf7fae20 to your computer and use it in GitHub Desktop.
Simple tilemap engine #litecanvas

Simple Tilemap Engine for Litecanvas

Usage

let map 

litecanvas()

function init() {
  // create a map
  const tiles = [
    '   $',
    '  $$$',
    ' $$$$$',
    '=======#',
    '=======#'
  ]
  
  // create the tilemap
  map = tilemap(tiles, {
    tileWidth: 32,
    tileHeight: 32,
    
    // deines how to render each tile
    tiles: {
      '$': (x, y) => {
        circfill(x + 16, y + 16, 6, 5)
        stroke(11)
      },
      '=': (x, y) => {
        rectfill(x, y, 32, 32, 9)
        stroke(8)
      },
      '#': (x, y) => {
        rectfill(x, y, 32, 32, 7)
        stroke(6)
      },
    }
  })
}

function draw() {
  cls(0)
  
  // draw the tilemap
  map.draw()
}

Demo

Demo in playground

/**
* @version 0.1.2
*/
function tilemap(map, { tileWidth = 32, tileHeight = 32, tiles, engine = globalThis }) {
let cols = 1,
rows = map.length,
result = {},
tilegrid
for(const line of map) {
cols = max(cols, line.length)
}
// requires Grid class from https://github.com/litecanvas/utils
tilegrid = new Grid(cols, rows)
for (let y = 0; y < rows; y++) {
const line = map[y]
for (let x = 0; x < line.length; x++) {
tilegrid.set(x, y, line[x])
}
}
function _paint() {
return engine.paint(cols * tileWidth, rows * tileHeight, () => {
for (let [x, y, ch] of tilegrid) {
if (!ch || ' ' === ch) continue;
const tile = tiles[ch]
if (!tile) continue;
if ('function' === typeof tile) {
tile(x * tileWidth, y * tileHeight)
} else {
engine.image(x * tileWidth, y * tileHeight, tile)
}
tilegrid.set(x, y, ch)
}
})
}
return {
img: _paint(),
tileWidth,
tileHeight,
rows,
cols,
tiles: tilegrid,
// set a tile
set(tileX, tileY, ch) {
this.tiles.set(tileX, tileY, ch)
this.img = null // redraw
},
// get a tile
get(tileX, tileY) {
return this.tiles.get(tileX, tileY)
},
// draw the tilemap
draw(offsetX = 0, offsetY = 0) {
if (!this.img) {
this.img = _paint()
}
engine.image(offsetX, offsetY, this.img)
}
}
}
@luizbills
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment