world.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. var glob = require('glob'),
  2. fs = require('fs'),
  3. crypto = require('crypto');
  4. session = {
  5. "updateRate": 3000,
  6. "players": {},
  7. "rooms": {},
  8. "mobiles": {},
  9. "mobileIds": 1,
  10. "items": {},
  11. "itemIds": 1
  12. };
  13. builder = require('./builder');
  14. admin = require('./admin');
  15. commands = require('./commands');
  16. rooms = require(config.worldDataPath + '/rooms');
  17. items = require(config.worldDataPath + '/items');
  18. mobiles = require(config.worldDataPath + '/mobiles');
  19. class World {
  20. constructor() {
  21. this.time = 0;
  22. this.blacklist = ["constructor"];
  23. this.blacklistPrefix = "mud_";
  24. this.timerId = -1;
  25. }
  26. mud_load() {
  27. if(this.timerId != -1 ) {
  28. clearInterval(this.timerId);
  29. }
  30. session.updateRate = 3000;
  31. session.rooms = {};
  32. session.items = {};
  33. session.mobiles = {};
  34. session.players = {};
  35. session.mobileIds = 1;
  36. session.itemIds = 1;
  37. //populate rooms
  38. for(var roomName in rooms) {
  39. var room = builder.mud_spawnRoom(roomName);
  40. if(typeof room.mud_init == 'function') {
  41. room.mud_init();
  42. }
  43. }
  44. //populate mobiles
  45. for(var mobileName in mobiles) {
  46. if(mobileName == "PlayerMobile") {
  47. continue;
  48. }
  49. var mobile = builder.mud_spawnMobile(mobileName);
  50. if(typeof mobile.mud_init == 'function') {
  51. mobile.mud_init(mobileName);
  52. } else {
  53. world.mud_destroyMobile(mobile.id);
  54. }
  55. }
  56. //populate items
  57. for(var itemName in items) {
  58. var item = builder.mud_spawnItem(itemName);
  59. if(typeof item.mud_init == 'function') {
  60. item.mud_init();
  61. } else {
  62. world.mud_destroyItem(item.id);
  63. }
  64. }
  65. this.timerId = setInterval(function() {
  66. world.mud_tick(Date.now());
  67. }, session.updateRate);
  68. }
  69. mud_handleInput(roomName, mobileId, input) {
  70. var room = this.mud_getRoom(roomName);
  71. var mobile = this.mud_getMobile(mobileId);
  72. var command = input.shift();
  73. if(command.indexOf(this.blacklistPrefix) != -1) {
  74. libs.Output.toMobile(mobile.id, "I didn't understand that.");
  75. return true;
  76. }
  77. if(this.blacklist.indexOf(command) != -1) {
  78. libs.Output.toMobile(mobile.id, "I didn't understand that.");
  79. return true;
  80. }
  81. if (world.mud_mobileHasRole(mobile.id, "admin") && typeof admin[command] == 'function') {
  82. try {
  83. if(admin[command](room, mobile, input)) {
  84. return true;
  85. }
  86. } catch (error) {
  87. libs.Output.toServerError("Exception in admin tools - ", error);
  88. libs.Output.toMobile(mobile.id, "The administration tools are misbehaving.");
  89. if(world.mud_mobileHasRole(mobile.id, "admin")) {
  90. libs.Output.toMobile(mobile.id, error.code + " " + error.stack + "\n");
  91. }
  92. }
  93. }
  94. if (world.mud_mobileHasRole(mobile.id, "builder") && typeof builder[command] == 'function') {
  95. try {
  96. if(builder[command](room, mobile, input)) {
  97. return true;
  98. }
  99. } catch (error) {
  100. libs.Output.toServerError("Exception in builder tools - ", error);
  101. libs.Output.toMobile(mobile.id, "The build tools are misbehaving.");
  102. if(world.mud_mobileHasRole(mobile.id, "admin")) {
  103. libs.Output.toMobile(mobile.id, error.code + " " + error.stack + "\n");
  104. }
  105. }
  106. }
  107. for (var itemIndex in mobile.items) {
  108. var otherItem = this.mud_getItem(mobile.items[itemIndex]);
  109. if(typeof otherItem[command] == 'function') {
  110. try {
  111. if(otherItem[command](room, mobile, input)) {
  112. return true;
  113. }
  114. } catch (error) {
  115. libs.Output.toServerError("Exception in mobile item: " + mobile.constructor.name + ":" +mobile.id+","+otherItem.constructor.name+":"+otherItem.id+" - ", error);
  116. libs.Output.toMobile(mobile.id, otherItem.name + " you are holding {error}glitches{/error} for a second.");
  117. if(world.mud_mobileHasRole(mobile.id, "builder")) {
  118. libs.Output.toMobile(mobile.id, error.code + " " + error.stack + "\n");
  119. }
  120. }
  121. }
  122. }
  123. if(typeof mobile[command] == 'function') {
  124. try {
  125. if(mobile[command](room, mobile, input)) {
  126. return true;
  127. }
  128. } catch (error) {
  129. libs.Output.toServerError("Exception in mobile: " + mobile.constructor.name + ":" +mobile.id+" - ", error);
  130. libs.Output.toMobile(mobile.id, "You feel funny and {error}not quite right{/error}.");
  131. if(world.mud_mobileHasRole(mobile.id, "builder")) {
  132. libs.Output.toMobile(mobile.id, error.code + " " + error.stack + "\n");
  133. }
  134. }
  135. }
  136. for (var itemIndex in room.items) {
  137. var otherItem = this.mud_getItem(room.items[itemIndex]);
  138. if(typeof otherItem[command] == 'function') {
  139. try {
  140. if(otherItem[command](room, mobile, input)) {
  141. return true;
  142. }
  143. } catch (error) {
  144. libs.Output.toServerError("Exception in room item: " + room.constructor.name + ","+otherItem.constructor.name+":"+otherItem.id+" - ", error);
  145. libs.Output.toMobile(mobile.id, otherItem.name + " here {error}glitches{/error} for a second.");
  146. if(world.mud_mobileHasRole(mobile.id, "builder")) {
  147. libs.Output.toMobile(mobile.id, error.code + " " + error.stack + "\n");
  148. }
  149. }
  150. }
  151. }
  152. for (var mobileIndex in room.mobiles) {
  153. var otherMobile = this.mud_getMobile(room.mobiles[mobileIndex]);
  154. if(typeof otherMobile[command] == 'function') {
  155. try {
  156. if(otherMobile[command](room, mobile, input)) {
  157. return true;
  158. }
  159. } catch (error) {
  160. libs.Output.toServerError("Exception in room mobile: " + room.constructor.name + "," + otherMobile.constructor.name +":"+otherMobile.id+" - ", error);
  161. libs.Output.toMobile(mobile.id, otherMobile.name + " {error}staggers{/error} in and out of reality.");
  162. if(world.mud_mobileHasRole(mobile.id, "builder")) {
  163. libs.Output.toMobile(mobile.id, error.code + " " + error.stack + "\n");
  164. }
  165. }
  166. }
  167. }
  168. if(typeof room[command] == 'function') {
  169. try {
  170. if(room[command](room, mobile, input)) {
  171. return true;
  172. }
  173. } catch (error) {
  174. libs.Output.toServerError("Exception in room: " + room.id + " - ", error);
  175. libs.Output.toMobile(mobile.id, "You see strange {error}glitch errors{/error} in the surrounding area.");
  176. if(world.mud_mobileHasRole(mobile.id, "builder")) {
  177. libs.Output.toMobile(mobile.id, error.code + " " + error.stack + "\n");
  178. }
  179. }
  180. }
  181. for(var commanderClass in commands) {
  182. var commander = new commands[commanderClass]();
  183. if (typeof commander[command] == 'function') {
  184. try {
  185. if(commander[command](room, mobile, input)) {
  186. return true;
  187. }
  188. } catch (error) {
  189. libs.Output.toServerError("Exception in command: " + commanderClass + " - ", error);
  190. libs.Output.toMobile(mobile.id, commander.mud_getErrorMessage());
  191. if(world.mud_mobileHasRole(mobile.id, "builder")) {
  192. libs.Output.toMobile(mobile.id, error.code + " " + error.stack + "\n");
  193. }
  194. }
  195. }
  196. }
  197. libs.Output.toMobile(mobile.id, "I didn't understand that.");
  198. return true;
  199. }
  200. mud_tick(time) {
  201. try {
  202. for(var roomName in session.rooms) {
  203. var room = this.mud_getRoom(roomName);
  204. if(typeof room.mud_tick == 'function') {
  205. room.mud_tick(time);
  206. }
  207. }
  208. } catch (error) {
  209. libs.Output.worldToMobiles("The flow of time seems to {error}stutter{/error} a second.");
  210. libs.Output.toBuildersError("Room tick error", error);
  211. libs.Output.toServerError("Room tick error", error);
  212. }
  213. try {
  214. for(var mobileId in session.mobiles) {
  215. var mobile = this.mud_getMobile(mobileId);
  216. if(mobile == null) {
  217. console.log("null mobile", mobile);
  218. continue;
  219. }
  220. if(typeof mobile.mud_tick == 'function') {
  221. mobile.mud_tick(time);
  222. }
  223. }
  224. } catch (error) {
  225. libs.Output.worldToMobiles("Lifeforms in the universe {error}skip{/error} a unified heartbeat.");
  226. libs.Output.toBuildersError("Mobile tick error", error);
  227. libs.Output.toServerError("Mobile tick error", error);
  228. }
  229. try {
  230. for(var itemId in session.items) {
  231. var item = this.mud_getItem(itemId);
  232. if(item == null) {
  233. console.log("null item", item);
  234. continue;
  235. }
  236. if(typeof item.mud_tick == 'function') {
  237. item.mud_tick(time);
  238. }
  239. }
  240. } catch (error) {
  241. libs.Output.worldToMobiles("Items everywhere {error}flicker{/error} out of reality for a second.");
  242. libs.Output.toBuildersError("Item tick error", error);
  243. libs.Output.toServerError("Item tick error", error);
  244. }
  245. this.time++;
  246. this.time %= 640;
  247. switch(this.time) {
  248. case 0:
  249. //text must include dawn
  250. libs.Output.worldToMobiles("{global}Dawn breaks as the sun begins to rise.{/global}");
  251. this.mud_allPlayersSave();
  252. break;
  253. case 160:
  254. //text must include midday
  255. libs.Output.worldToMobiles("{global}The sky is a clear, crisp cerulean to hold the bright midday sun.{/global}");
  256. this.mud_allPlayersSave();
  257. break;
  258. case 320:
  259. //text must include twilight
  260. libs.Output.worldToMobiles("{global}Twilight creeps in slowly as the sun begins to set.{/global}");
  261. this.mud_allPlayersSave();
  262. break;
  263. case 480:
  264. //text must include midnight
  265. libs.Output.worldToMobiles("{global}Stars twinkle in the midnight sky.{/global}");
  266. this.mud_allPlayersSave();
  267. break;
  268. }
  269. }
  270. mud_moveMobile(mobileId, sourceRoom, destinationRoom, outDirection, inDirection) {
  271. if(session.rooms[destinationRoom] == null) {
  272. libs.Output.toMobile(mobileId, destinationRoom + " doesn't seem to exist yet.");
  273. return;
  274. }
  275. this.mud_moveMobileFromRoom(sourceRoom, mobileId, outDirection);
  276. this.mud_moveMobileToRoom(destinationRoom, mobileId, inDirection);
  277. }
  278. mud_moveMobileToRoom(roomName, mobileId, direction) {
  279. var mobileObj = this.mud_getMobile(mobileId);
  280. if(typeof mobileObj.mud_enterRoom == "function") {
  281. libs.Output.toRoom(roomName, mobileObj.mud_enterRoom(direction), mobileObj);
  282. } else {
  283. if(direction != null) {
  284. libs.Output.toRoom(roomName, mobileObj.mud_getName() + " " + direction + ".");
  285. } else {
  286. libs.Output.toRoom(roomName, mobileObj.mud_getName() + " arrives.", mobileObj);
  287. }
  288. }
  289. this.mud_addMobileToRoom(roomName, mobileId);
  290. this.mud_handleInput(roomName, mobileId, ["look"]);
  291. }
  292. mud_moveMobileFromRoom(roomName, mobileId, direction) {
  293. var mobileObj = this.mud_getMobile(mobileId);
  294. this.mud_removeMobileFromRoom(roomName, mobileId);
  295. if(typeof mobileObj.mud_leaveRoom == "function") {
  296. libs.Output.toRoom(roomName, mobileObj.mud_leaveRoom(direction), mobileObj);
  297. } else {
  298. if(direction != null) {
  299. libs.Output.toRoom(roomName, mobileObj.mud_getName() + " " + direction + ".");
  300. } else {
  301. libs.Output.toRoom(roomName, mobileObj.mud_getName() + " leaves.", mobileObj);
  302. }
  303. }
  304. }
  305. mud_getItem(itemId) {
  306. var item = session.items[itemId];
  307. if(item == null) {
  308. throw new Error("Item '"+itemId+"' not defined.");
  309. }
  310. return item;
  311. }
  312. mud_getMobile(mobileId) {
  313. var mobile = session.mobiles[mobileId];
  314. if(mobile == null) {
  315. throw new Error("Mobile '"+mobileId+"' not defined.");
  316. }
  317. return mobile;
  318. }
  319. mud_getRoom(roomName) {
  320. var room = session.rooms[roomName];
  321. if(room == null) {
  322. throw new Error("Room '"+roomName+"' not defined.");
  323. }
  324. return room;
  325. }
  326. mud_addMobileToRoom(roomName, mobileId) {
  327. var mobileObj = this.mud_getMobile(mobileId);
  328. var roomObj = this.mud_getRoom(roomName);
  329. mobileObj.roomId = roomName;
  330. roomObj.mobiles.push(mobileId);
  331. }
  332. mud_removeMobileFromRoom(roomName, mobileId) {
  333. var room = this.mud_getRoom(roomName);
  334. room.mobiles.splice(room.mobiles.indexOf(mobileId), 1);
  335. }
  336. mud_addItemToRoom(roomName, itemId) {
  337. var room = this.mud_getRoom(roomName);
  338. if(room.items.indexOf(itemId) == -1) {
  339. room.items.push(itemId);
  340. var item = world.mud_getItem(itemId);
  341. item.inRoom = roomName;
  342. }
  343. }
  344. mud_addItemToMobile(mobileId, itemId) {
  345. var mobile = this.mud_getMobile(mobileId);
  346. if(mobile.items.indexOf(itemId) == -1) {
  347. mobile.items.push(itemId);
  348. var item = world.mud_getItem(itemId);
  349. item.heldBy = mobileId;
  350. }
  351. }
  352. mud_removeItemFromMobile(mobileId, itemId) {
  353. var mobile = session.mobiles[mobileId];
  354. for(var slotIndex in mobile.itemSlots) {
  355. var slot = mobile.itemSlots[slotIndex];
  356. if(slot == itemId) {
  357. mobile.itemSlots[slotIndex] = null;
  358. var item = world.mud_getItem(itemId);
  359. item.isWorn = -1;
  360. item.heldBy = -1;
  361. }
  362. }
  363. if(mobile.items.indexOf(itemId) != -1) {
  364. mobile.items.splice(mobile.items.indexOf(itemId), 1);
  365. }
  366. }
  367. mud_removeItemFromRoom(roomId, itemId) {
  368. var room = session.rooms[roomId];
  369. room.items.splice(room.items.indexOf(itemId), 1);
  370. var item = world.mud_getItem(itemId);
  371. item.inRoom = -1;
  372. }
  373. mud_destroyItem(itemId) {
  374. delete session.items[itemId];
  375. }
  376. mud_destroyMobile(mobileId) {
  377. delete session.mobiles[mobileId];
  378. }
  379. mud_mobileHasRole(mobileId, role) {
  380. var mobile = session.mobiles[mobileId];
  381. if(mobile.roles != null) {
  382. return mobile.roles.indexOf(role) != -1;
  383. }
  384. return false;
  385. }
  386. mud_generateHash(input) {
  387. return crypto.createHash('sha256').update(input).digest("base64");
  388. }
  389. mud_getUserData(username) {
  390. var playerFilename = config.playerDataPath+ "/"+username.toLowerCase().trim()+".json";
  391. var files = glob.sync(playerFilename, {} );
  392. if(files.length == 1) {
  393. var fileData = fs.readFileSync(files[0], "utf8");
  394. return JSON.parse(fileData);
  395. }
  396. return null;
  397. }
  398. mud_isValidLogin(userData, password) {
  399. var hash = crypto.createHash('sha256').update(userData.username.toLowerCase().trim() + password).digest("base64");
  400. if(userData.password == hash) {
  401. return true;
  402. }
  403. return false;
  404. }
  405. mud_playerLoad(login, userData) {
  406. for(var activePlayerId in session.players) {
  407. var activePlayer = session.players[activePlayerId];
  408. if(activePlayer.password == userData.password) {
  409. libs.Output.toMobile(activePlayer.id, "You are being booted by another login.");
  410. var oldLogin = activePlayer.login.reconnect(login);
  411. login.player = activePlayer;
  412. login.setConnectionTimeout(activePlayer.connectionTimeout);
  413. return;
  414. }
  415. }
  416. var player = builder.mud_spawnMobile("PlayerMobile");
  417. player.login = login;
  418. player.connectionTimeout = userData.connectionTimeout || 0;
  419. player.login.setConnectionTimeout(player.connectionTimeout);
  420. player.name = userData.username;
  421. player.description = userData.description || "A player";
  422. player.password = userData.password;
  423. player.roomId = userData.roomName || "ZebedeeTemple";
  424. player.hintColor = userData.hintColor || "FgMagenta";
  425. player.terminalWidthPreference = userData.terminalWidthPreference || 78;
  426. player.connectionTimeout = userData.connectionTimeout || 0;
  427. player.keywords.push(player.name.toLowerCase());
  428. player.roles = userData.roles || [];
  429. player.title = userData.title || "the Player";
  430. player.pubKeys = userData.pubKeys || [];
  431. player.account = parseInt(userData.account) || 0;
  432. for(var itemIdIndex in userData.items) {
  433. var loadedItemData = userData.items[itemIdIndex];
  434. var loadedItem = builder.mud_spawnItem(loadedItemData.classname);
  435. if(typeof loadedItem.mud_loadItem == "function") {
  436. loadedItem.mud_loadItem(loadedItemData);
  437. }
  438. this.mud_addItemToMobile(player.id, loadedItem.id);
  439. }
  440. player.aliases = userData.aliases;
  441. for(var aliasKey in userData.aliases) {
  442. player.mud_setAlias(aliasKey, userData.aliases[aliasKey]);
  443. }
  444. login.player = player;
  445. world.mud_attachPlayer(player);
  446. }
  447. mud_attachPlayer(player) {
  448. this.mud_addMobileToRoom(player.roomId, player.id);
  449. session.players[player.id] = player;
  450. var joinMessage = player.name + " joined the server.";
  451. libs.Output.toServer(joinMessage);
  452. libs.Output.worldToMobiles(joinMessage, player);
  453. this.mud_handleInput(player.roomId, player.id, ["look"]);
  454. }
  455. mud_playerSave(player) {
  456. var playerFilename = config.playerDataPath+ "/"+player.name.toLowerCase().trim()+".json";
  457. var userData = {};
  458. userData.username = player.name;
  459. userData.password = player.password,
  460. userData.roomName = session.rooms[player.roomId].constructor.name;
  461. userData.hintColor = player.hintColor;
  462. userData.description = player.description;
  463. userData.terminalWidthPreference = player.terminalWidthPreference;
  464. userData.connectionTimeout = player.connectionTimeout;
  465. userData.roles = player.roles;
  466. userData.title = player.title;
  467. userData.pubKeys = player.pubKeys;
  468. userData.account = player.account;
  469. var items = [];
  470. for(var itemIdIndex in player.items) {
  471. var savedItem = {};
  472. if(typeof session.items[player.items[itemIdIndex]].mud_saveItem == "function") {
  473. savedItem = session.items[player.items[itemIdIndex]].mud_saveItem();
  474. }
  475. savedItem.classname = session.items[player.items[itemIdIndex]].constructor.name;
  476. items.push(savedItem);
  477. }
  478. userData.items = items;
  479. userData.aliases = player.aliases;
  480. fs.writeFile(playerFilename, JSON.stringify(userData, null, "\t"), (err) => {
  481. if (err) {
  482. throw err;
  483. }
  484. libs.Output.toServer("saved player data " + playerFilename);
  485. });
  486. }
  487. mud_allPlayersSave() {
  488. for(var index in session.players) {
  489. var player = session.players[index];
  490. this.mud_playerSave(player);
  491. }
  492. }
  493. mud_playerQuit(player) {
  494. this.mud_playerSave(player);
  495. var playerId = player.id;
  496. for(var itemIdIndex in player.items) {
  497. var item = session.items[player.items[itemIdIndex]];
  498. this.mud_removeItemFromMobile(player.id, item.id);
  499. this.mud_destroyItem(item.id);
  500. }
  501. this.mud_removeMobileFromRoom(player.roomId, player.id);
  502. delete session.players[player.id];
  503. this.mud_destroyMobile(playerId);
  504. libs.Output.toServer(player.mud_getName() + " left the server.");
  505. libs.Output.worldToMobiles(player.mud_getName() + " left the server.", player);
  506. return true;
  507. }
  508. mud_rollRandom(probabilitySet) {
  509. var rollValue = parseInt(Math.random() * 100) + 1;
  510. var probabilityTotal = 0;
  511. var sortedSet = probabilitySet.sort(function(a, b) {
  512. return (a.probability < b.probability) ? 1 : ((a.probability > b.probability) ? -1 : 0);
  513. });
  514. for(var index in sortedSet) {
  515. var row = sortedSet[index];
  516. probabilityTotal += row.probability;
  517. if(rollValue <= probabilityTotal) {
  518. return row.value;
  519. }
  520. }
  521. }
  522. mud_replaceRoomItem(roomId, itemName) {
  523. var isFound = false;
  524. var room = this.mud_getRoom(roomId);
  525. for(var i in room.items) {
  526. var itemId = room.items[i];
  527. if(this.mud_getItem(itemId).constructor.name == itemName) {
  528. isFound = true;
  529. }
  530. }
  531. if(!isFound) {
  532. world.mud_addItemToRoom(roomId, builder.mud_spawnItem(itemName).id);
  533. }
  534. }
  535. }
  536. module.exports = new World();