unibutton/static/js/index.js

83 lines
2 KiB
JavaScript
Raw Normal View History

2024-11-25 14:14:20 -05:00
const cs = 1024;
const assets = [
'assets/player.svg',
'assets/head.svg',
];
class Game extends GameBasic {
constructor() {
super();
let assetsIn = {};
for (let asset in assets) {
assetsIn[asset] = new Image();
assetsIn[asset].src = assets[asset];
}
let canvas = document.querySelector("#canvas");
canvas.width = canvas.height = cs;
this.canvas = canvas;
this.ctx = canvas.getContext("2d");
this.assetsIn = assetsIn;
2024-11-25 14:14:20 -05:00
}
render () {
let { ctx, assetsIn, entities, player } = this;
ctx.clearRect(0, 0, cs, cs);
2024-11-25 14:14:20 -05:00
ctx.save();
ctx.translate(player.camera.x + cs / 2, player.camera.y + cs / 2);
for (let ent of entities) {
ctx.save();
ctx.translate(ent.pos.x, ent.pos.y);
ctx.rotate(ent.rot);
ctx.drawImage(assetsIn[1], -64 / 2, -128, 64, 128);
ctx.restore();
ctx.drawImage(assetsIn[0], ent.pos.x - 64 / 2, ent.pos.y - 64 / 2, 64, 64);
}
2024-11-25 14:14:20 -05:00
ctx.restore();
if (player.health <= 0) {
ctx.fillStyle = 'rgba(0,0,0,0.5)';
ctx.fillRect(0, 0, cs, cs);
ctx.fillStyle = 'rgb(255,255,255)';
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = "bold 48px sans-serif";
ctx.fillText('You died! Click to respawn', cs / 2, cs / 2);
}
2024-11-25 14:14:20 -05:00
}
ui() {
document.querySelector('.ui-text').textContent = `HP: ${this.player.health}`
}
click() {
let { player } = this;
if (player.health <= 0) {
game = new Game();
} else {
player.bump();
}
}
init(){
super.init();
setInterval(function () { game.render() }, 1000 / 60);
setInterval(function () { game.ui() }, 1000 / 10);
2024-11-25 14:14:20 -05:00
}
2024-11-25 14:14:20 -05:00
}
var game = new Game();
game.init();
2024-11-25 14:14:20 -05:00
game.canvas.onclick = () => game.click();