Files
pacman.js/Game.js
2019-06-11 18:46:14 +02:00

114 lines
3.1 KiB
JavaScript

class Game {
constructor() {
this.canvas = document.body.createChild('canvas', 'pacman-game');
this.ctx = this.canvas.getContext('2d');
this.loadMap();
this.onResize();
this.gameObjects = [];
this.paused = false;
this.gameOver = false;
this.init();
}
init() {
this.gameObjects.push(new Player(this, this.map.spawn.x + 0.5, this.map.spawn.y + 0.5));
this.gameObjects.push(new Ghost(this, 5.5, 6.5));
// this.gameObjects.push(new Ghost(this, 3.5, 20.5));
// this.gameObjects.push(new Ghost(this, 10.5, 7.5));
// this.gameObjects.push(new Ghost(this, 19.5, 12.5));
this.registerKeyListeners();
this.registerWindowListeners();
}
registerKeyListeners() {
window.addEventListener('keydown', (event) => {
const key = event.key;
switch (key) {
case 'ArrowLeft':
this.getPlayer().changeDir({x: -1, y: 0});
break;
case 'ArrowUp':
this.getPlayer().changeDir({x: 0, y: -1});
break;
case 'ArrowRight':
this.getPlayer().changeDir({x: 1, y: 0});
break;
case 'ArrowDown':
this.getPlayer().changeDir({x: 0, y: 1});
break;
}
});
}
registerWindowListeners() {
window.addEventListener('resize', (event) => {
this.onResize();
});
}
onResize() {
this.calculateConf(window.innerWidth, window.innerHeight);
this.canvas.width = this.conf.tileSize * this.map.width;
this.canvas.height = this.conf.tileSize * this.map.height;
this.canvas.style.width = this.canvas.width + 'px';
this.canvas.style.height = this.canvas.height + 'px';
}
loadMap() {
const mapLoader = new MapLoader("levels/level1.pacmap");
mapLoader.start();
this.map = mapLoader.getMap();
}
calculateConf(width, height) {
this.conf = {
tileSize: calculateTileSize(width, height, this.map.width, this.map.height),
};
}
getGameObjectsByType(type) {
return this.gameObjects.filter(object => object instanceof type);
}
getPlayer() {
return this.getGameObjectsByType(Player)[0];
}
draw() {
this.ctx.clearRect(0, 0, this.canvas.clientWidth, this.canvas.clientHeight);
this.map.draw(this.ctx, this.conf);
this.gameObjects.forEach(object => {
object.draw(this.ctx, this.conf);
});
requestAnimationFrame(() => this.draw());
}
update(lastUpdate) {
const updateTime = Date.now();
const deltaTime = updateTime - lastUpdate || 16;
this.gameObjects.forEach(object => {
object.update(deltaTime);
});
if (!this.paused && !this.gameOver)
requestAnimationFrame(() => this.update(updateTime));
}
start() {
this.draw();
this.update();
}
}