-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
363 lines (316 loc) · 13.7 KB
/
script.js
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
const onlineMode = confirm("Запустить мултиплеер?");
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
let joystick = new JoyStick("joystick_el");
let joystick_direction = ["C"];
// This code keeps the canvas size fit the screen size
function updateSize() {
canvas.width = innerWidth;
canvas.height = innerHeight;
}
addEventListener("resize", updateSize);
updateSize();
let serverAddress = onlineMode ? prompt("Введите адрес сервера") : null;
let server = null; // WebSocket object will be created here later
let nickname = prompt("Введите ваш ник") ?? "Игрок";
nickname = nickname.trim();
if (nickname == "") nickname = "Игрок";
// ==== Render & collision settings ====
let blockSize = 64;
let playerSize = 48;
let moveCof = 4;
let cameraMoveScreenPrecentage = 30; // When to move camera
let camera = {
x: Math.floor(-canvas.width * (cameraMoveScreenPrecentage / 100)), // Camera position X
y: Math.floor(-canvas.height * (cameraMoveScreenPrecentage / 100)) // Camera position Y
}
// This is a class for any Player, no matter, offline or online.
class Player {
x = 1.5 * blockSize;
y = 1.5 * blockSize;
done = false;
walkFrameId = 0;
onlineId = -1; // If the multiplayer is not enabled, player has -1 as id
nickname = "Игрок";
texture = new Sprite(new CaImage("textures/spritesheet.png"), 64, 0, 11)
move(xof, yof) {
if (yof < 0) this.texture.indexY = 8;
else if (yof > 0) this.texture.indexY = 10;
else if (xof > 0) this.texture.indexY = 11;
else if (xof < 0) this.texture.indexY = 9;
this.walkCof += 1;
if (this.walkCof >= 8) this.walkCof = 0;
this.texture.indexX = this.walkCof;
this.x += xof;
this.y += yof;
if (this.x > (map[0].length - 2) * blockSize && this.y > (map.length - 2) * blockSize) this.done = true; else this.done = false;
if (onlineMode) onlineUpdate();
}
resetMove() {
if (this.walkCof != 0) {
this.walkCof = 0;
this.texture.indexX = this.walkCof;
if (onlineMode) onlineUpdate();
}
}
canMove(map) {
let canMove = {
up: true,
down: true,
left: true,
right: true
};
let xLeft = this.x - playerSize / 2;
let yTop = this.y - playerSize / 2;
let xRight = this.x + playerSize / 2;
let yBottom = this.y + playerSize / 2;
// LT = XL+YT; RT = XR+YT; LB = XL+YB; RB = XR+YB
let cellRight = Math.floor(xRight / blockSize);
let cellLeft = Math.floor(xLeft / blockSize);
let cellTop = Math.floor(yTop / blockSize);
let cellBottom = Math.floor(yBottom / blockSize);
if (this.y + playerSize / 2 == cellBottom * blockSize) cellBottom--;
if (this.x + playerSize / 2 == cellRight * blockSize) cellRight--;
canMove.up = !((map[cellTop - 1][cellLeft] == 2 || map[cellTop - 1][cellRight] == 2) && (this.y - playerSize / 2) == cellTop * blockSize);
canMove.down = !((map[cellBottom + 1][cellLeft] == 2 || map[cellBottom + 1][cellRight] == 2) && (this.y + playerSize / 2 == cellBottom * blockSize + blockSize));
canMove.left = !((map[cellTop][cellLeft - 1] == 2 || map[cellBottom][cellLeft - 1] == 2) && (this.x - playerSize / 2 == cellLeft * blockSize));
canMove.right = !((map[cellTop][cellRight + 1] == 2 || map[cellBottom][cellRight + 1] == 2) && (this.x + playerSize / 2 == cellRight * blockSize + blockSize));
return canMove;
}
}
function onlineUpdate() {
if (onlineMode) {
server.send(`update ${currentPlayer.nickname} ${currentPlayer.x} ${currentPlayer.y} ${currentPlayer.texture.indexX} ${currentPlayer.texture.indexY} ${currentPlayer.done ? 1 : 0}`);
}
}
let players = [];
let currentPlayer;
const globalTextures = {
wall: new CaImage("textures/wall.jpg"),
air: new CaImage("textures/air.jpg")
}
let map = [];
let autosolveQueue = [];
let onlineAskedFor = {
onlineId: false,
map: false,
players: false
}
const keyboard = { // Keyboard legacy object
w: false,
a: false,
s: false,
d: false
}
function onlineMessage(msg) {
msg = msg.data;
msg = msg.split(" ");
if (msg[0] == "you") {
let data = JSON.parse(msg[1]);
currentPlayer.onlineId = data.mid;
if (msg[2]) {
currentPlayer.x = data.x;
currentPlayer.y = data.y;
currentPlayer.texture.indexX = data.tIndexX;
currentPlayer.texture.indexY = data.tIndexY;
}
} else if (msg[0] == "map") {
let data = JSON.parse(msg[1]);
autosolveQueue = [];
map = data;
} else if (msg[0] == "np") {
let np = new Player();
let data = JSON.parse(msg[1]);
np.onlineId = data.mid;
np.nickname = data.nickname;
players.push(np);
} else if (msg[0] == "dp") {
let onlineId = msg[1];
for (let i = 0; i < players.length; i++) {
if (players[i].onlineId == onlineId) players.splice(i, 1);
}
} else if (msg[0] == "up") {
let data = JSON.parse(msg[1]);
for (let i = 0; i < players.length; i++) {
if (players[i].onlineId == data.mid) {
players[i].nickname = data.nickname;
players[i].x = data.x;
players[i].y = data.y;
players[i].texture.indexX = data.tIndexX;
players[i].texture.indexY = data.tIndexY;
}
}
} else if (msg[0] == "players") {
players = [];
let data = JSON.parse(msg[1]);
for (let i = 0; i < data.length; i++) {
if (currentPlayer.onlineId == data[i].mid) continue;
let p = new Player();
p.onlineId = data[i].mid;
p.nickname = data[i].nickname;
p.texture.indexX = data[i].tIndexX;
p.texture.indexY = data[i].tIndexY;
p.x = data[i].x;
p.y = data[i].y;
players.push(p);
}
players.push(currentPlayer);
}
}
// Keyboard handlers
document.addEventListener("keydown", function (event) {
const code = event.code;
const new_state = true;
if (code == "KeyW" || code == "ArrowUp") keyboard.w = new_state;
if (code == "KeyA" || code == "ArrowLeft") keyboard.a = new_state;
if (code == "KeyS" || code == "ArrowDown") keyboard.s = new_state;
if (code == "KeyD" || code == "ArrowRight") keyboard.d = new_state;
});
document.addEventListener("keyup", function (event) {
const code = event.code;
const new_state = false;
if (code == "KeyW" || code == "ArrowUp") keyboard.w = new_state;
if (code == "KeyA" || code == "ArrowLeft") keyboard.a = new_state;
if (code == "KeyS" || code == "ArrowDown") keyboard.s = new_state;
if (code == "KeyD" || code == "ArrowRight") keyboard.d = new_state;
});
document.addEventListener("keypress", function (event) {
const code = event.code;
if (code == "KeyU") {
solveInit();
}
});
document.getElementById("autosolve_button").addEventListener("click", solveInit);
function solveInit() {
currentPlayer.x = (Math.floor(currentPlayer.x / blockSize) + 0.5) * blockSize;
currentPlayer.y = (Math.floor(currentPlayer.y / blockSize) + 0.5) * blockSize;
autosolveQueue = solveMaze(map, Math.floor(currentPlayer.x / blockSize), Math.floor(currentPlayer.y / blockSize), 39, 39);
}
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // Fatal destruction of everything
for (let y = 0; y < map.length; ++y) for (let x = 0; x < map[y].length; x++) { // Cell rendering
if (map[y][x] == 2) {
ctx.drawImage(globalTextures.wall, x * blockSize - camera.x, y * blockSize - camera.y, blockSize, blockSize);
} else if (x == map[y].length - 2 && y == map.length - 2) {
ctx.fillStyle = "#0000ff";
ctx.fillRect(x * blockSize - camera.x, y * blockSize - camera.y, blockSize, blockSize);
} else if (map[y][x] == 1) {
ctx.drawImage(globalTextures.air, x * blockSize - camera.x, y * blockSize - camera.y, blockSize, blockSize);
}
}
if (autosolveQueue.length > 0) {
ctx.strokeStyle = "purple";
ctx.lineWidth = 3;
ctx.setLineDash([5, 5]);
ctx.beginPath();
ctx.moveTo(currentPlayer.x - camera.x, currentPlayer.y - camera.y);
ctx.lineTo((autosolveQueue[0].x + 0.5) * blockSize - camera.x, (autosolveQueue[0].y + 0.5) * blockSize - camera.y);
for (let i = 1; i < autosolveQueue.length; i++) {
ctx.lineTo((autosolveQueue[i].x + 0.5) * blockSize - camera.x, (autosolveQueue[i].y + 0.5) * blockSize - camera.y);
}
ctx.stroke();
}
for (let i = 0; i < players.length; i++) {
players[i].texture.render(ctx, players[i].x - playerSize / 2 - camera.x, players[i].y - playerSize / 2 - camera.y, playerSize, playerSize);
ctx.font = "20px Arial";
ctx.fillStyle = "red";
ctx.font = "16px Arial monospace";
ctx.textBaseline = "top";
ctx.textAlign = "center";
ctx.fillText(players[i].nickname, players[i].x - camera.x, players[i].y - playerSize / 2 - 5 - camera.y);
}
}
function app() {
if (currentPlayer == undefined) {
currentPlayer = new Player();
currentPlayer.nickname = nickname;
players.push(currentPlayer);
}
if (onlineMode) {
if (server == null) {
server = new WebSocket(`ws://${serverAddress}:8080`);
server.addEventListener("open", app);
server.addEventListener("message", onlineMessage);
server.addEventListener("error", event => alert("Произошла сетевая ошибка. Игра может быть нестабильной."));
return;
}
if (server.readyState != WebSocket.OPEN) {
alert("Соединение с сервером потеряно. Синхронизация остановлена.");
return;
}
if (currentPlayer.onlineId == -1) {
if (!onlineAskedFor.onlineId) {
onlineUpdate();
onlineAskedFor.onlineId = true;
}
}
if (map.length == 0) {
if (!onlineAskedFor.map) {
server.send("map");
onlineAskedFor.map = true;
}
}
if (players.length <= 1) {
if (!onlineAskedFor.players) {
server.send("players");
onlineAskedFor.players = true;
}
}
} else {
if (map.length == 0) map = convertMaze(generateMazeOld(20, 20));
}
joystick_direction = [...joystick.GetDir()];
let canMove = true; // Can player move at all (if we wouldn't check this, there could be a problem with sync)
if (onlineMode) if (!(currentPlayer.onlineId != -1 && map.length > 0 && players.length > 0)) canMove = false;
if (canMove) {
let availableDirections = currentPlayer.canMove(map);
// Joystick: WASD = NWSE
if (keyboard.w || joystick_direction.includes("N")) {
if (availableDirections.up) currentPlayer.move(0, -moveCof);
}
if (keyboard.a || joystick_direction.includes("W")) {
if (availableDirections.left) currentPlayer.move(-moveCof, 0);
}
if (keyboard.s || joystick_direction.includes("S")) {
if (availableDirections.down) currentPlayer.move(0, moveCof);
}
if (keyboard.d || joystick_direction.includes("E")) {
if (availableDirections.right) currentPlayer.move(moveCof, 0);
}
if (!keyboard.w && !keyboard.a && !keyboard.s && !keyboard.d && joystick_direction.includes("C")) {
if (autosolveQueue.length > 0) {
let cofX = 0, cofY = 0;
let nextBlock = autosolveQueue[0];
let targetX = (nextBlock.x + 0.5) * blockSize
let targetY = (nextBlock.y + 0.5) * blockSize;
if (targetX > currentPlayer.x) cofX = moveCof;
else if (targetX < currentPlayer.x) cofX = -moveCof;
if (targetY > currentPlayer.y) cofY = moveCof;
else if (targetY < currentPlayer.y) cofY = -moveCof;
currentPlayer.move(cofX, cofY);
if (currentPlayer.x == targetX && currentPlayer.y == targetY) autosolveQueue.shift();
} else {
currentPlayer.resetMove();
}
} else {
autosolveQueue = [];
}
}
if (!onlineMode && currentPlayer.done) {
currentPlayer.x = blockSize * 1.5;
currentPlayer.y = blockSize * 1.5;
currentPlayer.done = false;
currentPlayer.resetMove();
autosolveQueue = [];
map = convertMaze(generateMazeOld(20, 20));
}
let player_render_x = currentPlayer.x - camera.x;
let player_render_y = currentPlayer.y - camera.y;
if (player_render_x > canvas.width * (1 - cameraMoveScreenPrecentage / 100)) camera.x += moveCof;
if (player_render_x < canvas.width * (cameraMoveScreenPrecentage / 100)) camera.x -= moveCof;
if (player_render_y > canvas.height * (1 - cameraMoveScreenPrecentage / 100)) camera.y += moveCof;
if (player_render_y < canvas.height * (cameraMoveScreenPrecentage / 100)) camera.y -= moveCof;
render();
setTimeout(app, 1000 / 60);
}
app();