top-down-action-adventure/src/game.js
2025-06-07 09:28:18 -04:00

72 lines
1.8 KiB
JavaScript

import Player from "./player.js"
import Input from "./input.js"
import Event from "./event.js"
import Message from "./message.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.setProperty("color", "blue")),
"show_message": new Event("show_message", object => this.message = new Message(this, object.getProperty("messageText")))
}
this.message = null
}
triggerEvent(eventName, object) {
const event = this.events[eventName]
if (event) event.trigger(object)
else console.error("Unknown event " + eventName)
}
start() {
this.loadRoom(this.assets.get("sampleRoom"))
requestAnimationFrame(this.loop.bind(this))
}
loadRoom(room) {
this.currentRoom = room
this.currentRoom.objects.forEach(roomObject => this.actors.push(roomObject))
}
closeMessage(message) {
this.message = null
}
loop(timestamp) {
const dt = timestamp - this.timestamp
this.timestamp= timestamp
this.tick(dt)
this.draw()
requestAnimationFrame(this.loop.bind(this))
}
tick(dt) {
if (this.message) {
this.message?.tick(dt)
} else {
this.actors.forEach(actor => actor.tick(dt))
Object.values(this.events).forEach(e => e.nextFrame())
}
this.input.tick()
}
draw() {
const { canvas, ctx } = this
this.currentRoom.draw(ctx)
this.actors.forEach(actor => actor.draw(ctx))
this.message?.draw(ctx)
}
}