-
Notifications
You must be signed in to change notification settings - Fork 12
/
world.js
85 lines (80 loc) · 2.57 KB
/
world.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
var _ = require('underscore');
var util = require("util");
var events = require("events");
module.exports.WorldModule = WorldModule;
function WorldModule(game) {
events.EventEmitter.call(this);
var _this = this;
this._listenersAdded = [];
this._spawns = {};
// Make all regular globals available within the modules (is this a
// good idea?)
_.extend(this, global);
// Inject underscore
this._ = _;
this.game = game;
this.require = require;
// Make available world creation commands
this.command = _.bind(game.createCommand, game);
// Create a command that expects an item name following it. Will
// automatically check that the item is present.
this.itemCommand = function (command, item, description, fn) {
game.createCommand(command + ' ' + item, description, fn);
};
this.room = _.bind(game.createRoom, game);
this.character = function (name, properties) {
var player = game.createPlayer(name);
properties.npc = true;
_.extend(player, properties);
return player;
};
this.setTimeout = function (fn, time) {
setTimeout(function () {
try {
fn();
} catch(e) {
game.broadcast('Error running timeout');
game.broadcast(e);
game.broadcast(e.stack);
console.trace();
}
}, time);
};
this.handler = function (event, fn) {
var wrapped = function () {
try {
fn.apply(_this, arguments);
} catch (e) {
game.broadcast('Error running handler for event: ' + event);
game.broadcast(e);
game.broadcast(e.stack);
console.log('Error running handler for event: ' + event);
console.trace();
_this.removeListener(event, wrapped);
}
};
_this.on(event, wrapped);
};
// Create an item in the given room every spawnFrequency seconds if
// one of the same name does not already exist.
this.item = function (room, name, spawnFrequency, item) {
item.name = name;
_this._spawns[room + ':' + name] = {room: room, lastSpawn: 0, spawnFrequency: spawnFrequency, item: item};
};
// Set up a tick handler to check for spawns
this.handler('tick', function () {
_.each(_this._spawns, function (spawn) {
var t = (new Date()).getTime()/1000,
room = game.rooms[spawn.room];
if (t-spawn.lastSpawn > spawn.spawnFrequency) {
spawn.lastSpawn = t;
if (!room.getItem(spawn.item.name)) {
var item = _.clone(spawn.item);
room.items.push(item);
game.emit('spawn', room, item);
}
}
});
});
}
util.inherits(WorldModule, events.EventEmitter);