-
Notifications
You must be signed in to change notification settings - Fork 29
/
game.js
executable file
·424 lines (352 loc) · 10.5 KB
/
game.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
let util = require("util"), // Utility resources (logging, object inspection, etc)
express = require('express'),
app = express(),
port = 8000,
io = require('socket.io').listen(app.listen(port)),
MongoClient = require('mongodb').MongoClient,
Player = require("./Player").Player, // Player class
Enemy = require("./Enemy").Enemy, // Enemy class
Level = require("./Level").Level,
Item = require("./Item").Item, // Player class
Npc = require("./Npc").Npc,
mongoUrl = 'mongodb://localhost:27017/mmorpg',
dbConnection,
db,
quests = require("./questlist").questlist,
socket, // socket controller
players = [], // connected players
enemies = [],
npcs = [],
items = [],
world, // map to draw
collisionMap = [],
worldSize,
tileSize;
app.use(express.static(__dirname + '/public'));
MongoClient.connect(mongoUrl, { useNewUrlParser: true }, function(err, client) {
if (err) throw err;
dbConnection = client;
db = client.db('mmorpg');
//client.close();
});
function init() {
// Initialize the world array
world = Level.getMap(1);
worldSize = Level.getWorldSize();
tileSize = Level.getTileSize();
// Create empty collision map and init enemy array
let enemyID = 0;
for (var x = 0; x < worldSize; x++) {
collisionMap[x] = [];
for (var y = 0; y < worldSize; y++) {
if (world[x][y] == 0) {
collisionMap[x][y] = 0;
}
else if (world[x][y] == 1) {
collisionMap[x][y] = 1;
var newEnemy = new Enemy(x * tileSize, y * tileSize, enemyID, 20);
enemies.push(newEnemy);
enemyID++;
}
else {
collisionMap[x][y] = 3;
}
}
}
// Init npc array
var npcList = Level.getNpcList();
// Fill collision map
for (var i = 0; i < npcList.length; i += 1) {
var newNpc = new Npc(npcList[i].id, npcList[i].x * tileSize, npcList[i].y * tileSize, npcList[i].name, npcList[i].questID);
npcs.push(newNpc);
collisionMap[npcList[i].x][npcList[i].y] = 2;
}
setEventHandlers();
};
// Game event handlers
var setEventHandlers = function() {
io.sockets.on("connection", onSocketConnection);
};
// New socket connection
function onSocketConnection(client) {
util.log("Player connected: " + client.id);
// Listen for client disconnected
client.on("disconnect", onClientDisconnect);
// Listen for new player message
client.on("player connected", onPlayerConnect);
// Listen for player updates
client.on("update player", onUpdatePlayer);
// Listen for new messages
client.on("new message", onNewMessage);
// Listen for logout
client.on("logout", onLogout);
// Player going to fight
client.on("start fight", onStartFight);
// Player ended fight
client.on("abort fight", onAbortFight);
};
function onPlayerConnect(data) {
var toClient = this;
if (!data.name) {
toClient.emit("no player");
}
db.collection('users').findOne( { name: data.name }, function(err, savedUser) {
if (err || !savedUser) {
toClient.emit("no player");
var player = new Player(128, 192, data.name, 100);
db.collection('users').insertOne(player, function(err2, savedUser2) {
if (err2 || !savedUser2) {
// Error occurred
}
else {
// User saved
}
});
}
else {
toClient.emit("validated");
joinPlayer(toClient, data.name);
}
});
};
function joinPlayer(client, name) {
// Send world-data to client
client.emit("init map", {world: world, tileSize: tileSize, worldSize: worldSize});
// Send existing enemies to client
for (var i = 0; i < enemies.length; i++) {
if (enemies[i].alive) {
client.emit("update enemy", {enemy: enemies[i]});
}
}
// Send available quests to client
for (var i = 0; i < quests.length; i++) {
client.emit("update quest", quests[i]);
}
// Send existing items to client
for (var i = 0; i < items.length; i++) {
client.emit("new item", items[i]);
}
// Send existing npcs to client
for (var i = 0; i < npcs.length; i++) {
var npc = npcs[i];
client.emit("new npc", npc);
}
client.emit("init collisionMap", collisionMap);
var player = playerByName(name);
// New Localplayer
if (!player) {
for (var i = 0; i < players.length; i++) {
client.emit("update player", players[i]);
};
// Create a new player
player = new Player(320, 128, name, 100, client.id);
// Add new player to the players array
players.push(player);
// Broadcast new player to connected socket clients
client.broadcast.emit("update player", player);
client.broadcast.emit("new message", {player: name, text: "joined the game", mode: "s"});
}
// Existing Localplayer
else {
// Update the old ID
var oldID = player.id;
for (var j = 0; j < players.length; j++) {
if (players[j].id == oldID) {
players[j].id = client.id;
}
else {
client.broadcast.emit("update player", players[j]);
}
};
}
client.emit("create localplayer", player);
};
function onStartFight(data) {
var player = playerById(data.id);
if (player) {
player.setGoFight(data.enemyID);
}
};
function onAbortFight(data) {
var player = playerById(data.id);
if (player) {
player.stopFight();
}
}
var calculateDamage = function(att, def) {
// Math.random() * (max - min + 1) + min;
var damage = Math.floor((Math.random()*((att - def) - (att - def - 8))) + (att - def - 8));
if (damage < 0) damage = 0;
return damage;
}
var fightLoop = setInterval(function() {
for (i = 0; i < enemies.length; i++) {
if (enemies[i].readyToHit()) {
var player = playerById(enemies[i].fightingAgainst());
if (!player) {
continue;
}
player.getHurt(enemies[i].strength);
enemies[i].setLastStrike(Date.now());
if (!player.alive) {
enemies[i].killedPlayer(player.id);
}
io.sockets.emit("player hurt", {id: player.id, amount: enemies[i].strength});
io.sockets.emit("update player", player);
}
else if (!enemies[i].alive && (Date.now() - enemies[i].killTime > enemies[i].respawnTime)) {
// If player stands on the tile, don't respawn yet (first is for passing tile, second - after || - is for right on the tile
for (var j = 0; j < players.length; j++) {
if ((players[j].pos.x > enemies[i].x && players[j].pos.x < enemies[i].x + 32 &&
players[j].pos.y > enemies[i].y && players[j].pos.y < enemies[i].y + 32) ||
(players[j].pos.x == enemies[i].x && players[j].pos.y == enemies[i].y))
{
break;
}
}
enemies[i].setAlive();
io.sockets.emit("update enemy", {enemy: enemies[i]});
world[enemies[i].x / 32][enemies[i].y / 32] = 1;
var item = getItem(enemies[i].x, enemies[i].y);
if (item) {
io.sockets.emit("update item", {item: item, remove: true});
removeItem(enemies[i].x, enemies[i].y);
}
}
}
for (var j = 0; j < players.length; j++) {
var enemyID = players[j].fighting;
if (players[j].readyToHit() && enemies[enemyID]) {
var enemy = enemies[enemyID];
var tileX = enemy.x / 32;
var tileY = enemy.y / 32;
players[j].setLastStrike(Date.now());
var damage = calculateDamage(players[j].strength, enemy.def);
enemy.getHurt(damage);
io.sockets.emit("update enemy", {enemy: enemy, amount: damage});
if (!enemy.alive) {
world[tileX][tileY] = 0;
players[j].stopFight();
dropItem(tileX * 32, tileY * 32);
break;
}
}
}
}, 16);
function onLogout(data) {
var player = playerById(this.id);
if (!player) {
return;
}
this.broadcast.emit("new message", {player: player.name, text: "left the game", mode: "s"});
players.splice(this.id, 1);
this.broadcast.emit("remove player", {id: this.id});
};
// Socket client has disconnected
function onClientDisconnect(data) {
util.log("disconnect: " + this.id);
//this.emit("disconnect");
};
function onUpdatePlayer(data) {
var player = playerById(this.id);
// Player not found
if (!player) {
return;
};
// Update player position
player.pos.x = data.x;
player.pos.y = data.y;
player.dir = data.dir;
// Check if player stepped on an item
var item = getItem(player.pos.x, player.pos.y);
if (item) {
io.sockets.emit("update item", {item: item, remove: true}); // TO-DO: only player who got the item should be informed
io.sockets.emit("get item", {item: item, quantity: item.quantity});
player.takeItem(item.type, item.quantity);
removeItem(player.pos.x, player.pos.y);
}
// Broadcast updated position to connected socket clients
this.broadcast.emit("update player", player);
if (data.enemyID != null) {
player.fighting = data.enemyID;
enemies[data.enemyID].startFight(data.id);
}
}
/*var gameLoop = setInterval(function() {
for (var i = 0; i < players.length; i++) {
io.sockets.emit("update player", {player: players[i]});
}
}, 16);*/
function dropItem(x, y) {
var chance = Math.round(Math.random() * 100);
if (chance < 100) {
var id = (chance < 40) ? 11 : 10;
var quantity = (id == 11 && chance < 40) ? 20 : null;
var item = new Item(Date.now(), id, x, y, quantity);
items.push(item);
io.sockets.emit("update item", {item: item});
}
};
function getItem(x, y) {
for (var i = 0; i < items.length; i++) {
if (items[i].x == x && items[i].y == y) {
return items[i];
}
}
return false;
};
function removeItem(x, y) {
for (var i = 0; i < items.length; i++) {
if (items[i].x == x && items[i].y == y) {
items.splice(i, 1);
break;
}
}
};
function onNewMessage(data) {
var player = playerById(this.id);
if (data.chatTo) {
var chatTo = playerByName(data.chatTo);
if (data.mode == "w" && chatTo) {
io.to(chatTo.id).emit("new message", {player: player.name, text: data.text, mode: data.mode});
}
else if (!chatTo) {
this.emit("new message", {player: data.chatTo, text: "Player " + data.chatTo + " doesn't exist!", mode: "s"});
}
}
else {
io.sockets.emit("new message", {player: player.name, text: data.text, mode: data.mode});
}
}
// Helper
function playerById(id) {
for (var i = 0; i < players.length; i++) {
if (players[i].id == id) {
return players[i];
}
}
return false;
}
function playerByName(name) {
for (var j = 0; j < players.length; j++) {
if (players[j].name == name) {
return players[j];
}
};
return false;
};
// Run the game
init();
/*****************************************
* NOTES
*****************************************
$ sudo apt-get install mongodb
$ sudo npm install mongojs
Dann, um auf die DB zuzugreifen:
mongo mongoapp
Commands für darin (die collection "users" wird oben beim connect schon erstellt):
show collections - zeigt alle collections in der DB
db.users.find() - listet alle Dokumente in der DB auf
db.users.drop() - löscht die collection
db.users.findOne( { playerName: data.playerName } ) - durchsucht alle Dokumente nach dem value
db.users.ensureIndex({id:1}, {unique : true}); - sorgt dafür, dass jede ID nur einmal vorkommt */