finally, now multiplayer

This commit is contained in:
biglyderv 2024-11-25 14:14:20 -05:00
parent 873102a927
commit b1501d7251
6 changed files with 93 additions and 17 deletions

View file

@ -17,9 +17,7 @@
<canvas id='canvas'></canvas>
</div>
</section>
<script src='js/player.js'></script>
<script src='js/game_basic.js'></script>
<script src='js/index.js'></script>
<script src='js/index.js' type="module"></script>
</body>
</html>

View file

@ -1,3 +1,6 @@
import Player from "./player.js";
import GameBasic from "./game_basic.js";
const cs = 1024;
const assets = [
'assets/player.svg',
@ -52,7 +55,7 @@ class Game extends GameBasic {
ctx.textBaseline = "bottom";
ctx.font = "bold 16px sans-serif";
let args = [`HP: ${ent.health} KO: ${ent.headCount}`, ent.pos.x, ent.pos.y - 64 / 2];
let args = [`HP: ${ent.health} KO: ${ent.headCount} XY: ${Math.round(ent.pos.x)}, ${Math.round(ent.pos.y)}`, ent.pos.x, ent.pos.y - 64 / 2];
ctx.strokeText(...args);
ctx.fillText(...args);
@ -74,18 +77,49 @@ class Game extends GameBasic {
let { player } = this;
if (player.health <= 0) {
this.ws = new WebSocket(window.location.href);
this.player = new Player(false, true);
this.entities.push(this.player);
} else {
player.bump();
}
}
sync() {
let { player } = this;
let { vel, dir, you } = player;
this.ws.send(JSON.stringify({ vel, dir, you }));
}
recv({data}) {
let {player} = this;
let you = player.you;
let entList = JSON.parse(data);
entList = entList.map(x => {
x.handleTick = Player.prototype.handleTick;
return x;
})
let matchingPlayer = entList.filter(x => x.you == you)
this.player = Object.assign(this.player || new Player(false,false),matchingPlayer[0]);
this.entities = entList;
if (this.entities.length == 0) this.entities = [this.player];
}
init() {
super.init();
let that = this;
this.ws = new WebSocket(window.location.href);
this.ws.addEventListener('message',function(e) { that.recv(e) });
setInterval(function () { that.render() }, 1000 / 60);
setInterval(function () { that.sync() }, 1000 / 20);
game.canvas.onclick = () => that.click();
}
@ -93,4 +127,4 @@ class Game extends GameBasic {
var game = new Game();
game.init();
game.init();