54 lines
1.4 KiB
JavaScript
54 lines
1.4 KiB
JavaScript
import Player from "./player.js"
|
|
import Input from "./input.js"
|
|
import Event from "./event.js"
|
|
|
|
export default class Game {
|
|
constructor(canvas) {
|
|
this.canvas = canvas
|
|
this.ctx = canvas.getContext("2d")
|
|
this.timestamp = 0
|
|
this.player = new Player(this, 200, 200)
|
|
this.actors = [this.player]
|
|
|
|
this.input = new Input().initialize()
|
|
|
|
this.currentRoom = null
|
|
this.events = {
|
|
"log_test": new Event("log_test", () => console.log("Log events work!")),
|
|
"change_color": new Event("change_color", object => object.properties.find(property => property.name == "color").value = "blue")
|
|
}
|
|
}
|
|
|
|
triggerEvent(eventName, object) {
|
|
const event = this.events[eventName]
|
|
if (event) event.trigger(object)
|
|
else console.error("Unknown event " + eventName)
|
|
}
|
|
|
|
start() {
|
|
this.currentRoom = this.assets.get("sampleRoom")
|
|
requestAnimationFrame(this.loop.bind(this))
|
|
}
|
|
|
|
loop(timestamp) {
|
|
const dt = timestamp - this.timestamp
|
|
this.timestamp = timestamp
|
|
this.tick(dt)
|
|
this.draw()
|
|
|
|
requestAnimationFrame(this.loop.bind(this))
|
|
}
|
|
|
|
tick(dt) {
|
|
this.actors.forEach(actor => actor.tick(dt))
|
|
this.currentRoom.tick(dt)
|
|
Object.values(this.events).forEach(e => e.nextFrame())
|
|
}
|
|
|
|
draw() {
|
|
const { canvas, ctx } = this
|
|
this.currentRoom.draw(ctx)
|
|
this.actors.forEach(actor => actor.draw(ctx))
|
|
}
|
|
}
|