-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
538 lines (486 loc) · 19.4 KB
/
index.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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
/* --- */
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
/* --- */
function Player() {
this.name = 'Guest';
this.map = null;
this.coords = null;
this.level = 1;
this.exp = 0;
this.inventary = [];
this.equipments = {
head: null,
chest: null,
legs: null,
arms: null,
primary: null,
secondary: null
};
this.gold = 0;
this.str = 5;
this.dex = 5;
this.int = 5;
}
function Item(file) {
this.id = null;
this.name = null;
this.price = null;
this.type = null;
this.bonus = [];
this.load = function(file) {
var data = fs.readFileSync('items/'+file+'.item');
data = data.toString();
data = data.split("\n");
this.id = file;
for (var i = 0; i < data.length; i++) {
var attribute = data[i].substr(0,data[i].indexOf(':'));
var value = data[i].substr(data[i].indexOf(':')+1);
switch (attribute) {
case 'name':
case 'price':
case 'type':
this[attribute] = value;
break;
case 'bonus':
var bonusAttribute = value.substr(0,value.indexOf(','));
var bonusValue = value.substr(value.indexOf(',')+1);
var index = this.bonus.length;
this.bonus[index] = [];
this.bonus[index][bonusAttribute] = parseInt(bonusValue);
break;
default:
break;
}
}
};
if (file) this.load(file);
}
function Map(file) {
this.dimensions = null;
this.data = null;
this.spawn = null;
this.warp = null;
this.name = null;
this.title = null;
this.playersAt = null;
this.load = function (file) {
var data = fs.readFileSync('maps/'+file+'.map');
data = data.toString();
data = data.split("\n");
this.name = file;
var info = data[0].split(',');
this.title = info[0];
this.dimensions = [parseInt(info[1]), parseInt(info[2])];
this.data = [];
this.playersAt = [];
for (var i = 1; i <= this.dimensions[0]; i++) {
this.data[i-1] = data[i];
this.playersAt[i-1] = [];
for (var j = 0; j < this.dimensions[1]; j++) {
this.playersAt[i-1][j] = [];
}
}
this.warp = [];
for (var i = this.dimensions[0]+1; i < data.length; i++) {
var area = data[i].split(',');
if (area.length == 3) {
if (area[0] == '_spawn') this.spawn = [parseInt(area[1]),parseInt(area[2])];
else {
this.warp.push({
map: area[0],
coords: [parseInt(area[1]),parseInt(area[2])]
});
}
}
else if (area.length == 5) {
this.warp.push({
map: area[0],
coords: [parseInt(area[1]),parseInt(area[2])],
destination: [parseInt(area[3]),parseInt(area[4])]
});
}
}
};
if (file) this.load(file);
}
function Npc(file) {
this.id = new Date().getTime()+''+Math.floor(Math.random()*10000);
this.name = null;
this.map = null;
this.spawn = null;
this.type = null;
this.speed = null;
this.coords = null;
this.npc = true;
this.load = function(file) {
var data = fs.readFileSync('npcs/'+file+'.npc');
data = data.toString();
data = data.split("\n");
for (var i = 0; i < data.length; i++) {
var attribute = data[i].substr(0,data[i].indexOf(':'));
var value = data[i].substr(data[i].indexOf(':')+1);
switch (attribute) {
case 'name':
case 'map':
case 'type':
this[attribute] = value;
break;
case 'speed':
this[attribute] = parseInt(value);
break;
case 'spawn':
this[attribute] = value.split(',');
this[attribute][0] = parseInt(this[attribute][0]);
this[attribute][1] = parseInt(this[attribute][1]);
break;
default:
break;
}
}
if (this.spawn) this.spawnNow();
};
this.spawnNow = function() {
this.coords = [this.spawn[0],this.spawn[1]];
maps[this.map].playersAt[this.spawn[0]][this.spawn[1]].push(this);
npcs.spawned.push(this);
};
if (file) this.load(file);
}
/* --- */
function loadMaps() {
var files = fs.readdirSync(__dirname + '/maps');
for (var i = 0; i < files.length; i++) {
if (files[i].substr(files[i].length - 4,4) != '.map') continue;
files[i] = files[i].slice(0,-4);
maps[files[i]] = new Map(files[i]);
}
}
maps = {};
loadMaps();
/* --- */
function loadItems() {
var files = fs.readdirSync(__dirname + '/items');
for (var i = 0; i < files.length; i++) {
if (files[i].substr(files[i].length - 5,5) != '.item') continue;
files[i] = files[i].slice(0,-5);
items[files[i]] = new Item(files[i]);
}
}
items = {};
loadItems();
/* --- */
function loadNpcs() {
var files = fs.readdirSync(__dirname + '/npcs');
for (var i = 0; i < files.length; i++) {
if (files[i].substr(files[i].length - 4,4) != '.npc') continue;
files[i] = files[i].slice(0,-4);
npcs.data[files[i]] = new Npc(files[i]);
}
}
npcs = { data: {}, spawned: [] };
loadNpcs();
npcMovement = setInterval(moveNpcs,1000);
/* --- */
app.get('/', function(req, res){
res.sendFile(__dirname + '/views/index.html');
});
/* --- */
io.on('connection', function(socket) {
console.log('[+] A user connected.');
socket.emit('log', '*** Welcome to the game, type /help to see the list of commands.');
io.emit('log', '['+getTimestamp()+'] * A new player joined the game.');
// creating player data
socket.player = new Player();
socket.player.map = 'world';
socket.player.coords = maps['world'].spawn;
maps[socket.player.map].playersAt[socket.player.coords[0]][socket.player.coords[1]].push(socket);
sendCoords(socket);
sendPlayerName(socket);
sendPlayerStats(socket);
sendInventary(socket);
sendEquipments(socket);
updateNearby(socket);
socket.on('disconnect', function(){
console.log('[-] User disconnected.');
io.emit('log', '['+getTimestamp()+'] * '+socket.player.name+' has left the game.');
var socketIndex = maps[socket.player.map].playersAt[socket.player.coords[0]][socket.player.coords[1]].indexOf(socket);
maps[socket.player.map].playersAt[socket.player.coords[0]][socket.player.coords[1]].splice(socketIndex,1);
updateNearby(socket);
});
socket.on('move', function(direction) {
var x = 0;
var y = 0;
switch (direction) {
case 'n':
y = -1;
break;
case 's':
y = 1;
break;
case 'e':
x = 1;
break;
case 'w':
x = -1;
break;
default:
break;
}
// calculating new coords
var newcoords = [socket.player.coords[0], socket.player.coords[1]];
if (socket.player.coords[0]+y == maps[socket.player.map].dimensions[0]) newcoords[0] = 0;
else if (socket.player.coords[0]+y < 0) newcoords[0] = maps[socket.player.map].dimensions[0] - 1;
else newcoords[0] += y;
if (socket.player.coords[1]+x == maps[socket.player.map].dimensions[1]) newcoords[1] = 0;
else if (socket.player.coords[1]+x < 0) newcoords[1] = maps[socket.player.map].dimensions[1] - 1;
else newcoords[1] += x;
// check if there's a warp in this position
var warp = -1;
for (var i = 0; i < maps[socket.player.map].warp.length; i++) {
if ((maps[socket.player.map].warp[i].coords[0] == newcoords[0]) && (maps[socket.player.map].warp[i].coords[1] == newcoords[1])) {
warp = i;
break;
}
}
if (warp != -1) {
// removing actual player location on the map for other players
var socketIndex = maps[socket.player.map].playersAt[socket.player.coords[0]][socket.player.coords[1]].indexOf(socket);
maps[socket.player.map].playersAt[socket.player.coords[0]][socket.player.coords[1]].splice(socketIndex,1);
updateNearby(socket);
// updating player's own location and map
if (typeof maps[socket.player.map].warp[warp].destination !== 'undefined') {
socket.player.coords = maps[socket.player.map].warp[warp].destination;
}
else
socket.player.coords = maps[maps[socket.player.map].warp[warp].map].spawn;
socket.player.map = maps[socket.player.map].warp[warp].map;
// updating player location on the map for other players
maps[socket.player.map].playersAt[socket.player.coords[0]][socket.player.coords[1]].push(socket);
// updating map of nearby players and the client itself
updateNearby(socket);
// sending coords to the client
sendCoords(socket);
}
else {
// checking collision
switch (maps[socket.player.map].data[newcoords[0]][newcoords[1]]) {
case '~':
case '-':
break;
default:
// removing actual player location on the map for other players
var socketIndex = maps[socket.player.map].playersAt[socket.player.coords[0]][socket.player.coords[1]].indexOf(socket);
maps[socket.player.map].playersAt[socket.player.coords[0]][socket.player.coords[1]].splice(socketIndex,1);
// updating player's own location
socket.player.coords = newcoords;
// updating player location on the map for other players
maps[socket.player.map].playersAt[socket.player.coords[0]][socket.player.coords[1]].push(socket);
// updating map of nearby players and the client itself
updateNearby(socket);
// sending coords to the client
sendCoords(socket);
break;
}
}
});
socket.on('chat', function(msg) {
if (msg.substr(0,1) == '/') {
var params = msg.substr(1).split(' ');
switch (params[0]) {
case 'help':
var message = "*** Help ***\n";
message += "*** /name <new_name> - Changes your player name.\n";
message += "*** /map - Shows the full map.\n";
message += "*** /players - Shows the players online.\n";
message += "*** /hotkeys - Displays the available hotkeys.";
socket.emit('log', message);
break;
case 'name':
io.emit('log', '['+getTimestamp()+'] * '+socket.player.name+' has changed name to '+params[1]);
socket.player.name = params[1];
sendPlayerName(socket);
break;
case 'map':
drawFullMap(socket);
break;
case 'players':
var message = "*** Players online: "+io.sockets.sockets.length+" ***\n";
for (var i = 0; i < io.sockets.sockets.length; i++)
message += "*** "+io.sockets.sockets[i].player.name+"\n";
socket.emit('log', message);
break;
case 'hotkeys':
var message = "*** Hotkeys ***\n";
message += "*** Arrow keys - Moves the character.\n";
message += "*** T - Goes to the chat input.\n";
message += "*** Escape - Leaves the chat input and goes back to the game.\n";
message += "*** M - Displays the full map.";
socket.emit('log', message);
break;
default:
socket.emit('log', '*** Unknown command.');
break;
}
}
else io.sockets.emit('chat', '['+getTimestamp()+'] <'+socket.player.name+'> '+msg);
});
});
/* --- */
http.listen(3000, function(){
console.log('[*] Listening on *:3000');
});
/* --- */
function moveNpcs() {
var count = new Date().getSeconds();
for (var i = 0; i < npcs.spawned.length; i++) {
if ((count % npcs.spawned[i].speed) !== 0) continue;
// random direction
var direction = Math.floor(Math.random()*4);
var x = 0;
var y = 0;
switch (direction) {
case 0:
y = -1;
break;
case 1:
y = 1;
break;
case 2:
x = 1;
break;
case 3:
x = -1;
break;
default:
break;
}
// calculating new coords
var newcoords = [npcs.spawned[i].coords[0], npcs.spawned[i].coords[1]];
if (npcs.spawned[i].coords[0]+y == maps[npcs.spawned[i].map].dimensions[0]) newcoords[0] = 0;
else if (npcs.spawned[i].coords[0]+y < 0) newcoords[0] = maps[npcs.spawned[i].map].dimensions[0] - 1;
else newcoords[0] += y;
if (npcs.spawned[i].coords[1]+x == maps[npcs.spawned[i].map].dimensions[1]) newcoords[1] = 0;
else if (npcs.spawned[i].coords[1]+x < 0) newcoords[1] = maps[npcs.spawned[i].map].dimensions[1] - 1;
else newcoords[1] += x;
// checking collision
switch (maps[npcs.spawned[i].map].data[newcoords[0]][newcoords[1]]) {
case '~':
case '-':
break;
default:
// removing actual npc location on the map for other players
var socketIndex = maps[npcs.spawned[i].map].playersAt[npcs.spawned[i].coords[0]][npcs.spawned[i].coords[1]].indexOf(npcs.spawned[i]);
maps[npcs.spawned[i].map].playersAt[npcs.spawned[i].coords[0]][npcs.spawned[i].coords[1]].splice(socketIndex,1);
// updating npc's own location
npcs.spawned[i].coords = newcoords;
// updating npc location on the map for other players
maps[npcs.spawned[i].map].playersAt[npcs.spawned[i].coords[0]][npcs.spawned[i].coords[1]].push(npcs.spawned[i]);
// updating map of nearby players
updateNearby(npcs.spawned[i]);
break;
}
}
}
function drawFullMap(socket) {
var buffer = [];
for (var i = 0; i < maps[socket.player.map].dimensions[0]; i++) {
buffer[i] = maps[socket.player.map].data[i];
if (i == socket.player.coords[0])
buffer[i] = buffer[i].substr(0,socket.player.coords[1]) + '*' + buffer[i].substr(socket.player.coords[1]+1);
}
socket.emit('map',buffer);
}
function drawVisible(socket) {
var buffer = [];
var limit = [3,3];
var map_x;
var map_y;
var index = 0;
for (var i = socket.player.coords[0]-limit[0]; i <= socket.player.coords[0]+limit[0]; i++) {
buffer[index] = '';
if (i >= maps[socket.player.map].dimensions[0]) map_y = i-maps[socket.player.map].dimensions[0];
else if (i < 0) map_y = maps[socket.player.map].dimensions[0]+i;
else map_y = i;
for (var j = socket.player.coords[1]-limit[1]; j <= socket.player.coords[1]+limit[1]; j++) {
if (j >= maps[socket.player.map].dimensions[1]) map_x = j-maps[socket.player.map].dimensions[1];
else if (j < 0) map_x = maps[socket.player.map].dimensions[1]+j;
else map_x = j;
// buffers the map surrounding the client
if ((socket.player.coords[0] == map_y) && (socket.player.coords[1] == map_x)) buffer[index] += '*'; // player
else if (maps[socket.player.map].playersAt[map_y][map_x].length > 0) buffer[index] += '!'; // some other players
else buffer[index] += maps[socket.player.map].data[map_y][map_x]; // the map stuff itself
}
index++;
}
socket.emit('map',buffer);
}
function whatIsHere(socket) {
var total = maps[socket.player.map].playersAt[socket.player.coords[0]][socket.player.coords[1]].length;
var items = [];
for (var i = 0; i < total; i++) {
if (maps[socket.player.map].playersAt[socket.player.coords[0]][socket.player.coords[1]][i] == socket) continue;
var object = maps[socket.player.map].playersAt[socket.player.coords[0]][socket.player.coords[1]][i];
if (object.npc === true) items.push(object.name);
else items.push(object.player.name);
}
socket.emit('what is here',items);
}
function updateNearby(socket) {
var limit = [4,4];
if (socket.npc === true) socket.player = socket;
for (var i = socket.player.coords[0]-limit[0]; i <= socket.player.coords[0]+limit[0]; i++) {
if (i >= maps[socket.player.map].dimensions[0]) map_y = i-maps[socket.player.map].dimensions[0];
else if (i < 0) map_y = maps[socket.player.map].dimensions[0]+i;
else map_y = i;
for (var j = socket.player.coords[1]-limit[1]; j <= socket.player.coords[1]+limit[1]; j++) {
if (j >= maps[socket.player.map].dimensions[1]) map_x = j-maps[socket.player.map].dimensions[1];
else if (j < 0) map_x = maps[socket.player.map].dimensions[1]+j;
else map_x = j;
// broadcast to nearby players including the client itself
for (var k = 0; k < maps[socket.player.map].playersAt[map_y][map_x].length; k++) {
if (maps[socket.player.map].playersAt[map_y][map_x][k].npc === true) continue; // if it's a npc, skip
drawVisible(maps[socket.player.map].playersAt[map_y][map_x][k]);
whatIsHere(maps[socket.player.map].playersAt[map_y][map_x][k]);
}
}
}
if (socket.npc === true) delete socket.player;
}
function sendCoords(socket) {
socket.emit('player coords',{
title: maps[socket.player.map].title,
coords: socket.player.coords
});
}
function sendEquipments(socket) {
socket.emit('equipments',socket.player.equipments);
}
function sendInventary(socket) {
socket.emit('inventary',{
gold: socket.player.gold,
items: socket.player.inventary
});
}
function sendPlayerStats(socket) {
socket.emit('stats',{
level: socket.player.level,
exp: socket.player.exp,
stats: {
str: socket.player.str,
dex: socket.player.dex,
int: socket.player.int,
}
});
}
function sendPlayerName(socket) {
socket.emit('player name',socket.player.name);
}
function getTimestamp() {
var date = new Date();
return ('0'+date.getHours()).slice(-2)+':'+('0'+date.getMinutes()).slice(-2)+':'+('0'+date.getSeconds()).slice(-2);
}