From 6e747b6fc090f151ec4cf38cb2fef1d5661c452a Mon Sep 17 00:00:00 2001 From: Romain Beaumont Date: Fri, 28 Aug 2015 01:10:35 +0200 Subject: [PATCH] add player.handleCommand to the api, improve command handling --- doc/api.md | 5 +++++ lib/playerPlugins/chat.js | 29 ++++++----------------------- lib/playerPlugins/commands.js | 19 +++++++++++++++++++ 3 files changed, 30 insertions(+), 23 deletions(-) create mode 100644 lib/playerPlugins/commands.js diff --git a/doc/api.md b/doc/api.md index 361e3b0..f748ee2 100644 --- a/doc/api.md +++ b/doc/api.md @@ -61,6 +61,7 @@ - [player.sendInitialPosition()](#playersendinitialposition) - [player.spawn()](#playerspawn) - [player.setGameMode(gameMode)](#playersetgamemodegamemode) + - [player.handleCommand(command)](#playerhandlecommandcommand) - [Low level properties](#low-level-properties) - [player._client](#player_client) - [Low level methods](#low-level-methods) @@ -283,6 +284,10 @@ tell everybody else that the player spawned set player gameMode to `gameMode` +#### player.handleCommand(command) + +handle `command` + ### Low level properties #### player._client diff --git a/lib/playerPlugins/chat.js b/lib/playerPlugins/chat.js index 8b08a26..df89d7d 100644 --- a/lib/playerPlugins/chat.js +++ b/lib/playerPlugins/chat.js @@ -1,35 +1,18 @@ module.exports=inject; -function inject(serv, player, options) +function inject(serv, player) { player._client.on('chat', function (packet) { - if(!handleCommand(packet.message)) { + if(packet.message[0]=="/") { + var command = packet.message.slice(1); + player.handleCommand(command); + } + else { serv.broadcast('<' + player.username + '>' + ' ' + packet.message); player.emit("chat",packet.message); } }); - function handleCommand(message) - { - var command; - if(message[0]=="/") - command=message.slice(1); - else return false; - - if(options.commands[command]) { - player.chat("" + options.commands[command]); - return true; - } - var results; - if(results=command.match(/^gamemode ([0-3])$/)) { - var gameMode=parseInt(results[1]); - player.setGameMode(gameMode); - return true; - } - player.chat("Invalid command."); - return true; - } - function chat(message) { player._client.write('chat', { message: JSON.stringify(message), position: 0 }); } diff --git a/lib/playerPlugins/commands.js b/lib/playerPlugins/commands.js new file mode 100644 index 0000000..475cd13 --- /dev/null +++ b/lib/playerPlugins/commands.js @@ -0,0 +1,19 @@ +module.exports=inject; + +function inject(serv, player, options) +{ + function handleCommand(command) + { + var results; + if(options.commands[command]) + player.chat("" + options.commands[command]); + else if(results=command.match(/^gamemode ([0-3])$/)) { + var gameMode=parseInt(results[1]); + player.setGameMode(gameMode); + } + else + player.chat("Invalid command."); + } + + player.handleCommand=handleCommand; +} \ No newline at end of file