Skip to content

Instantly share code, notes, and snippets.

@luizbills
Last active February 14, 2025 13:50
Show Gist options
  • Save luizbills/08272728c6bd0c142020f24e087b0af4 to your computer and use it in GitHub Desktop.
Save luizbills/08272728c6bd0c142020f24e087b0af4 to your computer and use it in GitHub Desktop.
Simple scene manager for Litecanvas games

Simple scene manager

Usage

let scenes;

const e = litecanvas({})

function init() {
  scenes = new SceneManager(e)

  // defines the "menu" scene with object
  scenes.add('menu', {
    start() {
      console.log('start Menu scene')
    },
    end() {
      console.log('end Menu scene')
    },
    draw() {
      cls(0)
      text(0, 0, 'MENU SCENE')
    },
    tapped() {
      scenes.start('game')
    },
  })

  // defines the "game" scene with function
  // var e = litecanvas engine instance
  scenes.add('game', function (e) {
    const WHITE = 3
    return {
      draw() {
        e.cls(WHITE)
        e.text(0, 0, 'GAME SCENE', 0)
      },
      tapped() {
        scenes.start('menu')
      },
    }
  })

  // starts the first scene
  scenes.start('menu')
}
/**
* @version 1.1.1
*/
class SceneManager {
constructor(engine = globalThis) {
this.list = {}
const events = [
'update',
'draw',
'tap',
'untap',
'tapped',
'resized'
]
for (let ev of events) {
engine.listen(ev, (...args) => {
if (this.current && this.current[ev]) {
this.current[ev](...args)
}
})
}
this.engine = engine
}
add(name, data) {
if ('function' === typeof data) {
data = data(this.engine)
}
this.list[name] = data
}
start(name) {
if (this.current && this.current.end) {
this.current.end(this.engine)
}
const next = this.list[name]
if (!next) {
throw `unexpected scene "${name}"`
}
if (next && next.start) {
next.start(this.engine)
}
this.current = next
}
}
@luizbills
Copy link
Author

luizbills commented Feb 6, 2025

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