-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
82 lines (66 loc) · 2.64 KB
/
script.js
File metadata and controls
82 lines (66 loc) · 2.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { CLIENT_TICK, DISCONNECT, INIT, SERVER_TICK } from "./emits.js";
import Game from "./src/Game.js";
window.onload = () => {
const queryString = window.location.search;
if (queryString.includes('dev')) {
const playerName = Math.random().toString(16).slice(2, 10);
document.getElementById('login').style.display = 'none';
document.getElementById('game').style.display = 'block';
initGame(playerName);
} else {
const loginButton = document.getElementById('login-button');
loginButton.addEventListener('click', async () => {
const playerName = document.getElementById('player-name').value;
if (playerName && playerName.length > 0 && playerName.length < 10 && playerName.match(/^[a-zA-Z0-9]+$/)) {
document.getElementById('login').style.display = 'none';
document.getElementById('game').style.display = 'block';
initGame(playerName);
}
});
}
};
const initGame = async (playerName) => {
const canvas = document.getElementById('canvas1');
const ctx = canvas.getContext('2d');
canvas.height = 624;
canvas.width = 624;
const SERVER_URL = await fetch(`${window.location.origin}/api/server-url`)
.then((res) => res.json())
.then((data) => data.SERVER_URL);
const map = await fetch(`${window.location.origin}/api/map`)
.then((res) => res.json())
.then((data) => data.map);
const socket = io(SERVER_URL);
let { player, players, mobs } = await socket.emitWithAck(INIT, {
playerName,
});
console.log('player', playerName);
delete players[playerName];
socket.on(DISCONNECT, () => { // Update page on disconnect
window.location.href = window.location.href;
});
const game = new Game(canvas.width, canvas.height, map, player, players, mobs, socket);
let lastTime = 0;
socket.on(SERVER_TICK, (gameData) => {
game.updatePlayers(gameData.players);
game.updateEntities(gameData.mobs);
});
function animate(timeStamt = 0) {
const deltaTime = timeStamt - lastTime;
lastTime = timeStamt;
ctx.clearRect(0, 0, canvas.width, canvas.height);
game.update(deltaTime);
game.draw(ctx);
requestAnimationFrame(animate);
}
setInterval(() => {
socket.emit(CLIENT_TICK, {
worldX: game.player.getWorldXPixel(),
worldY: game.player.getWorldYPixel(),
direction: game.player.direction,
currentState: game.player.currentState.state,
speed: game.player.getSpeed(),
});
}, 3);
animate();
};