-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgameserver.js
472 lines (408 loc) · 18 KB
/
gameserver.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
// Simple grid-based game server
// License: MIT
"use strict";
require.paths.unshift('/Users/amitp/Projects/src/underscore')
var fs = require('fs');
var util = require('util');
var assert = require('assert');
var net = require('net');
var repl = require('repl');
var server = require('./Server');
var _ = require('underscore');
// Utility functions:
function setDifference(set1, set2) {
return set1.filter(function (x) { return set2.indexOf(x) < 0; });
}
// Map handling:
// Build the map tiles by combining data from three *.data files
var map = {width: 2048, height: 2048};
function buildMap() {
var elevation = fs.readFileSync("elevation.data");
var moisture = fs.readFileSync("moisture.data");
var overrides = fs.readFileSync("overrides.data");
map.tiles = new Buffer(map.width*map.height);
for (var i = 0; i < map.tiles.length; i++) {
var code = overrides[i] >> 4;
if (code === 1 || code === 5 || code === 6 || code === 7 || code === 8) {
// water
map.tiles[i] = 0;
} else if (code === 9 || code === 10 || code === 11 || code === 12) {
// road/bridge
map.tiles[i] = 1;
} else {
// combine moisture and elevation
map.tiles[i] = 2 + Math.floor(elevation[i]/255.0*9) + 10*Math.floor(moisture[i]/255.0*9);
}
}
}
buildMap();
// Chunks are blocks of the map. The server simulates objects one
// chunk at a time. The client subscribes to chunks. Events in the
// subscribed areas are sent to the client. A chunk id looks like
// "@chunk:x:y". Within that chunk the grid location is stored in x: y:
var chunkSize = 16;
function chunkLocationToId(chunkX, chunkY) {
var span = map.width / chunkSize;
assert.ok(0 <= chunkX && chunkX < span && 0 <= chunkY && chunkY < span,
"ERROR: chunkLocationToId(" + chunkX + "," + chunkY + ") out of range");
return '@chunk:' + chunkX + ':' + chunkY;
}
function chunkIdToLocation(chunkId) {
var span = map.width / chunkSize;
var parse = chunkId.split(':');
assert.equal(parse.length, 3);
assert.equal(parse[0], '@chunk');
return {chunkX: parseInt(parse[1], 10), chunkY: parseInt(parse[2], 10)};
}
function coordToChunkId(x, y) {
return chunkLocationToId(Math.floor(x / chunkSize), Math.floor(y / chunkSize));
}
function chunksSurroundingCoord(x, y) {
// TODO: we're currently generating a square but it would be
// better for the network (spread map loads out over time) if this
// were a circular region. TODO: hysteresis would help too
var radius = 9; // Approximate half-size of client viewport
var left = Math.floor((x - radius) / chunkSize);
var right = Math.ceil((x + radius) / chunkSize);
var top = Math.floor((y - radius) / chunkSize);
var bottom = Math.ceil((y + radius) / chunkSize);
var chunks = [];
for (var cx = left; cx < right; cx++) {
for (var cy = top; cy < bottom; cy++) {
chunks.push(chunkLocationToId(cx, cy));
}
}
// TODO: chunks should be sorted by distance from location
return chunks;
}
function chunkBounds(chunkId) {
var location = chunkIdToLocation(chunkId);
var left = location.chunkX * chunkSize;
var top = location.chunkY * chunkSize;
return {left: left, top: top, right: left+chunkSize, bottom: top+chunkSize};
}
function mapTileAt(x, y) {
if (0 <= x && x < map.width && 0 <= y && y < map.height) {
return map.tiles[x * map.height + y];
} else {
return null;
}
}
function constructMapTiles(left, right, top, bottom) {
// Clip the rectangle to the map and make sure bounds are sane
if (left < 0) left = 0;
if (right > map.width) right = map.width;
if (top < 0) top = 0;
if (bottom > map.height) bottom = map.height;
if (right < left) right = left;
if (bottom < top) bottom = top;
var tiles = [];
for (var x = left; x < right; x++) {
tiles.push(map.tiles.slice(x*map.height + top, x*map.height + bottom));
}
return {
left: left,
right: right,
top: top,
bottom: bottom,
binaryPayload: tiles.join("")
};
}
//////////////////////////////////////////////////////////////////////
// Server state
var clients = {}; // map from the client.id to the Client object
var clientDefaultLocation = {x: 945, y: 1220};
var contents = {}; // map from location id to set of objects at that location
var objects = {}; // map from object id to object
// Send a move event to clients. If the object is coming into
// existence or going out of existence, send an ins or del event
// instead.
function sendMoveEvent(object, src) {
var dst = object.loc;
_.values(clients).forEach(function (client) {
var subscribedToSrc = client.subscribedTo.indexOf(src) >= 0;
var subscribedToDst = client.subscribedTo.indexOf(dst) >= 0;
if (subscribedToSrc && subscribedToDst) {
client.events.push({type: 'obj_move', obj_id: object.id, x: object.x, y: object.y});
} else if (subscribedToDst) {
client.events.push({type: 'obj_ins', obj: object});
} else if (subscribedToSrc) {
client.events.push({type: 'obj_del', obj_id: object.id});
}
});
}
// TEST: create a creature that moves around by itself
nakai = createObject('#nakai', [942, 1220], {name: 'Nakai', sprite_id: 0x72});
setInterval(function () {
var angle = Math.floor(8*Math.random());
var dx = Math.round(Math.cos(0.125*angle*2*Math.PI));
var dy = Math.round(Math.sin(0.125*angle*2*Math.PI));
var oldLoc = {x: nakai.x, y: nakai.y};
var newLoc = {x: nakai.x + dx, y: nakai.y + dy};
if (!obstacleAtCoord(newLoc.x, newLoc.y)) {
moveObject(nakai, null, newLoc.x, newLoc.y);
if (Math.random() < 0.01) {
var obj = createObject(null, '#nakai', {sprite_id: 0x10b1, name: "treasure chest"});
moveObject(obj, null, oldLoc.x, oldLoc.y);
sendChatToAll({from: nakai.name, sprite_id: nakai.sprite_id,
systemtext: " dropped ", usertext: obj.name});
setTimeout(function () { destroyObject(obj); }, 10000);
}
}
}, 1500);
// Check if the map or any object would block movement to this location
function obstacleAtCoord(x, y) {
var chunkId = coordToChunkId(x, y);
function test(obj) {
return obj.loc === chunkId && obj.x === x && obj.y === y && obj.blocking;
}
var firstObstacle = _.detect(contents[chunkId] || [], test);
if (firstObstacle) { return firstObstacle; }
var waterAtDestination = (mapTileAt(x, y) === 0);
if (waterAtDestination) { return {name: "water"}; }
return null;
}
// Create an object and insert it into the appropriate maps. If id is
// null, create a fresh id. If location is a 2-element array, treat it as
// [grid x, grid y] and turn it into a loc + subloc.
function createObject(id, location, params) {
var x, y;
assert.equal(params.id, null, "Fresh object params should have no id");
assert.equal(params.loc, null, "Fresh object params should have no loc");
assert.ok(typeof location === 'string'
|| (location instanceof Array && location.length === 2),
"Fresh object location should be str or coord [x,y].");
if (id === null) {
id = '#obj:' + createObject.nextId;
createObject.nextId += 1;
}
if (typeof location !== 'string') {
x = location[0];
y = location[1];
location = coordToChunkId(x, y);
}
assert.equal(objects[id], null, "createObject() with id "+id+" already exists.");
params.id = id;
params.loc = null;
objects[id] = params;
moveObject(params, location, x, y);
return params;
}
createObject.nextId = 1; // static var
// Destroy an object and update the appropriate maps
function destroyObject(obj) {
assert.ok(obj.id, "destroyObject() with no id " + JSON.stringify(obj));
assert.ok(objects[obj.id], "destroyObject() with id "+obj.id+" does not exist.");
moveObject(obj, null);
delete objects[obj.id];
obj.id = null;
}
// Move a creature/player, and update the creatures mapping too. The
// original location or the target location can be null for creature
// birth/death. The x,y parameters are optional. If dst === null but
// x,y !== undefined then dst will be set to the chunk containing x,y.
function moveObject(object, dst, x, y) {
var i;
var src = object.loc;
assert.ok((typeof dst === 'string') || dst === null);
assert.ok((typeof src === 'string') || src === null);
assert.ok((typeof x === 'number') || x === undefined);
assert.ok((typeof y === 'number') || y === undefined);
if (dst === null && x !== undefined && y !== undefined) {
dst = coordToChunkId(x, y);
}
if (src !== dst) {
// Remove this object from the old block
if (src !== null) {
i = contents[src].indexOf(object);
assert.ok(i >= 0, "ERROR: object does not exist in contents map");
contents[src].splice(i, 1);
}
// Add this object to the new block
if (dst !== null) {
if (contents[dst] === undefined) contents[dst] = [];
contents[dst].push(object);
}
}
object.loc = dst;
object.x = x;
object.y = y;
sendMoveEvent(object, src);
}
function sendChatToAll(chatMessage) {
for (var clientId in clients) {
clients[clientId].messages.push(chatMessage);
}
}
// Class to handle a single game client
function Client(connectionId, log, sendMessage) {
this.object = {id: connectionId, name: '', sprite_id: null, loc: null};
this.messages = [];
this.subscribedTo = []; // list of block ids
this.events = [];
this.sendMessage = sendMessage;
if (clients[connectionId]) log('ERROR: client id already in clients map');
clients[connectionId] = this;
// Tell the client which of the object ids is itself
sendMessage({type: 'server_identify', id: connectionId});
// The client is now subscribed to this block, so send the full contents
function insertSubscription(blockId) {
(contents[blockId] || []).forEach(function (obj) {
// TODO: be consistent with event generator, with what fields sent to client
sendMessage({type: 'obj_ins', obj: obj});
});
}
// The client no longer subscribes to this block, so remove contents
function deleteSubscription(blockId) {
(contents[blockId] || []).forEach(function (obj) {
sendMessage({type: 'obj_del', obj_id: obj.id});
});
}
// Send all pending events from sim blocks
this.sendAllEvents = function () {
// Send an event per message:
this.events.forEach(function (event) { sendMessage(event); } );
this.events = [];
};
this.handleMessage = function (message, binaryMessage) {
if (message.type === 'client_identify') {
this.object.name = message.name;
this.object.sprite_id = message.sprite_id;
// Tell this player about everyone else
var myCreature = this.object;
var otherPlayers = _.pluck(_.select(_.pluck(_.values(clients), 'object'),
function (c) {
return c !== myCreature && c.name !== '';
}),
'name');
if (otherPlayers.length > 0) {
this.messages.push({systemtext: "Connected: ",
usertext: otherPlayers.join(", ")});
}
// Tell everyone else that this player connected
sendChatToAll({from: this.object.name, sprite_id: this.object.sprite_id,
systemtext: " has connected.", usertext: ""});
} else if (message.type === 'move') {
var obstacle = obstacleAtCoord(message.x, message.y);
if (obstacle) {
// We're not going to allow this move
this.messages.push({from: this.object.name, sprite_id: this.object.sprite_id,
systemtext: " blocked by ", usertext: obstacle.name});
} else {
moveObject(this.object, null, message.x, message.y);
}
// NOTE: we must flush all events before subscribing to
// new chunks, or we'll end up sending things twice. For
// example if a creature was created in a chunk and then
// we subscribe to the chunk, we don't want to first send
// the creature at subscription, and then send the
// creature again that was in the event log. Similar
// problems exist for unsubscriptions.
this.sendAllEvents();
// The list of chunks that the client should be subscribed to
var chunks = chunksSurroundingCoord(this.object.x, this.object.y);
// Compute the difference between the new list and the old list
var inserted = setDifference(chunks, this.subscribedTo);
var deleted = setDifference(this.subscribedTo, chunks);
// Set the new list on the server side
this.subscribedTo = chunks;
// The reply will tell the client where the player is now
var reply = {type: 'move_ok', loc: this.object.loc,
x: this.object.x, y: this.object.y};
// Set the new list on the client side
if (inserted.length > 0) reply.chunks_ins = inserted;
if (deleted.length > 0) reply.chunks_del = deleted;
sendMessage(reply);
// Send any additional data related to the change in subscriptions.
inserted.forEach(insertSubscription);
deleted.forEach(deleteSubscription);
// HACK: actions related to chairs
if ((this.object.x == 936 || this.object.x == 934) && this.object.y == 1220) {
// Send back a chair action
sendMessage({type: 's_actions', actions: [{obj: '#table1', verb: 'order', text: "Order a drink"}]});
}
} else if (message.type == 'c_jump') {
// No gameplay; just a visual we send to other clients
// NOTE: this is the only place we directly sendMessage with other clients
for (var clientId in clients) {
clients[clientId].sendMessage({type: 's_jump', id: this.object.id});
}
} else if (message.type == 'c_action') {
// TODO: not implemented yet
} else if (message.type === 'prefetch_map') {
// For now, just send a move_ok, which will trigger the fetching of map tiles
// TODO: this should share code with 'move' handler, sending ins/del events
sendMessage({
type: 'move_ok',
loc: coordToChunkId(clientDefaultLocation.x, clientDefaultLocation.y),
x: clientDefaultLocation.x,
y: clientDefaultLocation.y,
chunks: chunksSurroundingCoord(clientDefaultLocation.x, clientDefaultLocation.y)
});
} else if (message.type === 'map_tiles') {
var blockRange = chunkBounds(message.chunk_id);
var mapTiles = constructMapTiles(blockRange.left, blockRange.right, blockRange.top, blockRange.bottom);
sendMessage({
type: 'map_tiles',
chunk_id: message.chunk_id,
left: mapTiles.left,
right: mapTiles.right,
top: mapTiles.top,
bottom: mapTiles.bottom,
}, mapTiles.binaryPayload);
} else if (message.type === 'ping') {
// Send back all events that have occurred since the last ping
sendMessage({type: 'pong', timestamp: message.timestamp});
// Send back message events:
if (this.messages.length > 0) {
sendMessage({type: 'messages', messages: this.messages});
this.messages = [];
}
this.sendAllEvents();
} else if (message.type === 'message') {
// TODO: handle special commands
// TODO: handle empty messages (after spaces stripped)
sendChatToAll({from: this.object.name, sprite_id: this.object.sprite_id,
systemtext: " says: ", usertext: message.message});
} else {
log(' -- unknown message type');
}
};
this.handleDisconnect = function () {
if (this.object.sprite_id !== null) {
sendChatToAll({from: this.object.name, sprite_id: this.object.sprite_id,
systemtext: " has disconnected.", usertext: ""});
moveObject(this.object, null);
}
delete clients[connectionId];
};
}
net.createServer(function (socket) {
var context = repl.start("gameserver> ", socket).context;
context.clients = clients;
context.contents = contents;
context.objects = objects;
}).listen(5001);
// TEST: create a few items; HACK: use sprite_id >= 0x1000 as alternate spritesheet
createObject('#obj1', [940, 1215], {sprite_id: 0x10cf, name: "tree", blocking: true});
createObject('#obj2', [940, 1217], {sprite_id: 0x10ce, name: "tree", blocking: true});
createObject('#chair1', [936, 1220], {sprite_id: 0x10bc, name: "chair"});
createObject('#table1', [935, 1220], {sprite_id: 0x10b9, name: "table", blocking: true});
createObject('#chair2', [934, 1220], {sprite_id: 0x10bb, name: "chair"});
(function () {
var x, y;
for (x = 932; x <= 939; x++) {
for (y = 1218; y <= 1223; y++) {
if ((x == 932 && y == 1222) || (x == 939 && y == 1219)) {
// Doorway
} else if (x == 932 || x == 939 || y == 1218 || y == 1223) {
// Wall
createObject(null, [x, y], {sprite_id: 0x10c5, name: "wall", blocking: true});
} else {
// Floor
}
}
}
})();
server.go(Client, {'/debug': 'gameclient-dbg.swf', '/world': 'gameclient.swf'});