A lightweight JavaScript game engine
git clone git://soophie.de/game-engine
blob: 749e97544772a092b408d891a84cfbe8e8239722 (1822 bytes)[doc][blame][raw]
1
import GameEngine from './game-engine.js';2
import { scaleCanvas } from './util/canvas.js';4
export default class Game {5
constructor(width, height, { fps } = {}) {6
this.width = width || 900;7
this.height = height || 600;8
this.fps = 1000 / (fps || 60);9
this.then = Date.now();10
this.running = false;11
this.canvas = document.createElement('canvas');12
scaleCanvas(this.canvas, this.width, this.height);13
this.g = this.canvas.getContext('2d');14
this.g.imageSmoothingEnabled = false;15
this.events = [];16
this.sprites = [];17
GameEngine.instance = this;18
}19
async start() {20
for(const sprite of this.sprites) {21
await sprite.load();22
}23
this.running = true;24
if(this.oninit) {25
this.oninit();26
}27
requestAnimationFrame(this.loop.bind(this));28
this.update();29
this.render(this.g);30
}31
quit() {32
this.running = false;33
if(this.onquit) {34
this.onquit();35
}36
}37
loop() {38
try {39
if(this.running) {40
requestAnimationFrame(this.loop.bind(this));41
this.now = Date.now();42
this.elapsed = this.now - this.then;43
if(this.elapsed > this.fps) {44
this.then = this.now - (this.elapsed % this.fps);45
for(const event of this.events) {46
if(this['on' + event.type]) {47
this['on' + event.type](event);48
}49
}50
this.update();51
this.render(this.g);52
this.events = [];53
}54
}55
}56
catch(error) {57
console.error(error);58
this.running = false;59
}60
}61
update() {62
// nothing63
}64
render() {65
this.g.clearRect(0, 0, this.width, this.height);66
}67
resize(width, height) {68
this.width = width;69
this.height = height;70
scaleCanvas(this.canvas, this.width, this.height);71
this.g.imageSmoothingEnabled = false;72
}73
bindEvent(element, type) {74
element['on' + type] = event => this.events.push(event);75
}76
loadSprite(sprite) {77
this.sprites.push(sprite);78
}79
}