top-down-action-adventure/src/game.js

91 lines
2.3 KiB
JavaScript

import Player from "./player.js"
import Input from "./input.js"
import Event from "./event.js"
import Message from "./message.js"
import { average } from "./util.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
this.fpsBuffer = [60, 60, 60, 60, 60, 60, 60, 60, 60, 60]
}
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) {
this.dt = timestamp - this.timestamp
const fps = 1000 / this.dt
this.fpsBuffer.pop()
this.fpsBuffer.unshift(fps)
this.timestamp= timestamp
this.tick(this.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)
this.drawFps(ctx)
}
drawFps(ctx) {
ctx.fillStyle = "white"
ctx.fillRect(ctx.canvas.width, 0, -25, 20)
ctx.strokeStyle = "black"
ctx.textBaseline = "top"
ctx.textAlign = "right"
ctx.font = "bold 20px serif"
ctx.fillText(Math.round(average(this.fpsBuffer)), ctx.canvas.width, 0)
ctx.strokeText(Math.round(average(this.fpsBuffer)), ctx.canvas.width, 0)
}
}