2025-06-03 21:09:59 -04:00
|
|
|
import Player from "./player.js"
|
2025-06-02 18:54:00 -04:00
|
|
|
import Input from "./input.js"
|
2025-06-06 21:04:58 -04:00
|
|
|
import Event from "./event.js"
|
2025-06-07 09:28:18 -04:00
|
|
|
import Message from "./message.js"
|
2025-06-01 15:54:55 -04:00
|
|
|
|
2025-06-01 15:30:12 -04:00
|
|
|
export default class Game {
|
|
|
|
constructor(canvas) {
|
|
|
|
this.canvas = canvas
|
|
|
|
this.ctx = canvas.getContext("2d")
|
2025-06-01 15:37:12 -04:00
|
|
|
this.timestamp = 0
|
2025-06-04 21:29:23 -04:00
|
|
|
this.player = new Player(this, 200, 200)
|
|
|
|
this.actors = [this.player]
|
2025-06-02 18:54:00 -04:00
|
|
|
|
|
|
|
this.input = new Input().initialize()
|
2025-06-04 01:16:48 -04:00
|
|
|
|
|
|
|
this.currentRoom = null
|
2025-06-06 21:04:58 -04:00
|
|
|
this.events = {
|
|
|
|
"log_test": new Event("log_test", () => console.log("Log events work!")),
|
2025-06-07 08:45:01 -04:00
|
|
|
"change_color": new Event("change_color", object => object.setProperty("color", "blue")),
|
2025-06-07 09:28:18 -04:00
|
|
|
"show_message": new Event("show_message", object => this.message = new Message(this, object.getProperty("messageText")))
|
2025-06-06 21:04:58 -04:00
|
|
|
}
|
2025-06-07 09:28:18 -04:00
|
|
|
|
|
|
|
this.message = null
|
2025-06-06 21:04:58 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
triggerEvent(eventName, object) {
|
|
|
|
const event = this.events[eventName]
|
|
|
|
if (event) event.trigger(object)
|
|
|
|
else console.error("Unknown event " + eventName)
|
2025-06-01 15:37:12 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
start() {
|
2025-06-07 08:50:37 -04:00
|
|
|
this.loadRoom(this.assets.get("sampleRoom"))
|
2025-06-01 15:37:12 -04:00
|
|
|
requestAnimationFrame(this.loop.bind(this))
|
|
|
|
}
|
|
|
|
|
2025-06-07 08:50:37 -04:00
|
|
|
loadRoom(room) {
|
|
|
|
this.currentRoom = room
|
|
|
|
this.currentRoom.objects.forEach(roomObject => this.actors.push(roomObject))
|
|
|
|
}
|
|
|
|
|
2025-06-07 09:28:18 -04:00
|
|
|
closeMessage(message) {
|
|
|
|
this.message = null
|
|
|
|
}
|
|
|
|
|
2025-06-01 15:37:12 -04:00
|
|
|
loop(timestamp) {
|
|
|
|
const dt = timestamp - this.timestamp
|
2025-06-07 09:28:18 -04:00
|
|
|
this.timestamp= timestamp
|
2025-06-01 15:37:12 -04:00
|
|
|
this.tick(dt)
|
|
|
|
this.draw()
|
|
|
|
|
|
|
|
requestAnimationFrame(this.loop.bind(this))
|
|
|
|
}
|
|
|
|
|
|
|
|
tick(dt) {
|
2025-06-07 09:28:18 -04:00
|
|
|
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()
|
2025-06-01 15:30:12 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
draw() {
|
|
|
|
const { canvas, ctx } = this
|
2025-06-04 01:16:48 -04:00
|
|
|
this.currentRoom.draw(ctx)
|
2025-06-01 15:54:55 -04:00
|
|
|
this.actors.forEach(actor => actor.draw(ctx))
|
2025-06-07 09:28:18 -04:00
|
|
|
this.message?.draw(ctx)
|
2025-06-01 15:30:12 -04:00
|
|
|
}
|
|
|
|
}
|