Changed formatting to use idiomatic style. (like glasses-mode in emacs)

This commit is contained in:
walterhiggins 2014-01-29 19:49:15 +00:00
parent 7a7767c83c
commit 7457cd58b8
54 changed files with 4161 additions and 3849 deletions

View file

@ -829,11 +829,14 @@ The following example illustrates how to use http.request to make a request to a
... The following example illustrates a more complex use-case POSTing parameters to a CGI process on a server... ... The following example illustrates a more complex use-case POSTing parameters to a CGI process on a server...
var http = require('./http/request'); var http = require('./http/request');
http.request({ url: "http://pixenate.com/pixenate/pxn8.pl", http.request(
method: "POST", {
params: {script: "[]"} url: 'http://pixenate.com/pixenate/pxn8.pl',
}, function( responseCode, responseBody){ method: 'POST',
var jsObj = eval("(" + responseBody + ")"); params: {script: '[]'}
},
function( responseCode, responseBody ) {
var jsObj = eval('(' + responseBody + ')');
}); });
## sc-mqtt module ## sc-mqtt module
@ -1173,7 +1176,7 @@ package for scheduling processing of arrays.
- object : Additional (optional) information passed into the foreach method. - object : Additional (optional) information passed into the foreach method.
- array : The entire array. - array : The entire array.
* object (optional) : An object which may be used by the callback. * context (optional) : An object which may be used by the callback.
* delay (optional, numeric) : If a delay is specified (in ticks - 20 * delay (optional, numeric) : If a delay is specified (in ticks - 20
ticks = 1 second), then the processing will be scheduled so that ticks = 1 second), then the processing will be scheduled so that
each item will be processed in turn with a delay between the completion of each each item will be processed in turn with a delay between the completion of each
@ -2293,10 +2296,11 @@ Source Code ...
command( 'hello-byname', function( parameters, sender ) { command( 'hello-byname', function( parameters, sender ) {
var playerName = parameters[0]; var playerName = parameters[0];
var recipient = utils.player( playerName ); var recipient = utils.player( playerName );
if (recipient) if ( recipient ) {
greetings.hello( recipient ); greetings.hello( recipient );
else } else {
sender.sendMessage( 'Player ' + playerName + ' not found.' ); sender.sendMessage( 'Player ' + playerName + ' not found.' );
}
}); });
## Example Plugin #7 - Listening for events, Greet players when they join the game. ## Example Plugin #7 - Listening for events, Greet players when they join the game.

View file

@ -2,45 +2,53 @@
/* /*
command management - allow for non-ops to execute approved javascript code. command management - allow for non-ops to execute approved javascript code.
*/ */
var _commands = {}; var _commands = {},
var _cmdInterceptors = []; _cmdInterceptors = [];
/* /*
execute a JSP command. execute a JSP command.
*/ */
var executeCmd = function( args, player ) { var executeCmd = function( args, player ) {
if (args.length === 0) var name,
cmd,
intercepted,
result = null;
if ( args.length === 0 ) {
throw new Error('Usage: jsp command-name command-parameters'); throw new Error('Usage: jsp command-name command-parameters');
var name = args[0]; }
var cmd = _commands[name]; name = args[0];
cmd = _commands[name];
if ( typeof cmd === 'undefined' ) { if ( typeof cmd === 'undefined' ) {
// it's not a global command - pass it on to interceptors // it's not a global command - pass it on to interceptors
var intercepted = false; intercepted = false;
for ( var i = 0; i < _cmdInterceptors.length; i++ ) { for ( var i = 0; i < _cmdInterceptors.length; i++ ) {
if ( _cmdInterceptors[i]( args, player ) ) if ( _cmdInterceptors[i]( args, player ) )
intercepted = true; intercepted = true;
} }
if (!intercepted) if ( !intercepted ) {
console.warn( 'Command %s is not recognised', name ); console.warn( 'Command %s is not recognised', name );
}
}else{ }else{
var result = null;
try { try {
result = cmd.callback( args.slice(1), player ); result = cmd.callback( args.slice(1), player );
} catch ( e ) { } catch ( e ) {
console.error( 'Error while trying to execute command: ' + JSON.stringify( args ) ); console.error( 'Error while trying to execute command: ' + JSON.stringify( args ) );
throw e; throw e;
} }
return result;
} }
return result;
}; };
/* /*
define a new JSP command. define a new JSP command.
*/ */
var defineCmd = function( name, func, options, intercepts ) { var defineCmd = function( name, func, options, intercepts ) {
if (typeof options == 'undefined') if ( typeof options == 'undefined' ) {
options = []; options = [];
}
_commands[name] = { callback: func, options: options }; _commands[name] = { callback: func, options: options };
if (intercepts) if ( intercepts ) {
_cmdInterceptors.push(func); _cmdInterceptors.push(func);
}
return func; return func;
}; };
exports.command = defineCmd; exports.command = defineCmd;

View file

@ -35,20 +35,22 @@ ScriptCraft uses Java's [String.format()][strfmt] so any string substitution ide
[webcons]: https://developer.mozilla.org/en-US/docs/Web/API/console [webcons]: https://developer.mozilla.org/en-US/docs/Web/API/console
***/ ***/
var logger = __plugin.logger; var logger = __plugin.logger,
logMethodName = 'log(java.util.logging.Level,java.lang.String)';
var argsToArray = function( args ) { var argsToArray = function( args ) {
var result = []; var result = [];
for (var i =0;i < args.length; i++) for ( var i =0; i < args.length; i++ ) {
result.push(args[i]); result.push(args[i]);
}
return result; return result;
} }
var log = function( level, restOfArgs ) { var log = function( level, restOfArgs ) {
var args = argsToArray( restOfArgs ); var args = argsToArray( restOfArgs );
if ( args.length > 1 ) { if ( args.length > 1 ) {
var msg = java.lang.String.format( args[0], args.slice(1) ); var msg = java.lang.String.format( args[0], args.slice(1) );
logger['log(java.util.logging.Level,java.lang.String)'](level,msg); logger[logMethodName]( level, msg );
} else { } else {
logger['log(java.util.logging.Level,java.lang.String)'](level, args[0]); logger[logMethodName]( level, args[0] );
} }
}; };
@ -60,10 +62,12 @@ exports.log = function(){
exports.info = function( ) { exports.info = function( ) {
log( Level.INFO, arguments ); log( Level.INFO, arguments );
} };
exports.warn = function( ) { exports.warn = function( ) {
log( Level.WARNING, arguments ); log( Level.WARNING, arguments );
}; };
exports.error = function( ) { exports.error = function( ) {
log( Level.SEVERE, arguments ); log( Level.SEVERE, arguments );
}; };

View file

@ -75,9 +75,9 @@ To listen for events using a full class name as the `eventName` parameter...
***/ ***/
var bkEvent = org.bukkit.event; var bkEvent = org.bukkit.event,
var bkEvtExecutor = org.bukkit.plugin.EventExecutor; bkEvtExecutor = org.bukkit.plugin.EventExecutor,
var bkRegListener = org.bukkit.plugin.RegisteredListener; bkRegListener = org.bukkit.plugin.RegisteredListener;
exports.on = function( exports.on = function(
/* String or java Class */ /* String or java Class */
@ -86,13 +86,16 @@ exports.on = function(
handler, handler,
/* (optional) String (HIGH, HIGHEST, LOW, LOWEST, NORMAL, MONITOR), */ /* (optional) String (HIGH, HIGHEST, LOW, LOWEST, NORMAL, MONITOR), */
priority ) { priority ) {
var handlerList,
listener = {},
eventExecutor;
if (typeof priority == "undefined"){ if ( typeof priority == 'undefined' ) {
priority = bkEvent.EventPriority.HIGHEST; priority = bkEvent.EventPriority.HIGHEST;
} else { } else {
priority = bkEvent.EventPriority[priority]; priority = bkEvent.EventPriority[priority];
} }
if (typeof eventType == "string"){ if ( typeof eventType == 'string' ) {
/* /*
Nashorn doesn't support bracket notation for accessing packages. Nashorn doesn't support bracket notation for accessing packages.
E.g. java.net will work but java['net'] won't. E.g. java.net will work but java['net'] won't.
@ -106,9 +109,8 @@ exports.on = function(
eventType = eval( 'org.bukkit.event.' + eventType ); eventType = eval( 'org.bukkit.event.' + eventType );
} }
} }
var handlerList = eventType.getHandlerList(); handlerList = eventType.getHandlerList( );
var listener = {}; eventExecutor = new bkEvtExecutor( ) {
var eventExecutor = new bkEvtExecutor(){
execute: function( l, e ) { execute: function( l, e ) {
handler( listener.reg, e ); handler( listener.reg, e );
} }

View file

@ -17,6 +17,7 @@ module.exports = function($){
var bukkitTask = server.scheduler.runTaskLater( __plugin, callback, delayInMillis/50 ); var bukkitTask = server.scheduler.runTaskLater( __plugin, callback, delayInMillis/50 );
return bukkitTask; return bukkitTask;
}; };
$.clearTimeout = function( bukkitTask ) { $.clearTimeout = function( bukkitTask ) {
bukkitTask.cancel(); bukkitTask.cancel();
}; };
@ -26,8 +27,10 @@ module.exports = function($){
var bukkitTask = server.scheduler.runTaskTimer( __plugin, callback, delay, delay ); var bukkitTask = server.scheduler.runTaskTimer( __plugin, callback, delay, delay );
return bukkitTask; return bukkitTask;
}; };
$.clearInterval = function( bukkitTask ) { $.clearInterval = function( bukkitTask ) {
bukkitTask.cancel(); bukkitTask.cancel();
}; };
}; };

View file

@ -1,19 +1,28 @@
var _dataDir = null,
var _dataDir = null; _persistentData = {};
var _persistentData = {};
module.exports = function( rootDir, $ ) { module.exports = function( rootDir, $ ) {
var _load = function( name ) {
$.scload( _dataDir.canonicalPath + '/' + name + '-store.json' );
};
var _save = function( name, data ) {
$.scsave( data, _dataDir.canonicalPath + '/' + name + '-store.json' );
};
_dataDir = new java.io.File( rootDir, 'data' ); _dataDir = new java.io.File( rootDir, 'data' );
$.persist = function( name, data, write ) { $.persist = function( name, data, write ) {
var i, dataFromFile; var i,
if (typeof data == 'undefined') dataFromFile;
if ( typeof data == 'undefined' ) {
data = {}; data = {};
if (typeof write == 'undefined') }
if ( typeof write == 'undefined' ) {
write = false; write = false;
}
if ( !write ) { if ( !write ) {
dataFromFile = $.scload(_dataDir.canonicalPath + '/' + name + '-store.json'); dataFromFile = _load( name );
if ( dataFromFile ) { if ( dataFromFile ) {
for ( i in dataFromFile ) { for ( i in dataFromFile ) {
data[i] = dataFromFile[i]; data[i] = dataFromFile[i];
@ -21,16 +30,20 @@ module.exports = function( rootDir, $ ){
} }
} else { } else {
// flush data to file // flush data to file
$.scsave(data, _dataDir.canonicalPath + '/' + name + '-store.json'); _save( name, data );
} }
_persistentData[name] = data; _persistentData[name] = data;
return data; return data;
}; };
/*
persist on shutdown
*/
$.addUnloadHandler( function( ) { $.addUnloadHandler( function( ) {
for (var name in _persistentData){ var name,
var data = _persistentData[name]; data;
$.scsave(data, _dataDir.canonicalPath + '/' + name + '-store.json'); for ( name in _persistentData ) {
data = _persistentData[name];
_save( name, data );
} }
}); });
}; };

View file

@ -1,4 +1,5 @@
'use strict'; 'use strict';
var console = require('./console'), var console = require('./console'),
File = java.io.File, File = java.io.File,
FileWriter = java.io.FileWriter, FileWriter = java.io.FileWriter,
@ -8,18 +9,18 @@ var console = require('./console'),
*/ */
var _plugins = {}; var _plugins = {};
var _plugin = function(/* String */ moduleName, /* Object */ moduleObject, isPersistent) var _plugin = function(/* String */ moduleName, /* Object */ moduleObject, isPersistent ) {
{
// //
// don't load plugin more than once // don't load plugin more than once
// //
if (typeof _plugins[moduleName] != 'undefined') if ( typeof _plugins[moduleName] != 'undefined' ) {
return _plugins[moduleName].module; return _plugins[moduleName].module;
}
var pluginData = { persistent: isPersistent, module: moduleObject }; var pluginData = { persistent: isPersistent, module: moduleObject };
if (typeof moduleObject.store == 'undefined') if ( typeof moduleObject.store == 'undefined' ) {
moduleObject.store = {}; moduleObject.store = {};
}
_plugins[moduleName] = pluginData; _plugins[moduleName] = pluginData;
if ( isPersistent ) { if ( isPersistent ) {
@ -46,13 +47,14 @@ exports.autoload = function(dir,logger) {
/* /*
recursively walk the given directory and return a list of all .js files recursively walk the given directory and return a list of all .js files
*/ */
var _listSourceFiles = function(store,dir) var _listSourceFiles = function( store, dir ) {
{ var files = dir.listFiles(),
var files = dir.listFiles(); file;
if (!files) if ( !files ) {
return; return;
}
for ( var i = 0; i < files.length; i++ ) { for ( var i = 0; i < files.length; i++ ) {
var file = files[i]; file = files[i];
if ( file.isDirectory( ) ) { if ( file.isDirectory( ) ) {
_listSourceFiles( store, file ); _listSourceFiles( store, file );
}else{ }else{
@ -65,20 +67,24 @@ exports.autoload = function(dir,logger) {
/* /*
Reload all of the .js files in the given directory Reload all of the .js files in the given directory
*/ */
var _reload = function(pluginDir) (function( pluginDir ) {
{ var sourceFiles = [],
var sourceFiles = []; property,
module,
pluginPath;
_listSourceFiles( sourceFiles, pluginDir ); _listSourceFiles( sourceFiles, pluginDir );
var len = sourceFiles.length; var len = sourceFiles.length;
if (config.verbose) if ( config.verbose ) {
console.info( len + ' scriptcraft plugins found.' ); console.info( len + ' scriptcraft plugins found.' );
}
for ( var i = 0; i < len; i++ ) { for ( var i = 0; i < len; i++ ) {
var pluginPath = _canonize(sourceFiles[i]); pluginPath = _canonize( sourceFiles[i] );
var module = {}; module = {};
try { try {
module = require( pluginPath ); module = require( pluginPath );
for (var property in module){ for ( property in module ) {
/* /*
all exports in plugins become global all exports in plugins become global
*/ */
@ -88,7 +94,6 @@ exports.autoload = function(dir,logger) {
logger.severe( 'Plugin ' + pluginPath + ' ' + e ); logger.severe( 'Plugin ' + pluginPath + ' ' + e );
} }
} }
}; }(pluginDir));
_reload(pluginDir);
}; };

View file

@ -93,7 +93,6 @@ module specification, the '.js' suffix is optional.
return "" + file.canonicalPath.replaceAll("\\\\","/"); return "" + file.canonicalPath.replaceAll("\\\\","/");
}; };
var resolveModuleToFile = function(moduleName, parentDir) {
/********************************************************************** /**********************************************************************
### module name resolution ### module name resolution
@ -128,6 +127,7 @@ When resolving module names to file paths, ScriptCraft uses the following rules.
3.2 if no package.json file exists then look for an index.js file in the directory 3.2 if no package.json file exists then look for an index.js file in the directory
***/ ***/
var resolveModuleToFile = function ( moduleName, parentDir ) {
var file = new File(moduleName); var file = new File(moduleName);
if ( file.exists() ) { if ( file.exists() ) {

View file

@ -415,34 +415,36 @@ var server = org.bukkit.Bukkit.server;
*/ */
function __onEnable ( __engine, __plugin, __script ) function __onEnable ( __engine, __plugin, __script )
{ {
var File = java.io.File var File = java.io.File,
,FileReader = java.io.FileReader FileReader = java.io.FileReader,
,BufferedReader = java.io.BufferedReader BufferedReader = java.io.BufferedReader,
,PrintWriter = java.io.PrintWriter PrintWriter = java.io.PrintWriter,
,FileWriter = java.io.FileWriter; FileWriter = java.io.FileWriter;
var _canonize = function( file ) { var _canonize = function( file ) {
return "" + file.getCanonicalPath().replaceAll("\\\\","/"); return '' + file.getCanonicalPath().replaceAll( '\\\\', '/' );
}; };
// lib (assumes scriptcraft.js is in craftbukkit/plugins/scriptcraft/lib directory
var libDir = __script.parentFile; // lib (assumes scriptcraft.js is in craftbukkit/plugins/scriptcraft/lib directory var libDir = __script.parentFile,
var jsPluginsRootDir = libDir.parentFile; // scriptcraft jsPluginsRootDir = libDir.parentFile, // scriptcraft
var jsPluginsRootDirName = _canonize(jsPluginsRootDir); jsPluginsRootDirName = _canonize(jsPluginsRootDir),
var logger = __plugin.logger; logger = __plugin.logger;
/* /*
Save a javascript object to a file (saves using JSON notation) Save a javascript object to a file (saves using JSON notation)
*/ */
var _save = function( object, filename ) { var _save = function( object, filename ) {
var objectToStr = null; var objectToStr = null,
f,
out;
try { try {
objectToStr = JSON.stringify( object, null, 2 ); objectToStr = JSON.stringify( object, null, 2 );
} catch( e ) { } catch( e ) {
print("ERROR: " + e.getMessage() + " while saving " + filename); print( 'ERROR: ' + e.getMessage() + ' while saving ' + filename );
return; return;
} }
var f = (filename instanceof File) ? filename : new File(filename); f = (filename instanceof File) ? filename : new File(filename);
var out = new PrintWriter(new FileWriter(f)); out = new PrintWriter(new FileWriter(f));
out.println( objectToStr ); out.println( objectToStr );
out.close(); out.close();
}; };
@ -460,30 +462,34 @@ function __onEnable (__engine, __plugin, __script)
*/ */
var _load = function( filename, warnOnFileNotFound ) var _load = function( filename, warnOnFileNotFound )
{ {
var result = null var result = null,
,file = filename file = filename,
,r = undefined; r,
parent,
reader,
br,
code,
wrappedCode;
if (!(filename instanceof File)) if ( !( filename instanceof File ) ) {
file = new File(filename); file = new File(filename);
}
var canonizedFilename = _canonize( file ); var canonizedFilename = _canonize( file );
if ( file.exists() ) { if ( file.exists() ) {
var parent = file.getParentFile(); parent = file.getParentFile();
var reader = new FileReader(file); reader = new FileReader( file );
var br = new BufferedReader(reader); br = new BufferedReader( reader );
var code = ""; code = '';
var wrappedCode;
try { try {
while ((r = br.readLine()) !== null) while ( (r = br.readLine()) !== null ) {
code += r + "\n"; code += r + '\n';
}
wrappedCode = "(" + code + ")"; wrappedCode = '(' + code + ')';
result = __engine.eval( wrappedCode ); result = __engine.eval( wrappedCode );
// issue #103 avoid side-effects of || operator on Mac Rhino // issue #103 avoid side-effects of || operator on Mac Rhino
} catch ( e ) { } catch ( e ) {
logger.severe("Error evaluating " + canonizedFilename + ", " + e ); logger.severe( 'Error evaluating ' + canonizedFilename + ', ' + e );
} }
finally { finally {
try { try {
@ -493,8 +499,9 @@ function __onEnable (__engine, __plugin, __script)
} }
} }
} else { } else {
if (warnOnFileNotFound) if ( warnOnFileNotFound ) {
logger.warning(canonizedFilename + " not found"); logger.warning( canonizedFilename + ' not found' );
}
} }
return result; return result;
}; };
@ -502,14 +509,18 @@ function __onEnable (__engine, __plugin, __script)
now that load is defined, use it to load a global config object now that load is defined, use it to load a global config object
*/ */
var config = _load( new File(jsPluginsRootDir, 'data/global-config.json' ) ); var config = _load( new File(jsPluginsRootDir, 'data/global-config.json' ) );
if (!config) if ( !config ) {
config = { verbose: false }; config = { verbose: false };
}
global.config = config; global.config = config;
global.__plugin = __plugin; global.__plugin = __plugin;
/* /*
wph 20131229 Issue #103 JSON is not bundled with javax.scripting / Rhino on Mac. wph 20131229 Issue #103 JSON is not bundled with javax.scripting / Rhino on Mac.
*/ */
var jsonLoaded = __engine["eval(java.io.Reader)"](new FileReader(new File(jsPluginsRootDirName + '/lib/json2.js'))); (function(){
var jsonFileReader = new FileReader( new File( jsPluginsRootDirName + '/lib/json2.js' ) );
var jsonLoaded = __engine['eval(java.io.Reader)']( jsonFileReader );
}());
/* /*
Unload Handlers Unload Handlers
@ -523,6 +534,8 @@ function __onEnable (__engine, __plugin, __script)
unloadHandlers[i]( ); unloadHandlers[i]( );
} }
}; };
global.addUnloadHandler = _addUnloadHandler;
global.refresh = function( ) { global.refresh = function( ) {
__plugin.pluginLoader.disablePlugin( __plugin ); __plugin.pluginLoader.disablePlugin( __plugin );
@ -530,7 +543,7 @@ function __onEnable (__engine, __plugin, __script)
}; };
var _echo = function ( msg ) { var _echo = function ( msg ) {
if (typeof self == "undefined"){ if ( typeof self == 'undefined' ) {
return; return;
} }
self.sendMessage( msg ); self.sendMessage( msg );
@ -541,8 +554,6 @@ function __onEnable (__engine, __plugin, __script)
global.scload = _load; global.scload = _load;
global.scsave = _save; global.scsave = _save;
global.addUnloadHandler = _addUnloadHandler;
var configRequire = _load( jsPluginsRootDirName + '/lib/require.js', true ); var configRequire = _load( jsPluginsRootDirName + '/lib/require.js', true );
/* /*
setup paths to search for modules setup paths to search for modules
@ -556,13 +567,15 @@ function __onEnable (__engine, __plugin, __script)
} }
var requireHooks = { var requireHooks = {
loading: function( path ) { loading: function( path ) {
if (config.verbose) if ( config.verbose ) {
logger.info( 'loading ' + path ); logger.info( 'loading ' + path );
}
}, },
loaded: function( path ) { loaded: function( path ) {
if (config.verbose) if ( config.verbose ) {
logger.info( 'loaded ' + path ); logger.info( 'loaded ' + path );
} }
}
}; };
global.require = configRequire( jsPluginsRootDirName, modulePaths, requireHooks ); global.require = configRequire( jsPluginsRootDirName, modulePaths, requireHooks );
@ -608,10 +621,11 @@ function __onEnable (__engine, __plugin, __script)
global.__engine = __engine; global.__engine = __engine;
try { try {
var jsResult = __engine.eval(fnBody); var jsResult = __engine.eval(fnBody);
if (jsResult) if ( jsResult ) {
sender.sendMessage(jsResult); sender.sendMessage(jsResult);
}
} catch ( e ) { } catch ( e ) {
logger.severe("Error while trying to evaluate javascript: " + fnBody + ", Error: "+ e); logger.severe( 'Error while trying to evaluate javascript: ' + fnBody + ', Error: '+ e );
throw e; throw e;
} finally { } finally {
delete global.self; delete global.self;
@ -629,16 +643,19 @@ function __onEnable (__engine, __plugin, __script)
/* /*
wph 20140102 - warn if legacy 'craftbukkit/js-plugins' or 'craftbukkit/scriptcraft' directories are present wph 20140102 - warn if legacy 'craftbukkit/js-plugins' or 'craftbukkit/scriptcraft' directories are present
*/ */
var cbPluginsDir = jsPluginsRootDir.parentFile; (function(){
var cbDir = new File(cbPluginsDir.canonicalPath).parentFile; var cbPluginsDir = jsPluginsRootDir.parentFile,
var legacyDirs = [ cbDir = new File(cbPluginsDir.canonicalPath).parentFile,
new File(cbDir, 'js-plugins'), legacyExists = false,
new File(cbDir, 'scriptcraft') legacyDirs = [new File( cbDir, 'js-plugins' ),
]; new File( cbDir, 'scriptcraft' )];
var legacyExists = false;
for ( var i = 0; i < legacyDirs.length; i++ ) { for ( var i = 0; i < legacyDirs.length; i++ ) {
if (legacyDirs[i].exists() && legacyDirs[i].isDirectory()){ if ( legacyDirs[i].exists()
&& legacyDirs[i].isDirectory() ) {
legacyExists = true; legacyExists = true;
console.warn('Legacy ScriptCraft directory %s was found. This directory is no longer used.', console.warn('Legacy ScriptCraft directory %s was found. This directory is no longer used.',
legacyDirs[i].canonicalPath); legacyDirs[i].canonicalPath);
} }
@ -647,4 +664,6 @@ function __onEnable (__engine, __plugin, __script)
console.info( 'Please note that the working directory for %s is %s', console.info( 'Please note that the working directory for %s is %s',
__plugin, jsPluginsRootDir.canonicalPath ); __plugin, jsPluginsRootDir.canonicalPath );
} }
})();
} }

View file

@ -4,17 +4,22 @@ var _commands = require('command').commands;
Tab completion for the /jsp commmand Tab completion for the /jsp commmand
*/ */
var __onTabCompleteJSP = function( result, cmdSender, pluginCmd, cmdAlias, cmdArgs ) { var __onTabCompleteJSP = function( result, cmdSender, pluginCmd, cmdAlias, cmdArgs ) {
var cmdInput = cmdArgs[0]; var cmdInput = cmdArgs[0],
var cmd = _commands[cmdInput]; opts,
cmd,
len,
i;
cmd = _commands[cmdInput];
if ( cmd ) { if ( cmd ) {
var opts = cmd.options; opts = cmd.options;
var len = opts.length; len = opts.length;
if ( cmdArgs.length == 1 ) { if ( cmdArgs.length == 1 ) {
for (var i = 0;i < len; i++) for ( i = 0; i < len; i++ ) {
result.add( opts[i] ); result.add( opts[i] );
}
} else { } else {
// partial e.g. /jsp chat_color dar // partial e.g. /jsp chat_color dar
for (var i = 0;i < len; i++){ for ( i = 0; i < len; i++ ) {
if ( opts[i].indexOf( cmdArgs[1] ) == 0 ) { if ( opts[i].indexOf( cmdArgs[1] ) == 0 ) {
result.add( opts[i] ); result.add( opts[i] );
} }
@ -22,15 +27,16 @@ var __onTabCompleteJSP = function( result, cmdSender, pluginCmd, cmdAlias, cmdAr
} }
} else { } else {
if ( cmdArgs.length == 0 ) { if ( cmdArgs.length == 0 ) {
for (var i in _commands) for ( i in _commands ) {
result.add( i ); result.add( i );
}
} else { } else {
// partial e.g. /jsp ho // partial e.g. /jsp ho
// should tabcomplete to home // should tabcomplete to home
// //
for (var c in _commands){ for ( i in _commands ) {
if (c.indexOf(cmdInput) == 0){ if ( i.indexOf( cmdInput ) == 0 ) {
result.add(c); result.add( i );
} }
} }
} }

View file

@ -6,7 +6,7 @@ var tabCompleteJSP = require('tabcomplete-jsp');
var _isJavaObject = function(o){ var _isJavaObject = function(o){
var result = false; var result = false;
try { try {
o.hasOwnProperty("testForJava"); o.hasOwnProperty( 'testForJava' );
}catch (e){ }catch (e){
// java will throw an error when an attempt is made to access the // java will throw an error when an attempt is made to access the
// hasOwnProperty method. (it won't exist for Java objects) // hasOwnProperty method. (it won't exist for Java objects)
@ -28,22 +28,25 @@ var _javaLangObjectMethods = [
,'finalize' ,'finalize'
]; ];
var _getProperties = function(o) var _getProperties = function( o ) {
{ var result = [],
var result = []; i,
if (_isJavaObject(o)) j,
{ isObjectMethod,
typeofProperty;
if ( _isJavaObject( o ) ) {
propertyLoop: propertyLoop:
for (var i in o) for ( i in o ) {
{
// //
// don't include standard Object methods // don't include standard Object methods
// //
var isObjectMethod = false; isObjectMethod = false;
for (var j = 0;j < _javaLangObjectMethods.length; j++) for ( j = 0; j < _javaLangObjectMethods.length; j++ ) {
if (_javaLangObjectMethods[j] == i) if ( _javaLangObjectMethods[j] == i ) {
continue propertyLoop; continue propertyLoop;
var typeofProperty = null; }
}
typeofProperty = null;
try { try {
typeofProperty = typeof o[i]; typeofProperty = typeof o[i];
} catch( e ) { } catch( e ) {
@ -53,65 +56,83 @@ var _getProperties = function(o)
throw e; throw e;
} }
} }
if (typeofProperty == 'function' ) if ( typeofProperty == 'function' ) {
result.push( i+'()' ); result.push( i+'()' );
else } else {
result.push( i ); result.push( i );
} }
}
} else { } else {
if (o.constructor == Array) if ( o.constructor == Array ) {
return result; return result;
}
for (var i in o){ for ( i in o ) {
if ( i.match( /^[^_]/ ) ) { if ( i.match( /^[^_]/ ) ) {
if (typeof o[i] == 'function') if ( typeof o[i] == 'function' ) {
result.push( i+'()' ); result.push( i+'()' );
else } else {
result.push( i ); result.push( i );
} }
} }
} }
}
return result.sort(); return result.sort();
}; };
var onTabCompleteJS = function( result, cmdSender, pluginCmd, cmdAlias, cmdArgs ) { var onTabCompleteJS = function( result, cmdSender, pluginCmd, cmdAlias, cmdArgs ) {
var _globalSymbols,
lastArg,
propsOfLastArg,
statement,
statementSyms,
lastSymbol,
parts,
name,
symbol,
lastGoodSymbol,
i,
objectProps,
candidate,
re,
li,
possibleCompletion;
cmdArgs = Array.prototype.slice.call( cmdArgs, 0 ); cmdArgs = Array.prototype.slice.call( cmdArgs, 0 );
if (pluginCmd.name == 'jsp') if ( pluginCmd.name == 'jsp' ) {
return tabCompleteJSP( result, cmdSender, pluginCmd, cmdAlias, cmdArgs ); return tabCompleteJSP( result, cmdSender, pluginCmd, cmdAlias, cmdArgs );
}
global.self = cmdSender; // bring in self just for autocomplete global.self = cmdSender; // bring in self just for autocomplete
var _globalSymbols = _getProperties(global) _globalSymbols = _getProperties(global);
var lastArg = cmdArgs.length?cmdArgs[cmdArgs.length-1]+'':null; lastArg = cmdArgs.length?cmdArgs[cmdArgs.length-1]+'':null;
var propsOfLastArg = []; propsOfLastArg = [];
var statement = cmdArgs.join(' '); statement = cmdArgs.join(' ');
statement = statement.replace(/^\s+/,'').replace(/\s+$/,''); statement = statement.replace(/^\s+/,'').replace(/\s+$/,'');
if ( statement.length == 0 ) {
if (statement.length == 0)
propsOfLastArg = _globalSymbols; propsOfLastArg = _globalSymbols;
else{ } else {
var statementSyms = statement.split(/[^\$a-zA-Z0-9_\.]/); statementSyms = statement.split(/[^\$a-zA-Z0-9_\.]/);
var lastSymbol = statementSyms[statementSyms.length-1]; lastSymbol = statementSyms[statementSyms.length-1];
//print('DEBUG: lastSymbol=[' + lastSymbol + ']'); //print('DEBUG: lastSymbol=[' + lastSymbol + ']');
// //
// try to complete the object ala java IDEs. // try to complete the object ala java IDEs.
// //
var parts = lastSymbol.split(/\./); parts = lastSymbol.split(/\./);
var name = parts[0]; name = parts[0];
var symbol = global[name]; symbol = global[name];
var lastGoodSymbol = symbol; lastGoodSymbol = symbol;
if (typeof symbol != 'undefined') if ( typeof symbol != 'undefined' ) {
{ for ( i = 1; i < parts.length; i++ ) {
for (var i = 1; i < parts.length;i++){
name = parts[i]; name = parts[i];
symbol = symbol[name]; symbol = symbol[name];
if (typeof symbol == 'undefined') if ( typeof symbol == 'undefined' ) {
break; break;
}
lastGoodSymbol = symbol; lastGoodSymbol = symbol;
} }
//print('debug:name['+name+']lastSymbol['+lastSymbol+']symbol['+symbol+']'); //print('debug:name['+name+']lastSymbol['+lastSymbol+']symbol['+symbol+']');
@ -119,15 +140,15 @@ var onTabCompleteJS = function( result, cmdSender, pluginCmd, cmdAlias, cmdArgs)
// //
// look up partial matches against last good symbol // look up partial matches against last good symbol
// //
var objectProps = _getProperties(lastGoodSymbol); objectProps = _getProperties( lastGoodSymbol );
if ( name == '' ) { if ( name == '' ) {
// if the last symbol looks like this.. // if the last symbol looks like this..
// ScriptCraft. // ScriptCraft.
// //
for (var i =0;i < objectProps.length;i++){ for ( i =0; i < objectProps.length; i++ ) {
var candidate = lastSymbol + objectProps[i]; candidate = lastSymbol + objectProps[i];
var re = new RegExp(lastSymbol + '$','g'); re = new RegExp( lastSymbol + '$', 'g' );
propsOfLastArg.push( lastArg.replace( re, candidate ) ); propsOfLastArg.push( lastArg.replace( re, candidate ) );
} }
@ -137,42 +158,36 @@ var onTabCompleteJS = function( result, cmdSender, pluginCmd, cmdAlias, cmdArgs)
// //
//print('debug:case Y: ScriptCraft.co'); //print('debug:case Y: ScriptCraft.co');
var li = statement.lastIndexOf(name); li = statement.lastIndexOf(name);
for (var i = 0; i < objectProps.length;i++){ for ( i = 0; i < objectProps.length; i++ ) {
if (objectProps[i].indexOf(name) == 0) if ( objectProps[i].indexOf(name) == 0 ) {
{ candidate = lastSymbol.substring( 0, lastSymbol.lastIndexOf( name ) );
var candidate = lastSymbol.substring(0,lastSymbol.lastIndexOf(name));
candidate = candidate + objectProps[i]; candidate = candidate + objectProps[i];
var re = new RegExp(lastSymbol+ '$','g'); re = new RegExp( lastSymbol + '$', 'g' );
//print('DEBUG: re=' + re + ',lastSymbol='+lastSymbol+',lastArg=' + lastArg + ',candidate=' + candidate);
propsOfLastArg.push( lastArg.replace( re, candidate ) ); propsOfLastArg.push( lastArg.replace( re, candidate ) );
} }
} }
} }
} else { } else {
//print('debug:case Z:ScriptCraft'); objectProps = _getProperties( symbol );
var objectProps = _getProperties(symbol); for ( i = 0; i < objectProps.length; i++ ) {
for (var i = 0; i < objectProps.length; i++){ re = new RegExp( lastSymbol+ '$', 'g' );
var re = new RegExp(lastSymbol+ '$','g');
propsOfLastArg.push( lastArg.replace( re, lastSymbol + '.' + objectProps[i] ) ); propsOfLastArg.push( lastArg.replace( re, lastSymbol + '.' + objectProps[i] ) );
} }
} }
} else { } else {
//print('debug:case AB:ScriptCr'); for ( i = 0; i < _globalSymbols.length; i++ ) {
// loop thru globalSymbols looking for a good match
for (var i = 0;i < _globalSymbols.length; i++){
if ( _globalSymbols[i].indexOf(lastSymbol) == 0 ) { if ( _globalSymbols[i].indexOf(lastSymbol) == 0 ) {
var possibleCompletion = _globalSymbols[i]; possibleCompletion = _globalSymbols[i];
var re = new RegExp(lastSymbol+ '$','g'); re = new RegExp( lastSymbol+ '$', 'g' );
propsOfLastArg.push( lastArg.replace( re, possibleCompletion ) ); propsOfLastArg.push( lastArg.replace( re, possibleCompletion ) );
} }
} }
} }
} }
for (var i = 0;i < propsOfLastArg.length; i++) for ( i = 0; i < propsOfLastArg.length; i++ ) {
result.add( propsOfLastArg[i] ); result.add( propsOfLastArg[i] );
}
delete global.self; // delete self when no longer needed for autocomplete delete global.self; // delete self when no longer needed for autocomplete
}; };

View file

@ -192,7 +192,7 @@ var blocks = {
oak: '126:8', oak: '126:8',
spruce: '126:9', spruce: '126:9',
birch: '126:10', birch: '126:10',
jungle: '126:11', jungle: '126:11'
} }
}, },
cocoa: 127, cocoa: 127,
@ -252,7 +252,7 @@ var colors = {
red: ':14', red: ':14',
black: ':15' black: ':15'
}; };
var colorized_blocks = ["wool", "stained_clay", "carpet"]; var colorized_blocks = ['wool', 'stained_clay', 'carpet'];
for (var i = 0, len = colorized_blocks.length; i < len; i++) { for (var i = 0, len = colorized_blocks.length; i < len; i++) {
var block = colorized_blocks[i], var block = colorized_blocks[i],
@ -269,7 +269,8 @@ for (var i = 0, len = colorized_blocks.length; i < len; i++) {
object are no longer used to avoid confusion with carpet and stained object are no longer used to avoid confusion with carpet and stained
clay blocks. clay blocks.
*/ */
blocks.rainbow = [blocks.wool.red, blocks.rainbow = [
blocks.wool.red,
blocks.wool.orange, blocks.wool.orange,
blocks.wool.yellow, blocks.wool.yellow,
blocks.wool.lime, blocks.wool.lime,
@ -277,5 +278,4 @@ blocks.rainbow = [blocks.wool.red,
blocks.wool.blue, blocks.wool.blue,
blocks.wool.purple]; blocks.wool.purple];
module.exports = blocks; module.exports = blocks;

View file

@ -68,7 +68,8 @@ var firework = function(location){
var effectBuilder = FireworkEffect.builder() var effectBuilder = FireworkEffect.builder()
.flicker( Math.round( Math.random() ) == 0 ) .flicker( Math.round( Math.random() ) == 0 )
.withColor( c1 ) .withColor( c1 )
.withFade(c2).trail(Math.round(Math.random())==0); .withFade( c2 )
.trail( Math.round( Math.random() ) == 0 );
effectBuilder['with']( type ); effectBuilder['with']( type );
var effect = effectBuilder.build(); var effect = effectBuilder.build();
fwm.addEffect( effect ); fwm.addEffect( effect );

View file

@ -37,46 +37,48 @@ The following example illustrates how to use http.request to make a request to a
... The following example illustrates a more complex use-case POSTing parameters to a CGI process on a server... ... The following example illustrates a more complex use-case POSTing parameters to a CGI process on a server...
var http = require('./http/request'); var http = require('./http/request');
http.request({ url: "http://pixenate.com/pixenate/pxn8.pl", http.request(
method: "POST", {
params: {script: "[]"} url: 'http://pixenate.com/pixenate/pxn8.pl',
}, function( responseCode, responseBody){ method: 'POST',
var jsObj = eval("(" + responseBody + ")"); params: {script: '[]'}
},
function( responseCode, responseBody ) {
var jsObj = eval('(' + responseBody + ')');
}); });
***/ ***/
exports.request = function( request, callback) exports.request = function( request, callback ) {
{
var paramsToString = function( params ) { var paramsToString = function( params ) {
var result = ""; var result = '',
var paramNames = []; paramNames = [],
for (var i in params){ i;
for ( i in params ) {
paramNames.push( i ); paramNames.push( i );
} }
for (var i = 0;i < paramNames.length;i++){ for ( i = 0; i < paramNames.length; i++ ) {
result += paramNames[i] + "=" + encodeURI(params[paramNames[i]]); result += paramNames[i] + '=' + encodeURI( params[ paramNames[i] ] );
if ( i < paramNames.length-1 ) if ( i < paramNames.length-1 )
result += "&"; result += '&';
} }
return result; return result;
}; };
server.scheduler.runTaskAsynchronously(__plugin,function() server.scheduler.runTaskAsynchronously( __plugin, function() {
{
var url, paramsAsString, conn, requestMethod; var url, paramsAsString, conn, requestMethod;
if (typeof request === "string"){ if (typeof request === 'string'){
url = request; url = request;
requestMethod = "GET"; requestMethod = 'GET';
}else{ }else{
paramsAsString = paramsToString( request.params ); paramsAsString = paramsToString( request.params );
if (request.method) if ( request.method ) {
requestMethod = request.method requestMethod = request.method;
else } else {
requestMethod = "GET"; requestMethod = 'GET';
}
if (requestMethod == "GET" && request.params){ if ( requestMethod == 'GET' && request.params ) {
// append each parameter to the URL // append each parameter to the URL
url = request.url + "?" + paramsAsString; url = request.url + '?' + paramsAsString;
} }
} }
conn = new java.net.URL( url ).openConnection(); conn = new java.net.URL( url ).openConnection();
@ -84,12 +86,12 @@ exports.request = function( request, callback)
conn.doOutput = true; conn.doOutput = true;
conn.instanceFollowRedirects = false; conn.instanceFollowRedirects = false;
if (conn.requestMethod == "POST"){ if ( conn.requestMethod == 'POST' ) {
conn.doInput = true; conn.doInput = true;
// put each parameter in the outputstream // put each parameter in the outputstream
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty('Content-Type', 'application/x-www-form-urlencoded');
conn.setRequestProperty("charset", "utf-8"); conn.setRequestProperty('charset', 'utf-8');
conn.setRequestProperty("Content-Length", "" + paramsAsString.length); conn.setRequestProperty('Content-Length', '' + paramsAsString.length);
conn.useCaches =false ; conn.useCaches =false ;
wr = new java.io.DataOutputStream(conn.getOutputStream ()); wr = new java.io.DataOutputStream(conn.getOutputStream ());
wr.writeBytes(paramsAsString); wr.writeBytes(paramsAsString);

View file

@ -9,10 +9,12 @@ module.exports = function(options){
return { return {
start: function( ) { start: function( ) {
var objective, slot; var objective,
slot,
ccObj;
ccScoreboard = server.scoreboardManager.getNewScoreboard(); ccScoreboard = server.scoreboardManager.getNewScoreboard();
for ( objective in options ) { for ( objective in options ) {
var ccObj = ccScoreboard.registerNewObjective(objective,'dummy'); ccObj = ccScoreboard.registerNewObjective( objective, 'dummy' );
for ( slot in options[ objective ] ) { for ( slot in options[ objective ] ) {
ccObj.displaySlot = DisplaySlot[ slot ]; ccObj.displaySlot = DisplaySlot[ slot ];
ccObj.displayName = options[ objective ][ slot ]; ccObj.displayName = options[ objective ][ slot ];
@ -29,17 +31,20 @@ module.exports = function(options){
} }
}, },
update: function( objective, player, score ) { update: function( objective, player, score ) {
if (player.scoreboard && player.scoreboard != ccScoreboard) if ( player.scoreboard && player.scoreboard != ccScoreboard ) {
{
temp[player.name] = player.scoreboard; temp[player.name] = player.scoreboard;
player.scoreboard = ccScoreboard; player.scoreboard = ccScoreboard;
} }
ccScoreboard.getObjective(objective).getScore(player).score = score; ccScoreboard
.getObjective( objective )
.getScore( player )
.score = score;
}, },
restore: function( player ) { restore: function( player ) {
// offlineplayers don't have a scoreboard // offlineplayers don't have a scoreboard
if (player.scoreboard) if ( player.scoreboard ) {
player.scoreboard = temp[ player.name ]; player.scoreboard = temp[ player.name ];
} }
}
}; };
}; };

View file

@ -1,14 +0,0 @@
/**
* Create a partial function
*
* Parameters:
* func - base function
* [remaining arguments] - arguments bound to the partial function
*/
module.exports = function (func /*, 0..n args */) {
var args = Array.prototype.slice.call(arguments, 1);
return function() {
var allArguments = args.concat(Array.prototype.slice.call(arguments));
return func.apply(this, allArguments);
};
}

View file

@ -92,7 +92,6 @@ function Client(brokerUrl, clientId){
var client = new MqttClient( brokerUrl, clientId, null ); var client = new MqttClient( brokerUrl, clientId, null );
client.setCallback( callback ); client.setCallback( callback );
return { return {
connect: function( options ) { connect: function( options ) {
if ( typeof options === 'undefined' ) { if ( typeof options === 'undefined' ) {
client.connect(); client.connect();
@ -103,10 +102,11 @@ function Client(brokerUrl, clientId){
}, },
disconnect: function( quiesceTimeout ) { disconnect: function( quiesceTimeout ) {
if (typeof quiesceTimeout == 'undefined') if ( typeof quiesceTimeout == 'undefined' ) {
client.disconnect(); client.disconnect();
else } else {
client.disconnect( quiesceTimeout ); client.disconnect( quiesceTimeout );
}
return client; return client;
}, },
@ -150,7 +150,9 @@ function Client(brokerUrl, clientId){
} }
}; };
} }
/*
Return a new MQTT Client
*/
exports.client = function( brokerUrl, clientId, options ) { exports.client = function( brokerUrl, clientId, options ) {
if ( typeof org.walterhiggins.scriptcraft.ScriptCraftMqttCallback != 'function' ) { if ( typeof org.walterhiggins.scriptcraft.ScriptCraftMqttCallback != 'function' ) {
throw MISSING_MQTT; throw MISSING_MQTT;

View file

@ -16,24 +16,28 @@ var signs = plugin("signs", {
/* Function */ onInteract, /* Function */ onInteract,
/* Number */ defaultSelection ){}, /* Number */ defaultSelection ){},
store: _store store: _store
},true); },
true);
module.exports = signs; module.exports = signs;
/* /*
redraw a menu sign redraw a menu sign
*/ */
var _redrawMenuSign = function(p_sign,p_selectedIndex,p_displayOptions) var _redrawMenuSign = function( p_sign, p_selectedIndex, p_displayOptions ) {
{ var optLen = p_displayOptions.length,
var optLen = p_displayOptions.length; i,
text;
// the offset is where the menu window begins // the offset is where the menu window begins
var offset = Math.max( 0, Math.min( optLen-3, Math.floor( p_selectedIndex/3 ) * 3) ); var offset = Math.max( 0, Math.min( optLen-3, Math.floor( p_selectedIndex/3 ) * 3) );
for (var i = 0;i < 3; i++){ for ( i = 0;i < 3; i++ ) {
var text = ""; text = "";
if (offset+i < optLen) if ( offset+i < optLen ) {
text = p_displayOptions[offset+i]; text = p_displayOptions[offset+i];
if (offset+i == p_selectedIndex) }
text = ("" + text).replace(/^ /,">"); if ( offset+i == p_selectedIndex ) {
text = ('' + text).replace(/^ /,">");
}
p_sign.setLine( i+1, text ); p_sign.setLine( i+1, text );
} }
p_sign.update( true ); p_sign.update( true );
@ -44,26 +48,22 @@ var _updaters = {};
construct an interactive menu to be subsequently attached to construct an interactive menu to be subsequently attached to
one or more Signs. one or more Signs.
*/ */
signs.menu = function( signs.menu = function( /* String */ label, /* Array */ options, /* Function */ callback, /* Number */ selectedIndex ) {
/* String */ label,
/* Array */ options,
/* Function */ callback,
/* Number */ selectedIndex
)
{
if (typeof selectedIndex == "undefined") if ( typeof selectedIndex == "undefined" ) {
selectedIndex = 0; selectedIndex = 0;
}
// //
// variables common to all instances of this menu can go here // variables common to all instances of this menu can go here
// //
var labelPadding = "---------------"; var labelPadding = "---------------";
var optionPadding = " "; var optionPadding = " ";
var i;
var paddedLabel = (labelPadding+label+labelPadding).substr(((label.length+30)/2)-7,15); var paddedLabel = ( labelPadding + label + labelPadding)
.substr( ( ( label.length+30 ) / 2 ) - 7, 15 );
var optLen = options.length; var optLen = options.length;
var displayOptions = []; var displayOptions = [];
for (var i =0;i < options.length;i++){ for ( i = 0; i < options.length; i++ ) {
displayOptions[i] = (" " + options[i] + optionPadding).substring(0,15); displayOptions[i] = (" " + options[i] + optionPadding).substring(0,15);
} }
/* /*
@ -72,16 +72,17 @@ signs.menu = function(
signs.menu is for use by Plugin Authors. signs.menu is for use by Plugin Authors.
The function returned by signs.menu is for use by admins/ops. The function returned by signs.menu is for use by admins/ops.
*/ */
var convertToMenuSign = function(/* Sign */ sign, save) var convertToMenuSign = function(/* Sign */ sign, save) {
{ var mouseLoc;
if (typeof save == "undefined") if (typeof save == "undefined") {
save = true; save = true;
}
/* /*
@deprecated start @deprecated start
all calls should explicitly provide a [org.bukkit.block.Sign][buksign] parameter. all calls should explicitly provide a [org.bukkit.block.Sign][buksign] parameter.
*/ */
if ( typeof sign == "undefined" ) { if ( typeof sign == "undefined" ) {
var mouseLoc = utils.getMousePos(); mouseLoc = utils.getMousePos();
if ( mouseLoc ) { if ( mouseLoc ) {
sign = mouseLoc.block.state; sign = mouseLoc.block.state;
if ( !( sign && sign.setLine ) ) { if ( !( sign && sign.setLine ) ) {
@ -102,11 +103,12 @@ signs.menu = function(
var _updateSign = function( p_player, p_sign ) { var _updateSign = function( p_player, p_sign ) {
cSelectedIndex = ( cSelectedIndex + 1 ) % optLen; cSelectedIndex = ( cSelectedIndex + 1 ) % optLen;
_redrawMenuSign( p_sign, cSelectedIndex, displayOptions ); _redrawMenuSign( p_sign, cSelectedIndex, displayOptions );
var signSelectionEvent = {player: p_player, var signSelectionEvent = {
player: p_player,
sign: p_sign, sign: p_sign,
text: options[ cSelectedIndex ], text: options[ cSelectedIndex ],
number:cSelectedIndex}; number: cSelectedIndex
};
callback( signSelectionEvent ); callback( signSelectionEvent );
}; };
@ -131,11 +133,13 @@ signs.menu = function(
when the server starts up again. when the server starts up again.
*/ */
if ( save ) { if ( save ) {
if (typeof _store.menus == "undefined") if ( typeof _store.menus == "undefined") {
_store.menus = {}; _store.menus = {};
}
var signLocations = _store.menus[label]; var signLocations = _store.menus[label];
if (typeof signLocations == "undefined") if ( typeof signLocations == "undefined" ) {
signLocations = _store.menus[label] = []; signLocations = _store.menus[label] = [];
}
signLocations.push( menuSignSaveData ); signLocations.push( menuSignSaveData );
} }
return sign; return sign;
@ -148,17 +152,16 @@ signs.menu = function(
world with this same label and make dynamic again. world with this same label and make dynamic again.
*/ */
if (_store.menus && _store.menus[label]) if ( _store.menus && _store.menus[label] ) {
{
var signsOfSameLabel = _store.menus[ label ]; var signsOfSameLabel = _store.menus[ label ];
var defragged = []; var defragged = [];
var len = signsOfSameLabel.length; var len = signsOfSameLabel.length;
for (var i = 0; i < len ; i++) for ( i = 0; i < len; i++ ) {
{
var loc = signsOfSameLabel[i]; var loc = signsOfSameLabel[i];
var world = org.bukkit.Bukkit.getWorld(loc.world); var world = org.bukkit.Bukkit.getWorld(loc.world);
if (!world) if ( !world ) {
continue; continue;
}
var block = world.getBlockAt( loc.x, loc.y, loc.z ); var block = world.getBlockAt( loc.x, loc.y, loc.z );
if ( block.state instanceof org.bukkit.block.Sign ) { if ( block.state instanceof org.bukkit.block.Sign ) {
convertToMenuSign( block.state, false ); convertToMenuSign( block.state, false );
@ -184,12 +187,14 @@ events.on('player.PlayerInteractEvent',function(listener, event) {
a sign, then update it. a sign, then update it.
*/ */
if (! event.clickedBlock.state instanceof org.bukkit.block.Sign) if ( ! event.clickedBlock.state instanceof org.bukkit.block.Sign ) {
return; return;
}
var evtLocStr = utils.locationToString(event.clickedBlock.location); var evtLocStr = utils.locationToString(event.clickedBlock.location);
var signUpdater = _updaters[evtLocStr] var signUpdater = _updaters[evtLocStr];
if (signUpdater) if ( signUpdater ) {
signUpdater( event.player, event.clickedBlock.state ); signUpdater( event.player, event.clickedBlock.state );
}
}); });

View file

@ -98,10 +98,12 @@ for (var i in menu){
exports.getTargetedBy = function( livingEntity ) { exports.getTargetedBy = function( livingEntity ) {
var location = utils.getMousePos( livingEntity ); var location = utils.getMousePos( livingEntity );
if (!location) if ( !location ) {
return null; return null;
}
var state = location.block.state; var state = location.block.state;
if (!(state || state.setLine)) if ( ! (state || state.setLine) ) {
return null; return null;
}
return state; return state;
}; };

View file

@ -118,17 +118,19 @@ Location object.
***/ ***/
exports.locationFromJSON = function( json ) { exports.locationFromJSON = function( json ) {
var world;
if ( json.constuctor == Array ) { if ( json.constuctor == Array ) {
// for support of legacy format // for support of legacy format
var world = org.bukkit.Bukkit.getWorld(json[0]); world = org.bukkit.Bukkit.getWorld( json[0] );
return new org.bukkit.Location( world, json[1], json[2] , json[3] ); return new org.bukkit.Location( world, json[1], json[2] , json[3] );
} else { } else {
var world = org.bukkit.Bukkit.getWorld(json.world); world = org.bukkit.Bukkit.getWorld( json.world );
return new org.bukkit.Location( world, json.x, json.y , json.z, json.yaw, json.pitch ); return new org.bukkit.Location( world, json.x, json.y , json.z, json.yaw, json.pitch );
} }
}; };
exports.player = _player; exports.player = _player;
exports.getPlayerObject = function( player ) { exports.getPlayerObject = function( player ) {
console.warn( 'utils.getPlayerObject() is deprecated. Use utils.player() instead.' ); console.warn( 'utils.getPlayerObject() is deprecated. Use utils.player() instead.' );
return _player(player); return _player(player);
@ -160,7 +162,6 @@ exports.getPlayerPos = function( player ) {
else else
return player.location; return player.location;
} }
else
return null; return null;
}; };
/************************************************************************ /************************************************************************
@ -189,11 +190,13 @@ The following code will strike lightning at the location the player is looking a
exports.getMousePos = function( player ) { exports.getMousePos = function( player ) {
player = _player(player); player = _player(player);
if (!player) if ( !player ) {
return null; return null;
}
// player might be CONSOLE or a CommandBlock // player might be CONSOLE or a CommandBlock
if (!player.getTargetBlock) if ( !player.getTargetBlock ) {
return null; return null;
}
var targetedBlock = player.getTargetBlock( null, 5 ); var targetedBlock = player.getTargetBlock( null, 5 );
if ( targetedBlock == null || targetedBlock.isEmpty() ) { if ( targetedBlock == null || targetedBlock.isEmpty() ) {
return null; return null;
@ -228,7 +231,7 @@ package for scheduling processing of arrays.
- object : Additional (optional) information passed into the foreach method. - object : Additional (optional) information passed into the foreach method.
- array : The entire array. - array : The entire array.
* object (optional) : An object which may be used by the callback. * context (optional) : An object which may be used by the callback.
* delay (optional, numeric) : If a delay is specified (in ticks - 20 * delay (optional, numeric) : If a delay is specified (in ticks - 20
ticks = 1 second), then the processing will be scheduled so that ticks = 1 second), then the processing will be scheduled so that
each item will be processed in turn with a delay between the completion of each each item will be processed in turn with a delay between the completion of each
@ -286,18 +289,24 @@ without hogging CPU usage...
utils.foreach (a, processItem, null, 10, onDone); utils.foreach (a, processItem, null, 10, onDone);
***/ ***/
var _foreach = function(array, callback, object, delay, onCompletion) { var _foreach = function( array, callback, context, delay, onCompletion ) {
if (array instanceof java.util.Collection) if ( array instanceof java.util.Collection ) {
array = array.toArray(); array = array.toArray();
}
var i = 0; var i = 0;
var len = array.length; var len = array.length;
if ( delay ) { if ( delay ) {
var next = function(){ callback(array[i],i,object,array); i++;}; var next = function( ) {
var hasNext = function(){return i < len;}; callback(array[i], i, context, array);
i++;
};
var hasNext = function( ) {
return i < len;
};
_nicely( next, hasNext, onCompletion, delay ); _nicely( next, hasNext, onCompletion, delay );
} else { } else {
for ( ;i < len; i++ ) { for ( ;i < len; i++ ) {
callback(array[i],i,object,array); callback( array[i], i, context, array );
} }
} }
}; };
@ -334,9 +343,10 @@ var _nicely = function(next, hasNext, onDone, delay){
_nicely( next, hasNext, onDone, delay ); _nicely( next, hasNext, onDone, delay );
}, delay ); }, delay );
}else{ }else{
if (onDone) if ( onDone ) {
onDone(); onDone();
} }
}
}; };
exports.nicely = _nicely; exports.nicely = _nicely;
/************************************************************************ /************************************************************************
@ -372,9 +382,9 @@ exports.at = function(time24hr, callback, worlds) {
var timeParts = time24hr.split( ':' ); var timeParts = time24hr.split( ':' );
var hrs = ( (timeParts[0] * 1000) + 18000 ) % 24000; var hrs = ( (timeParts[0] * 1000) + 18000 ) % 24000;
var mins; var mins;
if (timeParts.length > 1) if ( timeParts.length > 1 ) {
mins = ( timeParts[1] / 60 ) * 1000; mins = ( timeParts[1] / 60 ) * 1000;
}
var timeMc = hrs + mins; var timeMc = hrs + mins;
if ( typeof worlds == 'undefined' ) { if ( typeof worlds == 'undefined' ) {
worlds = server.worlds; worlds = server.worlds;
@ -416,11 +426,11 @@ exports.find = function( dir , filter){
var recurse = function( dir, store ) { var recurse = function( dir, store ) {
var files, dirfile = new java.io.File( dir ); var files, dirfile = new java.io.File( dir );
if (typeof filter == 'undefined') if ( typeof filter == 'undefined' ) {
files = dirfile.list(); files = dirfile.list();
else } else {
files = dirfile.list(filter); files = dirfile.list(filter);
}
_foreach( files, function( file ) { _foreach( files, function( file ) {
file = new java.io.File( dir + '/' + file ); file = new java.io.File( dir + '/' + file );
if ( file.isDirectory() ) { if ( file.isDirectory() ) {
@ -429,7 +439,7 @@ exports.find = function( dir , filter){
store.push( file.canonicalPath ); store.push( file.canonicalPath );
} }
}); });
} };
recurse( dir, result ); recurse( dir, result );
return result; return result;
} };

View file

@ -52,7 +52,7 @@ console. Aliases will not be able to avail of command autocompletion
***/ ***/
var _usage = "\ var _usage = '\
/jsp alias set {alias} = {comand-1} ;{command-2}\n \ /jsp alias set {alias} = {comand-1} ;{command-2}\n \
/jsp alias global {alias} = {command-1} ; {command-2}\n \ /jsp alias global {alias} = {command-1} ; {command-2}\n \
/jsp alias list\n \ /jsp alias list\n \
@ -61,7 +61,7 @@ Create a new alias : \n \
/jsp alias set cw = time set {1} ; weather {2}\n \ /jsp alias set cw = time set {1} ; weather {2}\n \
Execute the alias : \n \ Execute the alias : \n \
/cw 4000 sun \n \ /cw 4000 sun \n \
...is the same as '/time set 4000' and '/weather sun'"; ...is the same as \'/time set 4000\' and \'/weather sun\'';
/* /*
persist aliases persist aliases
*/ */
@ -93,53 +93,53 @@ var _set = function(params, player){
var o = _processParams( params ); var o = _processParams( params );
playerAliases[o.cmd] = o.aliases; playerAliases[o.cmd] = o.aliases;
_store.players[player.name] = playerAliases; _store.players[player.name] = playerAliases;
player.sendMessage("Alias '" + o.cmd + "' created."); player.sendMessage( 'Alias ' + o.cmd + ' created.' );
}; };
var _remove = function( params, player ) { var _remove = function( params, player ) {
if (_store.players[player.name] && if ( _store.players[player.name] && _store.players[player.name][ params[0] ] ) {
_store.players[player.name][params[0]]){
delete _store.players[player.name][params[0]]; delete _store.players[player.name][params[0]];
player.sendMessage("Alias '" + params[0] + "' removed."); player.sendMessage( 'Alias ' + params[0] + ' removed.' );
} }
else{ else{
player.sendMessage("Alias '" + params[0] + "' does not exist."); player.sendMessage( 'Alias ' + params[0] + ' does not exist.' );
} }
if ( player.op ) { if ( player.op ) {
if (_store.global[params[0]]) if ( _store.global[params[0]] ) {
delete _store.global[params[0]]; delete _store.global[params[0]];
} }
}
}; };
var _global = function( params, player ) { var _global = function( params, player ) {
if ( !player.op ) { if ( !player.op ) {
player.sendMessage("Only operators can set global aliases. " + player.sendMessage( 'Only operators can set global aliases. ' +
"You need to be an operator to perform this command."); 'You need to be an operator to perform this command.' );
return; return;
} }
var o = _processParams( params ); var o = _processParams( params );
_store.global[o.cmd] = o.aliases; _store.global[o.cmd] = o.aliases;
player.sendMessage("Global alias '" + o.cmd + "' created."); player.sendMessage( 'Global alias ' + o.cmd + ' created.' );
}; };
var _list = function( params, player ) { var _list = function( params, player ) {
var alias = 0; var alias = 0;
try { try {
if ( _store.players[player.name] ) { if ( _store.players[player.name] ) {
player.sendMessage("Your aliases:"); player.sendMessage('Your aliases:');
for ( alias in _store.players[player.name] ) { for ( alias in _store.players[player.name] ) {
player.sendMessage(alias + " = " + player.sendMessage( alias + ' = ' +
JSON.stringify( _store.players[player.name][alias] ) ); JSON.stringify( _store.players[player.name][alias] ) );
} }
} else { } else {
player.sendMessage("You have no player-specific aliases."); player.sendMessage( 'You have no player-specific aliases.' );
} }
player.sendMessage("Global aliases:"); player.sendMessage( 'Global aliases:' );
for ( alias in _store.global ) { for ( alias in _store.global ) {
player.sendMessage(alias + " = " + JSON.stringify(_store.global[alias]) ); player.sendMessage( alias + ' = ' + JSON.stringify( _store.global[alias] ) );
} }
} catch( e ) { } catch( e ) {
console.error("Error in list function: " + e.message); console.error( 'Error in list function: ' + e.message );
throw e; throw e;
} }
}; };
@ -178,15 +178,17 @@ var aliasCmd = command('alias', function( params, invoker ) {
invoker.sendMessage( 'Usage:\n' + _usage ); invoker.sendMessage( 'Usage:\n' + _usage );
}); });
var _intercept = function( msg, invoker, exec) var _intercept = function( msg, invoker, exec ) {
{
if ( msg.trim().length == 0 ) if ( msg.trim().length == 0 )
return false; return false;
var msgParts = msg.split(' '), var msgParts = msg.split(' '),
command = msg.match( /^\/*([^\s]+)/ )[1], command = msg.match( /^\/*([^\s]+)/ )[1],
template = [], isAlias = false, cmds = [], template = [],
isAlias = false,
cmds = [],
commandObj, commandObj,
filledinCommand; filledinCommand,
i;
if ( _store.global[command] ) { if ( _store.global[command] ) {
template = _store.global[command]; template = _store.global[command];
@ -195,25 +197,23 @@ var _intercept = function( msg, invoker, exec)
/* /*
allows player-specific aliases to override global aliases allows player-specific aliases to override global aliases
*/ */
if (_store.players[invoker] && if ( _store.players[invoker] && _store.players[invoker][command] ) {
_store.players[invoker][command])
{
template = _store.players[invoker][command]; template = _store.players[invoker][command];
isAlias = true; isAlias = true;
} }
for (var i = 0;i < template.length; i++) for ( i = 0; i < template.length; i++) {
{
filledinCommand = template[i].replace( /{([0-9]+)}/g, function( match, index ) { filledinCommand = template[i].replace( /{([0-9]+)}/g, function( match, index ) {
index = parseInt( index, 10 ); index = parseInt( index, 10 );
if (msgParts[index]) if ( msgParts[index] ) {
return msgParts[index]; return msgParts[index];
else } else {
return match; return match;
}
}); });
cmds.push( filledinCommand ); cmds.push( filledinCommand );
} }
for (var i = 0; i< cmds.length; i++){ for (i = 0; i< cmds.length; i++ ) {
exec( cmds[i] ); exec( cmds[i] );
} }
return isAlias; return isAlias;
@ -225,18 +225,25 @@ var _intercept = function( msg, invoker, exec)
*/ */
events.on( 'player.PlayerCommandPreprocessEvent', function( listener, evt ) { events.on( 'player.PlayerCommandPreprocessEvent', function( listener, evt ) {
var invoker = evt.player; var invoker = evt.player;
var exec = function(cmd){ invoker.performCommand(cmd);}; var exec = function( cmd ) {
invoker.performCommand(cmd);
};
var isAlias = _intercept( ''+evt.message, ''+invoker.name, exec); var isAlias = _intercept( ''+evt.message, ''+invoker.name, exec);
if (isAlias) if ( isAlias ) {
evt.cancelled = true; evt.cancelled = true;
}
}); });
/* define a 'void' command because ServerCommandEvent can't be canceled */ /* define a 'void' command because ServerCommandEvent can't be canceled */
command('void',function(){}); command('void',function( ) {
} );
events.on( 'server.ServerCommandEvent', function( listener, evt ) { events.on( 'server.ServerCommandEvent', function( listener, evt ) {
var invoker = evt.sender; var invoker = evt.sender;
var exec = function(cmd){ invoker.server.dispatchCommand(invoker, cmd); }; var exec = function( cmd ) {
invoker.server.dispatchCommand( invoker, cmd);
};
var isAlias = _intercept( ''+evt.command, ''+ invoker.name, exec ); var isAlias = _intercept( ''+evt.command, ''+ invoker.name, exec );
if (isAlias) if ( isAlias ) {
evt.command = 'jsp void'; evt.command = 'jsp void';
}
}); });

View file

@ -25,64 +25,32 @@ player23's arrows explosive.
***/ ***/
var signs = require('signs'); var signs = require('signs'),
var fireworks = require('fireworks'); fireworks = require('fireworks'),
var utils = require('utils'); utils = require('utils'),
EXPLOSIVE_YIELD = 2.5,
var _store = {players: {}}; _store = { players: { } },
arrows = plugin( 'arrows', { store: _store }, true ),
var arrows = plugin("arrows",{ i,
/* type,
turn a sign into a menu of arrow choices _types = [ 'Normal', 'Explosive', 'Teleport', 'Flourish', 'Lightning', 'Firework' ];
*/
sign: function(sign){},
/*
change player's arrows to normal
*/
normal: function(player){},
/*
change player's arrows to explode on impact
*/
explosive: function(player){},
/*
change player's arrows to teleporting
*/
teleport: function(player){},
/*
change player's arrows to plant trees where they land
*/
flourish: function(player){},
/*
change player's arrows to strike lightning where they land
*/
lightning: function(player){},
/*
launch a firework where the arrow lands
*/
explosiveYield: 2.5,
store: _store
},true);
exports.arrows = arrows; exports.arrows = arrows;
//
// setup functions for the arrow types for ( i = 0; i < _types.length; i++ ) {
// type = _types[i].toLowerCase();
var _types = {normal: 0, explosive: 1, teleport: 2, flourish: 3, lightning: 4, firework: 5}; // iife (immediately-invoked function expression)
for (var type in _types)
{
arrows[ type ] = ( function( n ) { arrows[ type ] = ( function( n ) {
return function( player ) { return function( player ) {
player = utils.player( player ); player = utils.player( player );
if (player) if ( player ) {
arrows.store.players[ player.name ] = n; arrows.store.players[ player.name ] = n;
else } else {
console.warn('arrows.' + n + ' No player ' + player); console.warn('arrows.' + n + ' No player ' + player);
}
}; };
})(_types[type]); } )( i );
} }
/* /*
@ -91,13 +59,12 @@ for (var type in _types)
var _onMenuChoice = function( event ) { var _onMenuChoice = function( event ) {
arrows.store.players[ event.player.name ] = event.number; arrows.store.players[ event.player.name ] = event.number;
}; };
var convertToArrowSign = signs.menu( var convertToArrowSign = signs.menu( 'Arrow', _types, _onMenuChoice );
"Arrow",
["Normal","Explosive","Teleport","Flourish","Lightning","Firework"],
_onMenuChoice);
arrows.sign = function(cmdSender) /*
{ turn a sign into a menu of arrow choices
*/
arrows.sign = function( cmdSender ) {
var sign = signs.getTargetedBy( cmdSender ); var sign = signs.getTargetedBy( cmdSender );
if ( !sign ) { if ( !sign ) {
throw new Error( 'You must first look at a sign!' ); throw new Error( 'You must first look at a sign!' );
@ -108,27 +75,33 @@ arrows.sign = function(cmdSender)
/* /*
event handler called when a projectile hits something event handler called when a projectile hits something
*/ */
var _onArrowHit = function(listener,event) var _onArrowHit = function( listener, event ) {
{ var projectile = event.entity,
var projectile = event.entity; world = projectile.world,
var world = projectile.world; shooter = projectile.shooter,
var shooter = projectile.shooter; fireworkCount = 5,
var fireworkCount = 5; arrowType,
if (projectile instanceof org.bukkit.entity.Arrow && TeleportCause = org.bukkit.event.player.PlayerTeleportEvent.TeleportCause,
shooter instanceof org.bukkit.entity.Player) launch = function( ) {
{ fireworks.firework( projectile.location );
var arrowType = arrows.store.players[shooter.name]; if ( --fireworkCount ) {
setTimeout( launch, 2000 );
}
};
if (projectile instanceof org.bukkit.entity.Arrow
&& shooter instanceof org.bukkit.entity.Player) {
arrowType = arrows.store.players[ shooter.name ];
switch ( arrowType ) { switch ( arrowType ) {
case 1: case 1:
projectile.remove(); projectile.remove();
world.createExplosion(projectile.location,arrows.explosiveYield); world.createExplosion( projectile.location, EXPLOSIVE_YIELD );
break; break;
case 2: case 2:
projectile.remove(); projectile.remove();
var teleportCause =org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; shooter.teleport( projectile.location, TeleportCause.PLUGIN );
shooter.teleport(projectile.location,
teleportCause.PLUGIN);
break; break;
case 3: case 3:
projectile.remove(); projectile.remove();
@ -140,11 +113,6 @@ var _onArrowHit = function(listener,event)
break; break;
case 5: case 5:
projectile.remove(); projectile.remove();
var launch = function(){
fireworks.firework(projectile.location);
if (--fireworkCount)
setTimeout(launch,2000);
};
launch(); launch();
break; break;
} }

View file

@ -1,11 +1,33 @@
/* /*
TODO: Document this module TODO: Document this module
*/ */
var _store = {players: {}}; var _store = { players: { } },
colorCodes = {},
i,
colors = [
'black',
'blue',
'darkgreen',
'darkaqua',
'darkred',
'purple',
'gold',
'gray',
'darkgray',
'indigo',
'brightgreen',
'aqua',
'red',
'pink',
'yellow',
'white'
],
foreach = require('utils').foreach;
/* /*
declare a new javascript plugin for changing chat text color declare a new javascript plugin for changing chat text color
*/ */
exports.chat = plugin("chat", { exports.chat = plugin( 'chat', {
/* /*
set the color of text for a given player set the color of text for a given player
*/ */
@ -17,37 +39,33 @@ exports.chat = plugin("chat", {
},true); },true);
var colors = [ foreach( colors, function ( color, i ) {
"black", "blue", "darkgreen", "darkaqua", "darkred", colorCodes[color] = i.toString( 16 );
"purple", "gold", "gray", "darkgray", "indigo", } );
"brightgreen", "aqua", "red", "pink", "yellow", "white"
];
var colorCodes = {};
for (var i =0;i < colors.length;i++) {
var hexCode = i.toString(16);
colorCodes[colors[i]] = hexCode;
}
events.on("player.AsyncPlayerChatEvent",function(l,e){ events.on( 'player.AsyncPlayerChatEvent', function( l, e ) {
var player = e.player; var player = e.player;
var playerChatColor = _store.players[ player.name ]; var playerChatColor = _store.players[ player.name ];
if ( playerChatColor ) { if ( playerChatColor ) {
e.message = "§" + colorCodes[playerChatColor] + e.message; e.message = '§' + colorCodes[ playerChatColor ] + e.message;
} }
}); });
var listColors = function( params, sender ) { var listColors = function( params, sender ) {
var colorNamesInColor = []; var colorNamesInColor = [];
for (var i = 0;i < colors.length;i++) foreach (colors, function( color ) {
colorNamesInColor[i] = "§"+colorCodes[colors[i]] + colors[i]; colorNamesInColor.push( '§' + colorCodes[color] + color );
sender.sendMessage("valid chat colors are " + colorNamesInColor.join(", ")); } );
sender.sendMessage( 'valid chat colors are ' + colorNamesInColor.join( ', ') );
}; };
command("list_colors", listColors);
command("chat_color",function(params,sender){ command( 'list_colors', listColors );
command( 'chat_color', function( params, sender ) {
var color = params[0]; var color = params[0];
if ( colorCodes[color] ) { if ( colorCodes[color] ) {
chat.setColor( sender, color ); chat.setColor( sender, color );
} else { } else {
sender.sendMessage(color + " is not a valid color"); sender.sendMessage( color + ' is not a valid color' );
listColors(); listColors();
} }
}, colors ); }, colors );

View file

@ -1,4 +1,4 @@
var utils = require('utils'); var foreach = require('utils').foreach;
/************************************************************************ /************************************************************************
## Classroom Plugin ## Classroom Plugin
@ -43,34 +43,36 @@ don't try to bar themselves and each other from scripting.
***/ ***/
var _store = { enableScripting: false }; var _store = { enableScripting: false };
var classroom = plugin("classroom", { var classroom = plugin('classroom', {
allowScripting: function (/* boolean: true or false */ canScript, sender ) { allowScripting: function (/* boolean: true or false */ canScript, sender ) {
if ( typeof sender == 'undefined' ) { if ( typeof sender == 'undefined' ) {
console.log("Attempt to set classroom scripting without credentials"); console.log( 'Attempt to set classroom scripting without credentials' );
console.log("classroom.allowScripting(boolean, sender)"); console.log( 'classroom.allowScripting(boolean, sender)' );
return; return;
} }
if ( !sender.op ) { if ( !sender.op ) {
console.log("Attempt to set classroom scripting without credentials: " + sender.name); console.log( 'Attempt to set classroom scripting without credentials: ' + sender.name );
return; return;
} }
/* /*
only operators should be allowed run this function only operators should be allowed run this function
*/ */
if (!sender.isOp()) if ( !sender.isOp() ) {
return; return;
}
if ( canScript ) { if ( canScript ) {
utils.foreach( server.onlinePlayers, function (player) { foreach( server.onlinePlayers, function( player ) {
player.addAttachment(__plugin, "scriptcraft.*", true); player.addAttachment( __plugin, 'scriptcraft.*', true );
}); });
} else { } else {
utils.foreach( server.onlinePlayers, function(player) { foreach( server.onlinePlayers, function( player ) {
utils.foreach(player.getEffectivePermissions(), function(perm) { foreach( player.getEffectivePermissions(), function( perm ) {
if ((""+perm.permission).indexOf("scriptcraft.") == 0){ if ( (''+perm.permission).indexOf( 'scriptcraft.' ) == 0 ) {
if (perm.attachment) if ( perm.attachment ) {
perm.attachment.remove(); perm.attachment.remove();
} }
}
}); });
}); });
} }
@ -84,7 +86,7 @@ exports.classroom = classroom;
events.on( 'player.PlayerLoginEvent', function( listener, event ) { events.on( 'player.PlayerLoginEvent', function( listener, event ) {
var player = event.player; var player = event.player;
if ( _store.enableScripting ) { if ( _store.enableScripting ) {
player.addAttachment(__plugin, "scriptcraft.*", true); player.addAttachment( __plugin, 'scriptcraft.*', true );
} }
}, 'HIGHEST'); }, 'HIGHEST');

View file

@ -1,21 +1,22 @@
/* /*
A test of the commando plugin. A test of the commando plugin.
Adds a new `/scriptcrafttimeofday` command with 4 possible options: Dawn, Midday, Dusk, Midnight Adds a new `/js-time` command with 4 possible options: Dawn, Midday, Dusk, Midnight
*/ */
var commando = require('./commando').commando; var commando = require('./commando').commando,
var times = { times = ['Dawn','Midday','Dusk','Midnight'];
Dawn: 0,
Midday: 6000,
Dusk: 12000,
Midnight: 18000
};
commando('scriptcrafttimeofday',function(params,sender){
if (config.verbose){
console.log('scriptcrafttimeofday.params=%s',JSON.stringify(params));
}
if (sender.location)
sender.location.world.setTime(times[params[0]]);
else
sender.sendMessage('This command only works in-world');
},['Dawn','Midday','Dusk','Midnight']); commando( 'js-time' , function( params, sender ) {
var time = ''+params[0].toLowerCase(),
i = 0;
if ( sender.location ) {
for ( ; i < 4; i++ ) {
if ( times.toLowerCase() == time ) {
sender.location.world.setTime( i * 6000 );
break;
}
}
} else {
sender.sendMessage('This command only works in-world');
}
},times);

View file

@ -87,25 +87,29 @@ exports.commando = function(name, func, options, intercepts){
events.on( 'player.PlayerCommandPreprocessEvent', function( l, e ) { events.on( 'player.PlayerCommandPreprocessEvent', function( l, e ) {
var msg = '' + e.message; var msg = '' + e.message;
var parts = msg.match( /^\/([^\s]+)/ ); var parts = msg.match( /^\/([^\s]+)/ );
if (!parts) if ( !parts ) {
return; return;
if (parts.length < 2) }
if ( parts.length < 2 ) {
return; return;
}
var command = parts[1]; var command = parts[1];
if ( commands[command] ) { if ( commands[command] ) {
e.message = "/jsp " + msg.replace(/^\//,""); e.message = '/jsp ' + msg.replace( /^\//, '' );
} }
} ); } );
events.on( 'server.ServerCommandEvent', function( l, e ) { events.on( 'server.ServerCommandEvent', function( l, e ) {
var msg = '' + e.command; var msg = '' + e.command;
var parts = msg.match( /^\/*([^\s]+)/ ); var parts = msg.match( /^\/*([^\s]+)/ );
if (!parts) if ( !parts ) {
return; return;
if (parts.length < 2) }
if ( parts.length < 2 ) {
return; return;
}
var command = parts[1]; var command = parts[1];
if ( commands[ command ] ) { if ( commands[ command ] ) {
var newCmd = "jsp " + msg.replace(/^\//,""); var newCmd = 'jsp ' + msg.replace( /^\//, '' );
if ( config.verbose ) { if ( config.verbose ) {
console.log( 'Redirecting to : %s', newCmd ); console.log( 'Redirecting to : %s', newCmd );
} }

View file

@ -307,14 +307,22 @@ var bitmaps = {
/* /*
wph 20130121 compute the width, and x,y coords of pixels ahead of time wph 20130121 compute the width, and x,y coords of pixels ahead of time
*/ */
for (var c in bitmaps.raw){ var c,
var bits = bitmaps.raw[c]; bits,
var width = bits.length/5; width,
var bmInfo = {"width": width,"pixels":[]} bmInfo,
j;
for ( c in bitmaps.raw ) {
bits = bitmaps.raw[c];
width = bits.length/5;
bmInfo = { width: width, pixels:[] };
bitmaps.computed[c] = bmInfo; bitmaps.computed[c] = bmInfo;
for (var j = 0; j < bits.length; j++){ for ( j = 0; j < bits.length; j++ ) {
if ( bits.charAt(j) != ' ' ) { if ( bits.charAt(j) != ' ' ) {
bmInfo.pixels.push([j%width,Math.ceil(j/width)]); bmInfo.pixels.push( [
j % width,
Math.ceil( j / width )
] );
} }
} }
} }
@ -330,39 +338,65 @@ for (var c in bitmaps.raw){
// //
Drone.extend('blocktype', function( message, fg, bg ) { Drone.extend('blocktype', function( message, fg, bg ) {
var bmfg,
bmbg,
lines,
lineCount,
h,
line,
i,
x,
y,
ch,
bits,
charWidth,
j;
this.chkpt('blocktext'); this.chkpt('blocktext');
if (typeof fg == "undefined") if ( typeof fg == 'undefined' ) {
fg = blocks.wool.black; fg = blocks.wool.black;
}
var bmfg = this._getBlockIdAndMeta(fg); bmfg = this._getBlockIdAndMeta( fg );
var bmbg = null; bmbg = null;
if (typeof bg != "undefined") if ( typeof bg != 'undefined' ) {
bmbg = this._getBlockIdAndMeta( bg ); bmbg = this._getBlockIdAndMeta( bg );
var lines = message.split("\n"); }
var lineCount = lines.length; lines = message.split( '\n' );
for (var h = 0;h < lineCount; h++) { lineCount = lines.length;
var line = lines[h];
line = line.toLowerCase().replace(/[^0-9a-z \.\-\+\/\;\'\:\!]/g,""); for ( h = 0; h < lineCount; h++) {
line = lines[h];
line = line.toLowerCase().replace( /[^0-9a-z \.\-\+\/\;\'\:\!]/g, '' );
this.up( 7 * ( lineCount - ( h + 1 ) ) ); this.up( 7 * ( lineCount - ( h + 1 ) ) );
for (var i =0;i < line.length; i++) { for ( i =0; i < line.length; i++) {
var ch = line.charAt(i)
var bits = bitmaps.computed[ch]; ch = line.charAt( i );
if (typeof bits == "undefined"){ bits = bitmaps.computed[ ch ];
if ( typeof bits == 'undefined' ) {
bits = bitmaps.computed[' ']; bits = bitmaps.computed[' '];
} }
var charWidth = bits.width; charWidth = bits.width;
if (typeof bg != "undefined")
if ( typeof bg != 'undefined' ) {
this.cuboidX( bmbg[0], bmbg[1], charWidth, 7, 1 ); this.cuboidX( bmbg[0], bmbg[1], charWidth, 7, 1 );
for (var j = 0;j < bits.pixels.length;j++){ }
for ( j = 0; j < bits.pixels.length; j++ ) {
this.chkpt( 'btbl' ); this.chkpt( 'btbl' );
var x = bits.pixels[j][0]; x = bits.pixels[ j ][ 0 ];
var y = bits.pixels[j][1]; y = bits.pixels[ j ][ 1] ;
this.up( 6 - y ).right( x ).cuboidX( bmfg[ 0 ], bmfg[ 1 ] ); this.up( 6 - y ).right( x ).cuboidX( bmfg[ 0 ], bmfg[ 1 ] );
this.move( 'btbl' ); this.move( 'btbl' );
} }
this.right( charWidth - 1 ); this.right( charWidth - 1 );
} }
this.move( 'blocktext' ); this.move( 'blocktext' );
} }

View file

@ -3,8 +3,7 @@ var Drone = require('../drone').Drone;
// //
// a castle is just a big wide fort with 4 taller forts at each corner // a castle is just a big wide fort with 4 taller forts at each corner
// //
Drone.extend('castle', function(side, height) Drone.extend('castle', function( side, height ) {
{
// //
// use sensible default parameter values // use sensible default parameter values
// if no parameters are supplied // if no parameters are supplied
@ -40,8 +39,7 @@ Drone.extend('castle', function(side, height)
// //
// now place 4 towers at each corner (each tower is another fort) // now place 4 towers at each corner (each tower is another fort)
// //
for (var corner = 0; corner < 4; corner++) for ( var corner = 0; corner < 4; corner++ ) {
{
// construct a 'tower' fort // construct a 'tower' fort
this.fort(towerSide,towerHeight); this.fort(towerSide,towerHeight);
// move forward the length of the castle then turn right // move forward the length of the castle then turn right

View file

@ -10,27 +10,29 @@ var blocks = require('blocks');
* width - width of the chessboard * width - width of the chessboard
* height - height of the chessboard * height - height of the chessboard
*/ */
Drone.extend("chessboard", function(whiteBlock, blackBlock, width, depth) { Drone.extend('chessboard', function( whiteBlock, blackBlock, width, depth ) {
this.chkpt('chessboard-start'); var i,
if (typeof whiteBlock == "undefined") j,
whiteBlock = blocks.wool.white; block;
if (typeof blackBlock == "undefined")
blackBlock = blocks.wool.black;
if (typeof width == "undefined")
width = 8;
if (typeof depth == "undefined")
depth = width;
for(var i = 0; i < width; ++i) { this.chkpt('chessboard-start');
for(var j = 0; j < depth; ++j) {
var block = blackBlock; if ( typeof whiteBlock == 'undefined' ) {
if((i+j)%2 == 1) { whiteBlock = blocks.wool.white;
block = whiteBlock;
} }
this.box(block); if ( typeof blackBlock == 'undefined' ) {
this.right(); blackBlock = blocks.wool.black;
} }
this.move('chessboard-start').fwd(i+1); if ( typeof width == 'undefined' ) {
width = 8;
}
if ( typeof depth == 'undefined' ) {
depth = width;
}
var wb = [ blackBlock, whiteBlock ];
for ( i = 0; i < depth; i++ ) {
this.boxa( wb, width, 1, 1).fwd();
wb = wb.reverse();
} }
return this.move('chessboard-start'); return this.move('chessboard-start');
}); });

View file

@ -11,8 +11,7 @@ var Drone = require('../drone').Drone;
// /js drone.cottage(); // /js drone.cottage();
// //
Drone.extend('cottage',function () Drone.extend('cottage',function ( ) {
{
this.chkpt('cottage') this.chkpt('cottage')
.box0(48,7,2,6) // 4 walls .box0(48,7,2,6) // 4 walls
.right(3).door() // door front and center .right(3).door() // door front and center
@ -22,7 +21,8 @@ Drone.extend('cottage',function ()
// //
// put up a sign near door. // put up a sign near door.
// //
this.down().right(4).sign(["Home","Sweet","Home"],68); this.down().right(4)
.sign(['Home','Sweet','Home'],68);
return this.move('cottage'); return this.move('cottage');
}); });
@ -30,9 +30,8 @@ Drone.extend('cottage',function ()
// a more complex script that builds an tree-lined avenue with // a more complex script that builds an tree-lined avenue with
// cottages on both sides. // cottages on both sides.
// //
Drone.extend('cottage_road', function(numberCottages) Drone.extend('cottage_road', function( numberCottages ) {
{ if (typeof numberCottages == 'undefined'){
if (typeof numberCottages == "undefined"){
numberCottages = 6; numberCottages = 6;
} }
var i=0, distanceBetweenTrees = 11; var i=0, distanceBetweenTrees = 11;
@ -41,10 +40,10 @@ Drone.extend('cottage_road', function(numberCottages)
// //
var cottagesPerSide = Math.floor(numberCottages/2); var cottagesPerSide = Math.floor(numberCottages/2);
this this
.chkpt("cottage_road") // make sure the drone's state is saved. .chkpt('cottage_road') // make sure the drone's state is saved.
.box(43,3,1,cottagesPerSide*(distanceBetweenTrees+1)) // build the road .box(43,3,1,cottagesPerSide*(distanceBetweenTrees+1)) // build the road
.up().right() // now centered in middle of road .up().right() // now centered in middle of road
.chkpt("cr"); // will be returning to this position later .chkpt('cr'); // will be returning to this position later
// //
// step 2 line the road with trees // step 2 line the road with trees
@ -56,7 +55,7 @@ Drone.extend('cottage_road', function(numberCottages)
.left(5) // return to middle of road .left(5) // return to middle of road
.fwd(distanceBetweenTrees+1); // move forward. .fwd(distanceBetweenTrees+1); // move forward.
} }
this.move("cr").back(6); // move back 1/2 the distance between trees this.move('cr').back(6); // move back 1/2 the distance between trees
// this function builds a path leading to a cottage. // this function builds a path leading to a cottage.
function pathAndCottage( d ) { function pathAndCottage( d ) {
@ -65,15 +64,14 @@ Drone.extend('cottage_road', function(numberCottages)
// //
// step 3 build cottages on each side // step 3 build cottages on each side
// //
for (i = 0;i < cottagesPerSide; i++) for ( i = 0; i < cottagesPerSide; i++ ) {
{ this.fwd(distanceBetweenTrees+1).chkpt('r'+i);
this.fwd(distanceBetweenTrees+1).chkpt("r"+i);
// build cottage on left // build cottage on left
pathAndCottage(this.turn(3)).move("r"+i); pathAndCottage( this.turn(3) ).move( 'r' + i );
// build cottage on right // build cottage on right
pathAndCottage(this.turn()).move("r"+i); pathAndCottage(this.turn()).move( 'r' + i );
} }
// return drone to where it was at start of function // return drone to where it was at start of function
return this.move("cottage_road"); return this.move('cottage_road');
}); });

View file

@ -3,17 +3,20 @@ var Drone = require('../drone').Drone;
// //
// constructs a medieval fort // constructs a medieval fort
// //
Drone.extend('fort', function(side, height) Drone.extend('fort', function( side, height ) {
{ if ( typeof side == 'undefined' ) {
if (typeof side == "undefined")
side = 18; side = 18;
if (typeof height == "undefined") }
if ( typeof height == 'undefined' ) {
height = 6; height = 6;
}
// make sure side is even // make sure side is even
if (side%2) if ( side % 2 ) {
side++; side++;
if (height < 4 || side < 10) }
throw new java.lang.RuntimeException("Forts must be at least 10 wide X 4 tall"); if ( height < 4 || side < 10 ) {
throw new java.lang.RuntimeException('Forts must be at least 10 wide X 4 tall');
}
var brick = 98; var brick = 98;
// //
// build walls. // build walls.
@ -33,7 +36,7 @@ Drone.extend('fort', function(side, height)
try { try {
this.boxa(turret,1,1,side-2).fwd(side-2).turn(); this.boxa(turret,1,1,side-2).fwd(side-2).turn();
} catch( e ) { } catch( e ) {
console.log("ERROR: " + e.toString()); console.log('ERROR: ' + e.toString());
} }
} }
// //
@ -42,9 +45,9 @@ Drone.extend('fort', function(side, height)
this.move('fort'); this.move('fort');
this.up(height-2).fwd().right().box('126:0',side-2,1,side-2); this.up(height-2).fwd().right().box('126:0',side-2,1,side-2);
var battlementWidth = 3; var battlementWidth = 3;
if (side <= 12) if ( side <= 12 ) {
battlementWidth = 2; battlementWidth = 2;
}
this.fwd(battlementWidth).right(battlementWidth) this.fwd(battlementWidth).right(battlementWidth)
.box(0,side-((1+battlementWidth)*2),1,side-((1+battlementWidth)*2)); .box(0,side-((1+battlementWidth)*2),1,side-((1+battlementWidth)*2));
// //

View file

@ -17,12 +17,12 @@ exports.LCDClock = function(drone, fgColor,bgColor,border) {
world = drone.world, world = drone.world,
intervalId = -1; intervalId = -1;
if (typeof bgColor == 'undefined') if ( typeof bgColor == 'undefined' ) {
bgColor = '35:15'; // black wool bgColor = '35:15'; // black wool
}
if (typeof fgColor == 'undefined') if ( typeof fgColor == 'undefined' ) {
fgColor = 35 ; // white wool fgColor = 35 ; // white wool
}
if ( border ) { if ( border ) {
drone.box(border,21,9,1); drone.box(border,21,9,1);
drone.up().right(); drone.up().right();

View file

@ -19,16 +19,21 @@ Creates a Rainbow.
***/ ***/
Drone.extend('rainbow', function(radius){ Drone.extend('rainbow', function(radius){
if (typeof radius == "undefined") var i,
colors,
bm;
if ( typeof radius == "undefined" ) {
radius = 18; radius = 18;
}
this.chkpt('rainbow'); this.chkpt('rainbow');
this.down(radius); this.down(radius);
// copy blocks.rainbow and add air at end (to compensate for strokewidth) // copy blocks.rainbow and add air at end (to compensate for strokewidth)
var colors = blocks.rainbow.slice(0); colors = blocks.rainbow.slice(0);
colors.push(blocks.air); colors.push(blocks.air);
for (var i = 0;i < colors.length; i++) { for ( i = 0; i < colors.length; i++ ) {
var bm = this._getBlockIdAndMeta(colors[i]); bm = this._getBlockIdAndMeta( colors[i] );
this.arc({ this.arc({
blockType: bm[0], blockType: bm[0],
meta: bm[1], meta: bm[1],

View file

@ -2,16 +2,16 @@ var Drone = require('../drone').Drone;
var blocks = require('blocks'); var blocks = require('blocks');
Drone.extend('skyscraper', function( floors ) { Drone.extend('skyscraper', function( floors ) {
var i = 0;
if (typeof floors == "undefined") if ( typeof floors == 'undefined' ) {
floors = 10; floors = 10;
}
this.chkpt('skyscraper'); this.chkpt('skyscraper');
for (var i = 0;i < floors; i++) for ( i = 0; i < floors; i++ ) {
{ this // w h d
this .box( blocks.iron, 20, 1, 20) // iron floor
.box(blocks.iron,20,1,20) .up() // w h d
.up() .box0(blocks.glass_pane, 20, 3, 20) // glass walls
.box0(blocks.glass_pane,20,3,20)
.up(3); .up(3);
} }
return this.move('skyscraper'); return this.move('skyscraper');

View file

@ -7,16 +7,16 @@ var Drone = require('../drone').Drone;
* dir - "up", "down", "left", "right", "fwd", "back * dir - "up", "down", "left", "right", "fwd", "back
* maxIterations - (Optional) maximum number of cubes to generate, defaults to 1000 * maxIterations - (Optional) maximum number of cubes to generate, defaults to 1000
*/ */
Drone.extend("streamer", function(block, dir, maxIterations) { Drone.extend('streamer', function(block, dir, maxIterations) {
if (typeof maxIterations == "undefined") if (typeof maxIterations == 'undefined')
maxIterations = 1000; maxIterations = 1000;
var usage = "Usage: streamer({block-type}, {direction: 'up', 'down', 'fwd', 'back', 'left', 'right'}, {maximum-iterations: default 1000})\nE.g.\n" + var usage = "Usage: streamer({block-type}, {direction: 'up', 'down', 'fwd', 'back', 'left', 'right'}, {maximum-iterations: default 1000})\nE.g.\n" +
"streamer(5, 'up', 200)"; "streamer(5, 'up', 200)";
if (typeof dir == "undefined"){ if (typeof dir == 'undefined'){
throw new Error(usage); throw new Error(usage);
} }
if (typeof block == "undefined") { if (typeof block == 'undefined') {
throw new Error(usage); throw new Error(usage);
} }
for ( var i = 0; i < maxIterations || 1000; ++i ) { for ( var i = 0; i < maxIterations || 1000; ++i ) {
@ -24,7 +24,7 @@ Drone.extend("streamer", function(block, dir, maxIterations) {
this[dir].call(this); this[dir].call(this);
var block = this.world.getBlockAt(this.x, this.y, this.z); var block = this.world.getBlockAt(this.x, this.y, this.z);
if ( block.typeId != 0 && block.data != 0) { if ( block.typeId != 0 && block.data != 0) {
break break;
} }
} }
return this; return this;

View file

@ -1,5 +1,9 @@
var utils = require('utils'); var utils = require('utils'),
var blocks = require('blocks'); blocks = require('blocks'),
Location = org.bukkit.Location,
Player = org.bukkit.entity.Player,
Sign = org.bukkit.block.Sign,
TreeType = org.bukkit.TreeType;
/********************************************************************* /*********************************************************************
## Drone Plugin ## Drone Plugin
@ -631,32 +635,39 @@ Used when placing torches so that they face towards the drone.
// //
var putBlock = function( x, y, z, blockId, metadata, world ) { var putBlock = function( x, y, z, blockId, metadata, world ) {
if (typeof metadata == "undefined") if ( typeof metadata == 'undefined' ) {
metadata = 0; metadata = 0;
}
var block = world.getBlockAt( x, y, z ); var block = world.getBlockAt( x, y, z );
if (block.typeId != blockId || block.data != metadata) if ( block.typeId != blockId || block.data != metadata ) {
block.setTypeIdAndData( blockId, metadata, false ); block.setTypeIdAndData( blockId, metadata, false );
}
}; };
var putSign = function( texts, x, y, z, blockId, meta, world ) { var putSign = function( texts, x, y, z, blockId, meta, world ) {
if (blockId != 63 && blockId != 68) var i,
throw new Error("Invalid Parameter: blockId must be 63 or 68"); block,
state;
if ( blockId != 63 && blockId != 68 ) {
throw new Error( 'Invalid Parameter: blockId must be 63 or 68' );
}
putBlock( x, y, z, blockId, meta, world ); putBlock( x, y, z, blockId, meta, world );
var block = world.getBlockAt(x,y,z); block = world.getBlockAt( x, y, z );
var state = block.state; state = block.state;
if (state instanceof org.bukkit.block.Sign){ if ( state instanceof Sign ) {
for (var i = 0;i < texts.length; i++) for ( i = 0; i < texts.length; i++ ) {
state.setLine( i % 4, texts[ i ] ); state.setLine( i % 4, texts[ i ] );
}
state.update( true ); state.update( true );
} }
}; };
Drone = function(x,y,z,dir,world) var Drone = function( x, y, z, dir, world ) {
{
this.record = false; this.record = false;
var usePlayerCoords = false; var usePlayerCoords = false;
var player = self; var player = self;
if (x instanceof org.bukkit.entity.Player){ if ( x instanceof Player ) {
player = x; player = x;
} }
var playerPos = utils.getPlayerPos( player ); var playerPos = utils.getPlayerPos( player );
@ -669,12 +680,12 @@ Drone = function(x,y,z,dir,world)
that.world = loc.world; that.world = loc.world;
}; };
var mp = utils.getMousePos( player ); var mp = utils.getMousePos( player );
if (typeof x == "undefined" || x instanceof org.bukkit.entity.Player) if ( typeof x == 'undefined' || x instanceof Player ) {
{
if ( mp ) { if ( mp ) {
populateFromLocation( mp ); populateFromLocation( mp );
if (playerPos) if ( playerPos ) {
this.dir = _getDirFromRotation(playerPos.yaw); this.dir = _getDirFromRotation(playerPos.yaw);
}
} else { } else {
// base it on the player's current location // base it on the player's current location
usePlayerCoords = true; usePlayerCoords = true;
@ -688,18 +699,18 @@ Drone = function(x,y,z,dir,world)
populateFromLocation( playerPos ); populateFromLocation( playerPos );
} }
} else { } else {
if (arguments[0] instanceof org.bukkit.Location){ if ( arguments[0] instanceof Location ) {
populateFromLocation( arguments[ 0 ] ); populateFromLocation( arguments[ 0 ] );
} else { } else {
this.x = x; this.x = x;
this.y = y; this.y = y;
this.z = z; this.z = z;
if (typeof dir == "undefined"){ if ( typeof dir == 'undefined' ) {
this.dir = _getDirFromRotation( playerPos.yaw ); this.dir = _getDirFromRotation( playerPos.yaw );
} else { } else {
this.dir = dir%4; this.dir = dir%4;
} }
if (typeof world == "undefined"){ if ( typeof world == 'undefined' ) {
this.world = playerPos.world; this.world = playerPos.world;
} else { } else {
this.world = world; this.world = world;
@ -727,12 +738,12 @@ exports.blocks = blocks;
// //
// add custom methods to the Drone object using this function // add custom methods to the Drone object using this function
// //
Drone.extend = function(name, func) Drone.extend = function( name, func ) {
{
Drone.prototype[ '_' + name ] = func; Drone.prototype[ '_' + name ] = func;
Drone.prototype[ name ] = function( ) { Drone.prototype[ name ] = function( ) {
if (this.record) if ( this.record ) {
this.history.push( [ name, arguments ] ); this.history.push( [ name, arguments ] );
}
var oldVal = this.record; var oldVal = this.record;
this.record = false; this.record = false;
this[ '_' + name ].apply( this, arguments ); this[ '_' + name ].apply( this, arguments );
@ -815,21 +826,22 @@ Another example: This statement creates a row of trees 2 by 3 ...
***/ ***/
Drone.prototype.times = function( numTimes, commands ) { Drone.prototype.times = function( numTimes, commands ) {
if (typeof numTimes == "undefined") if ( typeof numTimes == 'undefined' ) {
numTimes = 2; numTimes = 2;
if (typeof commands == "undefined") }
if ( typeof commands == 'undefined' ) {
commands = this.history.concat(); commands = this.history.concat();
}
this.history = [ [ 'times', [ numTimes + 1, commands ] ] ]; this.history = [ [ 'times', [ numTimes + 1, commands ] ] ];
var oldVal = this.record; var oldVal = this.record;
this.record = false; this.record = false;
for (var j = 1; j < numTimes; j++) for ( var j = 1; j < numTimes; j++ ) {
{
for ( var i = 0; i < commands.length; i++) { for ( var i = 0; i < commands.length; i++) {
var command = commands[i]; var command = commands[i];
var methodName = command[0]; var methodName = command[0];
var args = command[1]; var args = command[1];
print ("command=" + JSON.stringify(command) + ",methodName=" + methodName); print ('command=' + JSON.stringify(command ) + ',methodName=' + methodName );
this[ methodName ].apply( this, args ); this[ methodName ].apply( this, args );
} }
} }
@ -844,13 +856,13 @@ Drone.extend('chkpt',function(name){
} ); } );
Drone.extend( 'move', function( ) { Drone.extend( 'move', function( ) {
if (arguments[0] instanceof org.bukkit.Location){ if ( arguments[0] instanceof Location ) {
this.x = arguments[0].x; this.x = arguments[0].x;
this.y = arguments[0].y; this.y = arguments[0].y;
this.z = arguments[0].z; this.z = arguments[0].z;
this.dir = _getDirFromRotation(arguments[0].yaw ); this.dir = _getDirFromRotation(arguments[0].yaw );
this.world = arguments[0].world; this.world = arguments[0].world;
}else if (typeof arguments[0] === "string"){ } else if ( typeof arguments[0] === 'string' ) {
var coords = this._checkpoints[arguments[0]]; var coords = this._checkpoints[arguments[0]];
if ( coords ) { if ( coords ) {
this.x = coords.x; this.x = coords.x;
@ -867,67 +879,79 @@ Drone.extend('move', function() {
this.z = arguments[2]; this.z = arguments[2];
case 2: case 2:
this.y = arguments[1]; this.y = arguments[1];
case 1:n case 1:
this.x = arguments[0]; this.x = arguments[0];
} }
} }
} ); } );
Drone.extend( 'turn', function ( n ) { Drone.extend( 'turn', function ( n ) {
if (typeof n == "undefined") if ( typeof n == 'undefined' ) {
n = 1; n = 1;
}
this.dir += n; this.dir += n;
this.dir %=4; this.dir %=4;
} ); } );
Drone.extend( 'right', function( n ) { Drone.extend( 'right', function( n ) {
if (typeof n == "undefined") if ( typeof n == 'undefined' ) {
n = 1; n = 1;
}
_movements[ this.dir ].right( this, n ); _movements[ this.dir ].right( this, n );
}); });
Drone.extend( 'left', function( n ) { Drone.extend( 'left', function( n ) {
if (typeof n == "undefined") if ( typeof n == 'undefined') {
n = 1; n = 1;
}
_movements[ this.dir ].left( this, n ); _movements[ this.dir ].left( this, n );
}); });
Drone.extend( 'fwd', function( n ) { Drone.extend( 'fwd', function( n ) {
if (typeof n == "undefined") if ( typeof n == 'undefined' ) {
n = 1; n = 1;
}
_movements[ this.dir ].fwd( this, n ); _movements[ this.dir ].fwd( this, n );
}); });
Drone.extend( 'back', function( n ) { Drone.extend( 'back', function( n ) {
if (typeof n == "undefined") if ( typeof n == 'undefined' ) {
n = 1; n = 1;
}
_movements[ this.dir ].back( this, n ); _movements[ this.dir ].back( this, n );
}); });
Drone.extend( 'up', function( n ) { Drone.extend( 'up', function( n ) {
if (typeof n == "undefined") if ( typeof n == 'undefined' ) {
n = 1; n = 1;
}
this.y+= n; this.y+= n;
}); });
Drone.extend( 'down', function( n ) { Drone.extend( 'down', function( n ) {
if (typeof n == "undefined") if ( typeof n == 'undefined' ) {
n = 1; n = 1;
}
this.y-= n; this.y-= n;
}); });
// //
// position // position
// //
Drone.prototype.getLocation = function( ) { Drone.prototype.getLocation = function( ) {
return new org.bukkit.Location(this.world, this.x, this.y, this.z); return new Location( this.world, this.x, this.y, this.z );
}; };
// //
// building // building
// //
Drone.extend( 'sign', function( message, block ) { Drone.extend( 'sign', function( message, block ) {
if (message.constructor == Array){ if ( message.constructor != Array ) {
}else{
message = [message]; message = [message];
} }
var bm = this._getBlockIdAndMeta( block ); var bm = this._getBlockIdAndMeta( block );
block = bm[0]; block = bm[0];
var meta = bm[1]; var meta = bm[1];
if ( block != 63 && block != 68 ) { if ( block != 63 && block != 68 ) {
print("ERROR: Invalid block id for use in signs"); print('ERROR: Invalid block id for use in signs');
return; return;
} }
if ( block == 68 ) { if ( block == 68 ) {
@ -942,6 +966,7 @@ Drone.extend('sign',function(message,block){
this.fwd(); this.fwd();
} }
}); });
Drone.prototype.cuboida = function(/* Array */ blocks, w, h, d ) { Drone.prototype.cuboida = function(/* Array */ blocks, w, h, d ) {
var properBlocks = []; var properBlocks = [];
var len = blocks.length; var len = blocks.length;
@ -949,16 +974,17 @@ Drone.prototype.cuboida = function(/* Array */ blocks,w,h,d){
var bm = this._getBlockIdAndMeta( blocks[ i ] ); var bm = this._getBlockIdAndMeta( blocks[ i ] );
properBlocks.push( [ bm[0], bm[1] ] ); properBlocks.push( [ bm[0], bm[1] ] );
} }
if (typeof h == "undefined") if ( typeof h == 'undefined' ) {
h = 1; h = 1;
if (typeof d == "undefined") }
if ( typeof d == 'undefined' ) {
d = 1; d = 1;
if (typeof w == "undefined") }
if ( typeof w == 'undefined' ) {
w = 1; w = 1;
}
var that = this; var that = this;
var dir = this.dir; var dir = this.dir;
var pl = org.bukkit.entity.Player;
var cs = org.bukkit.command.BlockCommandSender;
var bi = 0; var bi = 0;
/* /*
@ -982,12 +1008,15 @@ Drone.prototype.cuboida = function(/* Array */ blocks,w,h,d){
*/ */
Drone.prototype.cuboidX = function( blockType, meta, w, h, d ) { Drone.prototype.cuboidX = function( blockType, meta, w, h, d ) {
if (typeof h == "undefined") if ( typeof h == 'undefined' ) {
h = 1; h = 1;
if (typeof d == "undefined") }
if ( typeof d == 'undefined' ) {
d = 1; d = 1;
if (typeof w == "undefined") }
if ( typeof w == 'undefined' ) {
w = 1; w = 1;
}
var that = this; var that = this;
var dir = this.dir; var dir = this.dir;
@ -1005,7 +1034,6 @@ Drone.prototype.cuboidX = function(blockType, meta, w, h, d){
var widthFunc = function( ) { var widthFunc = function( ) {
_traverseHeight( that, h, heightFunc ); _traverseHeight( that, h, heightFunc );
}; };
_traverse[dir].width( that, w, widthFunc ); _traverse[dir].width( that, w, widthFunc );
return this; return this;
@ -1015,6 +1043,7 @@ Drone.prototype.cuboid = function(block,w,h,d){
var bm = this._getBlockIdAndMeta( block ); var bm = this._getBlockIdAndMeta( block );
return this.cuboidX( bm[0], bm[1], w, h, d ); return this.cuboidX( bm[0], bm[1], w, h, d );
}; };
Drone.prototype.cuboid0 = function( block, w, h, d ) { Drone.prototype.cuboid0 = function( block, w, h, d ) {
this.chkpt( 'start_point' ); this.chkpt( 'start_point' );
@ -1029,16 +1058,21 @@ Drone.prototype.cuboid0 = function(block,w,h,d){
return this.move( 'start_point' ); return this.move( 'start_point' );
}; };
Drone.extend( 'door', function( door ) { Drone.extend( 'door', function( door ) {
if (typeof door == "undefined"){ if ( typeof door == 'undefined' ) {
door = 64; door = 64;
} else { } else {
door = 71; door = 71;
} }
this.cuboid(door+':' + this.dir).up().cuboid(door+':8').down(); this.cuboid( door+':' + this.dir )
.up( )
.cuboid( door+':8' )
.down( );
} ); } );
Drone.extend( 'door2' , function( door ) { Drone.extend( 'door2' , function( door ) {
if (typeof door == "undefined"){ if ( typeof door == 'undefined' ) {
door = 64; door = 64;
} else { } else {
door = 71; door = 71;
@ -1057,7 +1091,8 @@ Drone.PLAYER_STAIRS_FACING = [0,2,1,3];
Drone.PLAYER_SIGN_FACING = [ 4, 2, 5, 3 ]; Drone.PLAYER_SIGN_FACING = [ 4, 2, 5, 3 ];
Drone.PLAYER_TORCH_FACING = [ 2, 4, 1, 3 ]; Drone.PLAYER_TORCH_FACING = [ 2, 4, 1, 3 ];
var _STAIRBLOCKS = {53: '5:0' // oak wood var _STAIRBLOCKS = {
53: '5:0' // oak wood
,67: 4 // cobblestone ,67: 4 // cobblestone
,108: 45 // brick ,108: 45 // brick
,109: 98 // stone brick ,109: 98 // stone brick
@ -1077,8 +1112,7 @@ var _prism = function(block,w,d) {
var d2 = 0; var d2 = 0;
var middle = Math.floor( d/2 ); var middle = Math.floor( d/2 );
var uc = 0,dc = 0; var uc = 0,dc = 0;
while (d2 < d) while ( d2 < d ) {
{
var di = (d2 < middle?this.dir:(this.dir+2 )%4 ); var di = (d2 < middle?this.dir:(this.dir+2 )%4 );
var bd = block + ':' + Drone.PLAYER_STAIRS_FACING[di]; var bd = block + ':' + Drone.PLAYER_STAIRS_FACING[di];
var putStep = true; var putStep = true;
@ -1087,8 +1121,9 @@ var _prism = function(block,w,d) {
putStep = false; putStep = false;
} }
} }
if (putStep) if ( putStep ) {
this.cuboid(bd,w ); this.cuboid(bd,w );
}
if ( d2 < middle-1 ) { if ( d2 < middle-1 ) {
this.up( ); this.up( );
uc++; uc++;
@ -1146,8 +1181,8 @@ Drone.extend('boxa',Drone.prototype.cuboida);
// show the Drone's position and direction // show the Drone's position and direction
// //
Drone.prototype.toString = function( ) { Drone.prototype.toString = function( ) {
var dirs = ["east","south","west","north"]; var dirs = ['east','south','west','north'];
return "x: " + this.x + " y: "+this.y + " z: " + this.z + " dir: " + this.dir + " "+dirs[this.dir]; return 'x: ' + this.x + ' y: '+this.y + ' z: ' + this.z + ' dir: ' + this.dir + ' '+dirs[this.dir];
}; };
Drone.prototype.debug = function( ) { Drone.prototype.debug = function( ) {
print(this.toString( ) ); print(this.toString( ) );
@ -1183,13 +1218,8 @@ var _bresenham = function(x0,y0,radius, setPixel, quadrants){
if ( quadrants.topleft || quadrants.bottomleft ) if ( quadrants.topleft || quadrants.bottomleft )
setPixel(x0 - radius, y0 ); // quadrant II/III leftmost setPixel(x0 - radius, y0 ); // quadrant II/III leftmost
while(x < y) while ( x < y ) {
{ if(f >= 0 ) {
// ddF_x == 2 * x + 1;
// ddF_y == -2 * y;
// f == x*x + y*y - radius*radius + 2*x - y + 1;
if(f >= 0)
{
y--; y--;
ddF_y += 2; ddF_y += 2;
f += ddF_y; f += ddF_y;
@ -1236,7 +1266,7 @@ var _getStrokeDir = function(x,y){
var _arc2 = function( params ) { var _arc2 = function( params ) {
var drone = params.drone; var drone = params.drone;
var orientation = params.orientation?params.orientation:"horizontal"; var orientation = params.orientation?params.orientation:'horizontal';
var quadrants = params.quadrants?params.quadrants:{ var quadrants = params.quadrants?params.quadrants:{
topright:1, topright:1,
topleft:2, topleft:2,
@ -1249,7 +1279,7 @@ var _arc2 = function( params ) {
drone.chkpt('arc2' ); drone.chkpt('arc2' );
var x0, y0, gotoxy,setPixel; var x0, y0, gotoxy,setPixel;
if (orientation == "horizontal"){ if ( orientation == 'horizontal' ) {
gotoxy = function( x,y ) { return drone.right(x ).fwd(y );}; gotoxy = function( x,y ) { return drone.right(x ).fwd(y );};
drone.right(radius ).fwd(radius ).chkpt('center' ); drone.right(radius ).fwd(radius ).chkpt('center' );
switch ( drone.dir ) { switch ( drone.dir ) {
@ -1438,8 +1468,7 @@ var _paste = function(name)
// //
// need to adjust blocks which face a direction // need to adjust blocks which face a direction
// //
switch (cb) switch ( cb ) {
{
// //
// doors // doors
// //
@ -1684,20 +1713,19 @@ Drone.extend('rand',function(dist,w,h,d){
this.boxa(randomized,w,h,d ); this.boxa(randomized,w,h,d );
} ); } );
var _trees = { var _trees = {
oak: org.bukkit.TreeType.BIG_TREE , oak: TreeType.BIG_TREE ,
birch: org.bukkit.TreeType.BIRCH , birch: TreeType.BIRCH ,
jungle: org.bukkit.TreeType.JUNGLE, jungle: TreeType.JUNGLE,
spruce: org.bukkit.TreeType.REDWOOD spruce: TreeType.REDWOOD
}; };
for (var p in _trees) for ( var p in _trees ) {
{
Drone.extend(p, function( v ) { Drone.extend(p, function( v ) {
return function( ) { return function( ) {
var block = this.world.getBlockAt(this.x,this.y,this.z ); var block = this.world.getBlockAt(this.x,this.y,this.z );
if ( block.typeId == 2 ) { if ( block.typeId == 2 ) {
this.up( ); this.up( );
} }
var treeLoc = new org.bukkit.Location(this.world,this.x,this.y,this.z); var treeLoc = new Location(this.world,this.x,this.y,this.z );
var successful = treeLoc.world.generateTree(treeLoc,v ); var successful = treeLoc.world.generateTree(treeLoc,v );
if ( block.typeId == 2 ) { if ( block.typeId == 2 ) {
this.down( ); this.down( );

View file

@ -22,20 +22,27 @@ Spheres are time-consuming to make. You *can* make large spheres (250 radius) bu
server to be very busy for a couple of minutes while doing so. server to be very busy for a couple of minutes while doing so.
***/ ***/
Drone.extend('sphere', function(block,radius) Drone.extend( 'sphere', function( block, radius ) {
{ var lastRadius = radius,
var lastRadius = radius; slices = [ [ radius , 0 ] ],
var slices = [[radius,0]]; diameter = radius * 2,
var diameter = radius*2; bm = this._getBlockIdAndMeta( block ),
var bm = this._getBlockIdAndMeta(block); r2 = radius * radius,
i = 0,
newRadius,
yOffset,
sr,
sh,
v,
h;
var r2 = radius*radius; for ( i = 0; i <= radius; i++ ) {
for (var i = 0; i <= radius;i++){ newRadius = Math.round( Math.sqrt( r2 - i * i ) );
var newRadius = Math.round(Math.sqrt(r2 - i*i)); if ( newRadius == lastRadius ) {
if (newRadius == lastRadius)
slices[ slices.length - 1 ][ 1 ]++; slices[ slices.length - 1 ][ 1 ]++;
else } else {
slices.push( [ newRadius , 1 ] ); slices.push( [ newRadius , 1 ] );
}
lastRadius = newRadius; lastRadius = newRadius;
} }
this.chkpt( 'sphere' ); this.chkpt( 'sphere' );
@ -46,23 +53,31 @@ Drone.extend('sphere', function(block,radius)
.cylinder( block, radius, ( slices[0][1]*2 ) - 1, { blockType: bm[0], meta: bm[1] } ) .cylinder( block, radius, ( slices[0][1]*2 ) - 1, { blockType: bm[0], meta: bm[1] } )
.down( radius - slices[0][1] ); .down( radius - slices[0][1] );
var yOffset = -1; yOffset = -1;
for (var i = 1; i < slices.length;i++) for ( i = 1; i < slices.length; i++ ) {
{
yOffset += slices[i-1][1]; yOffset += slices[i-1][1];
var sr = slices[i][0]; sr = slices[i][0];
var sh = slices[i][1]; sh = slices[i][1];
var v = radius + yOffset, h = radius-sr; v = radius + yOffset;
h = radius - sr;
// northern hemisphere // northern hemisphere
this.up(v).fwd(h).right(h) this.up( v )
.fwd( h )
.right( h )
.cylinder( block, sr, sh, { blockType: bm[0], meta: bm[1] } ) .cylinder( block, sr, sh, { blockType: bm[0], meta: bm[1] } )
.left(h).back(h).down(v); .left( h )
.back( h )
.down( v );
// southern hemisphere // southern hemisphere
v = radius - ( yOffset + sh + 1 ); v = radius - ( yOffset + sh + 1 );
this.up(v).fwd(h).right(h) this.up( v )
.fwd( h )
.right( h )
.cylinder( block, sr, sh, { blockType: bm[0], meta: bm[1] } ) .cylinder( block, sr, sh, { blockType: bm[0], meta: bm[1] } )
.left(h).back(h). down(v); .left( h )
.back( h )
.down( v );
} }
return this.move( 'sphere' ); return this.move( 'sphere' );
}); });
@ -88,33 +103,33 @@ server to be very busy for a couple of minutes while doing so.
***/ ***/
Drone.extend('sphere0', function(block,radius) Drone.extend('sphere0', function(block,radius)
{ {
/* var lastRadius = radius,
this.sphere(block,radius) slices = [ [ radius, 0 ] ],
.fwd().right().up() diameter = radius * 2,
.sphere(0,radius-1) bm = this._getBlockIdAndMeta( block ),
.back().left().down(); r2 = radius*radius,
i,
newRadius,
sr,
sh,
v,
h,
len,
yOffset;
*/ for ( i = 0; i <= radius; i++ ) {
newRadius = Math.round( Math.sqrt( r2 - i * i ) );
var lastRadius = radius; if ( newRadius == lastRadius ) {
var slices = [[radius,0]];
var diameter = radius*2;
var bm = this._getBlockIdAndMeta(block);
var r2 = radius*radius;
for (var i = 0; i <= radius;i++){
var newRadius = Math.round(Math.sqrt(r2 - i*i));
if (newRadius == lastRadius)
slices[ slices.length - 1 ][ 1 ]++; slices[ slices.length - 1 ][ 1 ]++;
else } else {
slices.push( [ newRadius, 1 ] ); slices.push( [ newRadius, 1 ] );
}
lastRadius = newRadius; lastRadius = newRadius;
} }
this.chkpt( 'sphere0' ); this.chkpt( 'sphere0' );
// //
// mid section // mid section
// //
//.cylinder(block,radius,(slices[0][1]*2)-1,{blockType: bm[0],meta: bm[1]})
this.up( radius - slices[0][1] ) this.up( radius - slices[0][1] )
.arc({ blockType: bm[0], .arc({ blockType: bm[0],
meta: bm[1], meta: bm[1],
@ -125,14 +140,14 @@ Drone.extend('sphere0', function(block,radius)
}) })
.down( radius - slices[0][1] ); .down( radius - slices[0][1] );
var yOffset = -1; yOffset = -1;
var len = slices.length; len = slices.length;
for (var i = 1; i < len;i++) for ( i = 1; i < len; i++ ) {
{
yOffset += slices[i-1][1]; yOffset += slices[i-1][1];
var sr = slices[i][0]; sr = slices[i][0];
var sh = slices[i][1]; sh = slices[i][1];
var v = radius + yOffset, h = radius-sr; v = radius + yOffset;
h = radius-sr;
// northern hemisphere // northern hemisphere
// .cylinder(block,sr,sh,{blockType: bm[0],meta: bm[1]}) // .cylinder(block,sr,sh,{blockType: bm[0],meta: bm[1]})
this.up( v ).fwd( h ).right( h ) this.up( v ).fwd( h ).right( h )
@ -148,7 +163,6 @@ Drone.extend('sphere0', function(block,radius)
// southern hemisphere // southern hemisphere
v = radius - ( yOffset + sh + 1 ); v = radius - ( yOffset + sh + 1 );
//.cylinder(block,sr,sh,{blockType: bm[0],meta: bm[1]})
this.up( v ).fwd( h ).right( h ) this.up( v ).fwd( h ).right( h )
.arc({ .arc({
blockType: bm[0], blockType: bm[0],
@ -186,25 +200,27 @@ To create a wood 'north' hemisphere with a radius of 7 blocks...
***/ ***/
Drone.extend( 'hemisphere', function( block, radius, northSouth ) { Drone.extend( 'hemisphere', function( block, radius, northSouth ) {
var lastRadius = radius; var lastRadius = radius,
var slices = [[radius,0]]; slices = [ [ radius, 0 ] ],
var diameter = radius*2; diameter = radius * 2,
var bm = this._getBlockIdAndMeta(block); bm = this._getBlockIdAndMeta(block),
r2 = radius * radius,
var r2 = radius*radius; i = 0,
for (var i = 0; i <= radius;i++){ newRadius;
var newRadius = Math.round(Math.sqrt(r2 - i*i)); for ( i = 0; i <= radius; i++ ) {
if (newRadius == lastRadius) newRadius = Math.round( Math.sqrt( r2 - i * i ) );
if ( newRadius == lastRadius ) {
slices[ slices.length - 1 ][ 1 ]++; slices[ slices.length - 1 ][ 1 ]++;
else } else {
slices.push( [ newRadius, 1 ] ); slices.push( [ newRadius, 1 ] );
}
lastRadius = newRadius; lastRadius = newRadius;
} }
this.chkpt( 'hsphere' ); this.chkpt( 'hsphere' );
// //
// mid section // mid section
// //
if (northSouth == "north"){ if ( northSouth == 'north' ) {
this.cylinder( block, radius, slices[0][1], { blockType: bm[0], meta: bm[1] } ); this.cylinder( block, radius, slices[0][1], { blockType: bm[0], meta: bm[1] } );
} else { } else {
this.up( radius - slices[0][1] ) this.up( radius - slices[0][1] )
@ -213,13 +229,12 @@ Drone.extend('hemisphere', function(block,radius, northSouth){
} }
var yOffset = -1; var yOffset = -1;
for (var i = 1; i < slices.length;i++) for ( i = 1; i < slices.length; i++ ) {
{
yOffset += slices[i-1][1]; yOffset += slices[i-1][1];
var sr = slices[i][0]; var sr = slices[i][0];
var sh = slices[i][1]; var sh = slices[i][1];
var v = yOffset, h = radius-sr; var v = yOffset, h = radius-sr;
if (northSouth == "north") { if ( northSouth == 'north' ) {
// northern hemisphere // northern hemisphere
this.up( v ).fwd( h ).right( h ) this.up( v ).fwd( h ).right( h )
.cylinder( block, sr, sh, { blockType: bm[0], meta: bm[1] } ) .cylinder( block, sr, sh, { blockType: bm[0], meta: bm[1] } )
@ -233,7 +248,6 @@ Drone.extend('hemisphere', function(block,radius, northSouth){
} }
} }
return this.move( 'hsphere' ); return this.move( 'hsphere' );
}); });
/************************************************************************ /************************************************************************
### Drone.hemisphere0() method ### Drone.hemisphere0() method
@ -257,7 +271,7 @@ To create a glass 'north' hemisphere with a radius of 20 blocks...
***/ ***/
Drone.extend( 'hemisphere0', function( block, radius, northSouth ) { Drone.extend( 'hemisphere0', function( block, radius, northSouth ) {
return this.hemisphere( block, radius, northSouth) return this.hemisphere( block, radius, northSouth)
.fwd().right().up(northSouth=="north"?0:1) .fwd().right().up( northSouth == 'north' ? 0 : 1 )
.hemisphere( 0, radius-1, northSouth ) .hemisphere( 0, radius-1, northSouth )
.back().left().down(northSouth=="north"?0:1); .back().left().down( northSouth == 'north' ? 0 : 1 );
}); });

View file

@ -35,10 +35,11 @@ Source Code ...
command( 'hello-byname', function( parameters, sender ) { command( 'hello-byname', function( parameters, sender ) {
var playerName = parameters[0]; var playerName = parameters[0];
var recipient = utils.player( playerName ); var recipient = utils.player( playerName );
if (recipient) if ( recipient ) {
greetings.hello( recipient ); greetings.hello( recipient );
else } else {
sender.sendMessage( 'Player ' + playerName + ' not found.' ); sender.sendMessage( 'Player ' + playerName + ' not found.' );
}
}); });
***/ ***/
@ -49,8 +50,9 @@ var greetings = require('./example-1-hello-module');
command( 'hello-byname', function( parameters, sender ) { command( 'hello-byname', function( parameters, sender ) {
var playerName = parameters[0]; var playerName = parameters[0];
var recipient = utils.player( playerName ); var recipient = utils.player( playerName );
if (recipient) if ( recipient ) {
greetings.hello( recipient ); greetings.hello( recipient );
else } else {
sender.sendMessage( 'Player ' + playerName + ' not found.' ); sender.sendMessage( 'Player ' + playerName + ' not found.' );
}
}); });

View file

@ -59,34 +59,36 @@ The following administration options can only be used by server operators...
blocks are destroyed by this command. blocks are destroyed by this command.
***/ ***/
var utils = require('utils'); var utils = require('utils'),
var _store = { TeleportCause = org.bukkit.event.player.PlayerTeleportEvent.TeleportCause,
_store = {
houses: { }, houses: { },
openHouses: { }, openHouses: { },
invites: { } invites: { }
}; };
/* /*
*/ */
var homes = plugin("homes", { var homes = plugin( 'homes', {
help: function( ) { help: function( ) {
return [ return [
/* basic functions */ /* basic functions */
"/jsp home : Return to your own home", '/jsp home : Return to your own home',
"/jsp home <player> : Go to player's home", '/jsp home <player> : Go to player home',
"/jsp home set : Set your current location as home", '/jsp home set : Set your current location as home',
"/jsp home delete : Delete your home location", '/jsp home delete : Delete your home location',
/* social */ /* social */
"/jsp home list : List homes you can visit", '/jsp home list : List homes you can visit',
"/jsp home ilist : List players who can visit your home", '/jsp home ilist : List players who can visit your home',
"/jsp home invite <player> : Invite <player> to your home", '/jsp home invite <player> : Invite <player> to your home',
"/jsp home uninvite <player> : Uninvite <player> to your home", '/jsp home uninvite <player> : Uninvite <player> to your home',
"/jsp home public : Open your home to all players", '/jsp home public : Open your home to all players',
"/jsp home private : Make your home private", '/jsp home private : Make your home private',
/* administration */ /* administration */
"/jsp home listall : Show all houses (ops only)", '/jsp home listall : Show all houses (ops only)',
"/jsp home clear <player> : Clears player's home location (ops only)" '/jsp home clear <player> : Clears player home location (ops only)'
]; ];
}, },
/* ======================================================================== /* ========================================================================
@ -94,43 +96,54 @@ var homes = plugin("homes", {
======================================================================== */ ======================================================================== */
go: function( guest, host ) { go: function( guest, host ) {
if (typeof host == "undefined") var loc,
homeLoc;
if ( typeof host == 'undefined' ) {
host = guest; host = guest;
}
guest = utils.player( guest ); guest = utils.player( guest );
host = utils.player( host ); host = utils.player( host );
var loc = _store.houses[host.name]; loc = _store.houses[ host.name ];
if ( !loc ) { if ( !loc ) {
guest.sendMessage(host.name + " has no home"); guest.sendMessage( host.name + ' has no home' );
return; return;
} }
if ( !this._canVisit( guest, host ) ) { if ( !this._canVisit( guest, host ) ) {
guest.sendMessage("You can't visit " + host.name + "'s home yet"); guest.sendMessage( 'You can not visit ' + host.name + "'s home yet" );
return; return;
} }
var teleportCause = org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; homeLoc = utils.locationFromJSON( loc );
var homeLoc = utils.locationFromJSON(loc); guest.teleport(homeLoc, TeleportCause.PLUGIN);
guest.teleport(homeLoc, teleportCause.PLUGIN);
}, },
/* /*
determine whether a guest is allow visit a host's home determine whether a guest is allow visit a host's home
*/ */
_canVisit: function( guest, host ) { _canVisit: function( guest, host ) {
if (guest == host) var invitations,
i;
if ( guest == host ) {
return true; return true;
if (_store.openHouses[host.name]) }
if ( _store.openHouses[ host.name ] ) {
return true; return true;
var invitations = _store.invites[host.name]; }
if (invitations) invitations = _store.invites[ host.name ];
for (var i = 0;i < invitations.length;i++) if ( invitations ) {
if (invitations[i] == guest.name) for ( i = 0; i < invitations.length; i++ ) {
if ( invitations[i] == guest.name ) {
return true; return true;
}
}
}
return false; return false;
}, },
set: function( player ) { set: function( player ) {
player = utils.player( player ); player = utils.player( player );
var loc = player.location; var loc = player.location;
_store.houses[player.name] = utils.locationToJSON( loc ); _store.houses[player.name] = utils.locationToJSON( loc );
}, },
remove: function( player ) { remove: function( player ) {
player = utils.player( player ); player = utils.player( player );
delete _store.houses[ player.name ]; delete _store.houses[ player.name ];
@ -143,36 +156,48 @@ var homes = plugin("homes", {
list homes which the player can visit list homes which the player can visit
*/ */
list: function( player ) { list: function( player ) {
var result = []; var result = [],
for (var ohp in _store.openHouses) ohp,
host,
guests,
i;
for ( ohp in _store.openHouses ) {
result.push(ohp); result.push(ohp);
}
player = utils.player(player); player = utils.player(player);
for (var host in _store.invites){ for ( host in _store.invites ) {
var guests = _store.invites[host]; guests = _store.invites[host];
for (var i = 0;i < guests.length; i++) for ( i = 0; i < guests.length; i++ ) {
if (guests[i] == player.name) if ( guests[i] == player.name ) {
result.push(host); result.push(host);
} }
}
}
return result; return result;
}, },
/* /*
list who can visit the player's home list who can visit the player home
*/ */
ilist: function( player ) { ilist: function( player ) {
var result = [],
onlinePlayers,
i;
player = utils.player( player ); player = utils.player( player );
var result = [];
// if home is public - all players // if home is public - all players
if ( _store.openHouses[player.name] ) { if ( _store.openHouses[player.name] ) {
var online = org.bukkit.Bukkit.getOnlinePlayers(); onlinePlayers = org.bukkit.Bukkit.getOnlinePlayers();
for (var i = 0;i < online.length; i++) for ( i = 0; i < onlinePlayers.length; i++ ) {
if (online[i].name != player.name) if ( onlinePlayers[i].name != player.name) {
result.push(online[i].name); result.push( onlinePlayers[i].name );
}
}
} else { } else {
if (_store.invites[player.name]) if ( _store.invites[player.name] ) {
result = _store.invites[ player.name ]; result = _store.invites[ player.name ];
else } else {
result = []; result = [];
} }
}
return result; return result;
}, },
/* /*
@ -182,39 +207,48 @@ var homes = plugin("homes", {
host = utils.player( host ); host = utils.player( host );
guest = utils.player( guest ); guest = utils.player( guest );
var invitations = []; var invitations = [];
if (_store.invites[host.name]) if ( _store.invites[host.name] ) {
invitations = _store.invites[host.name]; invitations = _store.invites[host.name];
}
invitations.push( guest.name ); invitations.push( guest.name );
_store.invites[host.name] = invitations; _store.invites[host.name] = invitations;
guest.sendMessage(host.name + " has invited you to their home."); guest.sendMessage( host.name + ' has invited you to their home.' );
guest.sendMessage("type '/jsp home " + host.name + "' to accept"); guest.sendMessage( 'type "/jsp home ' + host.name + '" to accept' );
}, },
/* /*
Uninvite someone to the home Uninvite someone to the home
*/ */
uninvite: function( host, guest ) { uninvite: function( host, guest ) {
var invitations,
revisedInvites,
i;
host = utils.player( host ); host = utils.player( host );
guest = utils.player( guest ); guest = utils.player( guest );
var invitations = _store.invites[host.name]; invitations = _store.invites[ host.name ];
if (!invitations) if ( !invitations ) {
return; return;
var revisedInvites = []; }
for (var i =0;i < invitations.length; i++) revisedInvites = [];
if (invitations[i] != guest.name) for ( i = 0; i < invitations.length; i++ ) {
if ( invitations[i] != guest.name ) {
revisedInvites.push( invitations[i] ); revisedInvites.push( invitations[i] );
}
}
_store.invites[host.name] = revisedInvites; _store.invites[host.name] = revisedInvites;
}, },
/* /*
make the player's house public make the player house public
*/ */
open: function( player, optionalMsg ) { open: function( player, optionalMsg ) {
player = utils.player( player ); player = utils.player( player );
_store.openHouses[ player.name ] = true; _store.openHouses[ player.name ] = true;
if (typeof optionalMsg != "undefined") if ( typeof optionalMsg != 'undefined' ) {
__plugin.server.broadcastMessage( optionalMsg ); __plugin.server.broadcastMessage( optionalMsg );
}
}, },
/* /*
make the player's house private make the player house private
*/ */
close: function( player ) { close: function( player ) {
player = utils.player( player ); player = utils.player( player );
@ -225,10 +259,12 @@ var homes = plugin("homes", {
======================================================================== */ ======================================================================== */
listall: function( ) { listall: function( ) {
var result = []; var result = [];
for (var home in _store.houses) for ( var home in _store.houses ) {
result.push(home); result.push(home);
}
return result; return result;
}, },
clear: function( player ) { clear: function( player ) {
player = utils.player( player ); player = utils.player( player );
delete _store.houses[ player.name ]; delete _store.houses[ player.name ];
@ -243,96 +279,124 @@ exports.homes = homes;
define a set of command options that can be used by players define a set of command options that can be used by players
*/ */
var options = { var options = {
'set': function(params, sender){ homes.set(sender); },
'delete': function(params, sender ){ homes.remove(sender);}, 'set': function( params, sender ) {
'help': function(params, sender){ sender.sendMessage(homes.help());}, homes.set( sender );
},
'delete': function( params, sender ) {
homes.remove( sender );
},
'help': function( params, sender ) {
sender.sendMessage( homes.help() );
},
'list': function( params, sender ) { 'list': function( params, sender ) {
var visitable = homes.list(); var visitable = homes.list();
if ( visitable.length == 0 ) { if ( visitable.length == 0 ) {
sender.sendMessage("There are no homes to visit"); sender.sendMessage( 'There are no homes to visit' );
return; return;
} else { } else {
sender.sendMessage([ sender.sendMessage([
"You can visit any of these " + visitable.length + " homes" 'You can visit any of these ' + visitable.length + ' homes'
,visitable.join(", ") ,visitable.join(', ')
]); ]);
} }
}, },
'ilist': function( params, sender ) { 'ilist': function( params, sender ) {
var potentialVisitors = homes.ilist(); var potentialVisitors = homes.ilist();
if (potentialVisitors.length == 0) if ( potentialVisitors.length == 0 ) {
sender.sendMessage("No one can visit your home"); sender.sendMessage('No one can visit your home');
else } else {
sender.sendMessage([ sender.sendMessage([
"These " + potentialVisitors.length + "players can visit your home", 'These ' + potentialVisitors.length + 'players can visit your home',
potentialVisitors.join(", ")]); potentialVisitors.join(', ')]);
}
}, },
'invite': function( params, sender ) { 'invite': function( params, sender ) {
if ( params.length == 1 ) { if ( params.length == 1 ) {
sender.sendMessage("You must provide a player's name"); sender.sendMessage( 'You must provide a player name' );
return; return;
} }
var playerName = params[1]; var playerName = params[1];
var guest = utils.player( playerName ); var guest = utils.player( playerName );
if (!guest) if ( !guest ) {
sender.sendMessage(playerName + " is not here"); sender.sendMessage( playerName + ' is not here' );
else } else {
homes.invite( sender, guest ); homes.invite( sender, guest );
}
}, },
'uninvite': function( params, sender ) { 'uninvite': function( params, sender ) {
if ( params.length == 1 ) { if ( params.length == 1 ) {
sender.sendMessage("You must provide a player's name"); sender.sendMessage( 'You must provide a player name' );
return; return;
} }
var playerName = params[1]; var playerName = params[1];
var guest = utils.player( playerName ); var guest = utils.player( playerName );
if (!guest) if ( !guest ) {
sender.sendMessage(playerName + " is not here"); sender.sendMessage( playerName + ' is not here' );
else } else {
homes.uninvite( sender, guest ); homes.uninvite( sender, guest );
}
}, },
'public': function( params, sender ) { 'public': function( params, sender ) {
homes.open( sender, params.slice( 1 ).join(' ') ); homes.open( sender, params.slice( 1 ).join(' ') );
sender.sendMessage("Your home is open to the public"); sender.sendMessage( 'Your home is open to the public' );
}, },
'private': function( params, sender ) { 'private': function( params, sender ) {
homes.close( sender ); homes.close( sender );
sender.sendMessage("Your home is closed to the public"); sender.sendMessage( 'Your home is closed to the public' );
}, },
'listall': function( params, sender ) { 'listall': function( params, sender ) {
if (!sender.isOp()) if ( !sender.isOp() ) {
sender.sendMessage("Only operators can do this"); sender.sendMessage( 'Only operators can do this' );
else } else {
sender.sendMessage(homes.listall().join(", ")); sender.sendMessage( homes.listall().join(', ') );
}
}, },
'clear': function( params, sender ) { 'clear': function( params, sender ) {
if (!sender.isOp()) if ( !sender.isOp() ) {
sender.sendMessage("Only operators can do this"); sender.sendMessage( 'Only operators can do this' );
else } else {
homes.clear( params[1], sender ); homes.clear( params[1], sender );
} }
}
}; };
var optionList = []; var optionList = [];
for (var o in options) for ( var o in options ) {
optionList.push(o); optionList.push(o);
}
/* /*
Expose a set of commands that players can use at the in-game command prompt Expose a set of commands that players can use at the in-game command prompt
*/ */
command("home", function ( params , sender) { command( 'home', function ( params , sender) {
var option,
host;
if ( params.length == 0 ) { if ( params.length == 0 ) {
homes.go( sender, sender ); homes.go( sender, sender );
return; return;
} }
var option = options[params[0]]; option = options[ params[0] ];
if (option) if ( option ) {
option( params, sender ); option( params, sender );
else{ } else {
var host = utils.player(params[0]); host = utils.player( params[0] );
if (!host) if ( !host ) {
sender.sendMessage(params[0] + " is not here"); sender.sendMessage( params[0] + ' is not here' );
else } else {
homes.go( sender, host ); homes.go( sender, host );
} }
}
}, optionList ); }, optionList );

View file

@ -15,9 +15,12 @@ Once the game begins, guess a number by typing the `/` character
followed by a number between 1 and 10. followed by a number between 1 and 10.
***/ ***/
var Prompt = org.bukkit.conversations.Prompt,
ConversationFactory = org.bukkit.conversations.ConversationFactory,
ConversationPrefix = org.bukkit.conversations.ConversationPrefix;
var sb = function( cmd ) { var sb = function( cmd ) {
org.bukkit.Bukkit.dispatchCommand(server.consoleSender, 'scoreboard ' + cmd) org.bukkit.Bukkit.dispatchCommand( server.consoleSender, 'scoreboard ' + cmd ) ;
}; };
exports.Game_NumberGuess = { exports.Game_NumberGuess = {
@ -29,50 +32,56 @@ exports.Game_NumberGuess = {
sb( 'players set ' + sender.name + ' NumberGuess ' + guesses ); sb( 'players set ' + sender.name + ' NumberGuess ' + guesses );
sb( 'objectives setdisplay sidebar NumberGuess' ); sb( 'objectives setdisplay sidebar NumberGuess' );
var Prompt = org.bukkit.conversations.Prompt;
var ConversationFactory = org.bukkit.conversations.ConversationFactory;
var ConversationPrefix = org.bukkit.conversations.ConversationPrefix;
var number = Math.ceil( Math.random() * 10 ); var number = Math.ceil( Math.random() * 10 );
var prompt = new Prompt() var prompt = new Prompt( ) {
{
getPromptText: function( ctx ) { getPromptText: function( ctx ) {
var hint = ""; var hint = '';
var h = ctx.getSessionData("hint"); var h = ctx.getSessionData( 'hint' );
if ( h ) { if ( h ) {
hint = h; hint = h;
} }
return hint + "Think of a number between 1 and 10"; return hint + 'Think of a number between 1 and 10';
}, },
acceptInput: function(ctx, s)
{ acceptInput: function( ctx, s ) {
s = s.replace(/^[^0-9]+/,""); // strip leading non-numeric characters (e.g. '/' ) s = s.replace( /^[^0-9]+/, '' ); // strip leading non-numeric characters (e.g. '/' )
s = parseInt( s ); s = parseInt( s );
if ( s == number ) { if ( s == number ) {
setTimeout(function( ) { setTimeout(function( ) {
ctx.forWhom.sendRawMessage("You guessed Correct!"); ctx.forWhom.sendRawMessage( 'You guessed Correct!' );
sb( 'objectives remove NumberGuess' ); sb( 'objectives remove NumberGuess' );
}, 100 ); }, 100 );
return null; return null;
} else { } else {
if (s < number) if ( s < number ) {
ctx.setSessionData("hint","too low\n"); ctx.setSessionData( 'hint', 'too low\n' );
if (s > number) }
ctx.setSessionData("hint","too high\n"); if ( s > number ) {
ctx.setSessionData( 'hint', 'too high\n' );
}
guesses++; guesses++;
sb( 'players set ' + sender.name + ' NumberGuess ' + guesses ); sb( 'players set ' + sender.name + ' NumberGuess ' + guesses );
return prompt; return prompt;
} }
}, },
blocksForInput: function(ctx){ return true; }
}; blocksForInput: function( ctx ) {
var cf = new ConversationFactory(__plugin); return true;
var conv = cf.withModality(true) }
.withFirstPrompt(prompt) };
.withPrefix(new ConversationPrefix(){ getPrefix: function(ctx){ return "[1-10] ";} }) var convPrefix = new ConversationPrefix( ) {
.buildConversation(sender); getPrefix: function( ctx ) {
conv.begin(); return '[1-10] ';
}
};
new ConversationFactory( __plugin )
.withModality( true )
.withFirstPrompt( prompt )
.withPrefix( convPrefix )
.buildConversation( sender )
.begin( );
} }
}; };

View file

@ -42,7 +42,18 @@ cover to make the game more fun.
***/ ***/
var GameMode = org.bukkit.GameMode,
EntityDamageByEntityEvent = org.bukkit.event.entity.EntityDamageByEntityEvent,
ItemStack = org.bukkit.inventory.ItemStack,
Material = org.bukkit.Material,
Snowball = org.bukkit.entity.Snowball;
var _startGame = function( gameState ) { var _startGame = function( gameState ) {
var i,
teamName,
team,
player;
// don't let game start if already in progress (wait for game to finish) // don't let game start if already in progress (wait for game to finish)
if ( gameState.inProgress ) { if ( gameState.inProgress ) {
return; return;
@ -52,17 +63,17 @@ var _startGame = function(gameState){
gameState.duration = gameState.originalDuration; gameState.duration = gameState.originalDuration;
// put all players in survival mode and give them each 200 snowballs // put all players in survival mode and give them each 200 snowballs
// 64 snowballs for every 30 seconds should be more than enough // 64 snowballs for every 30 seconds should be more than enough
for (var i = 10;i < gameState.duration;i+=10) for ( i = 10; i < gameState.duration; i += 10 ) {
gameState.ammo.push( gameState.ammo[ 0 ] ); gameState.ammo.push( gameState.ammo[ 0 ] );
}
for (var teamName in gameState.teams) for ( teamName in gameState.teams ) {
{
gameState.teamScores[teamName] = 0; gameState.teamScores[teamName] = 0;
var team = gameState.teams[teamName]; team = gameState.teams[ teamName ];
for (var i = 0;i < team.length;i++) { for ( i = 0; i < team.length; i++ ) {
var player = server.getPlayer(team[i]); player = server.getPlayer( team[i] );
gameState.savedModes[ player.name ] = player.gameMode; gameState.savedModes[ player.name ] = player.gameMode;
player.gameMode = org.bukkit.GameMode.SURVIVAL; player.gameMode = GameMode.SURVIVAL;
player.inventory.addItem( gameState.ammo ); player.inventory.addItem( gameState.ammo );
} }
} }
@ -71,30 +82,37 @@ var _startGame = function(gameState){
end the game end the game
*/ */
var _endGame = function( gameState ) { var _endGame = function( gameState ) {
var scores = []; var scores = [],
leaderBoard = [],
tn,
i,
teamName,
team,
player,
handlerList;
var leaderBoard = []; leaderBoard = [];
for (var tn in gameState.teamScores){ for ( tn in gameState.teamScores){
leaderBoard.push([tn,gameState.teamScores[tn]]); leaderBoard.push([tn,gameState.teamScores[tn]]);
} }
leaderBoard.sort(function(a,b){ return b[1] - a[1];}); leaderBoard.sort(function(a,b){ return b[1] - a[1];});
for (var i = 0;i < leaderBoard.length; i++){ for ( i = 0; i < leaderBoard.length; i++ ) {
scores.push("Team " + leaderBoard[i][0] + " scored " + leaderBoard[i][1]); scores.push( 'Team ' + leaderBoard[i][0] + ' scored ' + leaderBoard[i][1] );
} }
for (var teamName in gameState.teams) { for ( teamName in gameState.teams ) {
var team = gameState.teams[teamName]; team = gameState.teams[teamName];
for (var i = 0;i < team.length;i++) { for ( i = 0; i < team.length; i++ ) {
// restore player's previous game mode and take back snowballs // restore player's previous game mode and take back snowballs
var player = server.getPlayer(team[i]); player = server.getPlayer( team[i] );
player.gameMode = gameState.savedModes[ player.name ]; player.gameMode = gameState.savedModes[ player.name ];
player.inventory.removeItem( gameState.ammo ); player.inventory.removeItem( gameState.ammo );
player.sendMessage("GAME OVER."); player.sendMessage( 'GAME OVER.' );
player.sendMessage( scores ); player.sendMessage( scores );
} }
} }
var handlerList = org.bukkit.event.entity.EntityDamageByEntityEvent.getHandlerList(); handlerList = EntityDamageByEntityEvent.getHandlerList();
handlerList.unregister( gameState.listener ); handlerList.unregister( gameState.listener );
gameState.inProgress = false; gameState.inProgress = false;
}; };
@ -102,20 +120,26 @@ var _endGame = function(gameState){
get the team the player belongs to get the team the player belongs to
*/ */
var _getTeam = function( player, pteams ) { var _getTeam = function( player, pteams ) {
for (var teamName in pteams) { var teamName,
var team = pteams[teamName]; team,
for (var i = 0;i < team.length; i++) i;
if (team[i] == player.name) for ( teamName in pteams ) {
team = pteams[ teamName ];
for ( i = 0; i < team.length; i++ ) {
if ( team[i] == player.name ) {
return teamName; return teamName;
} }
}
}
return null; return null;
}; };
/* /*
construct a new game construct a new game
*/ */
var createGame = function( duration, teams ) { var createGame = function( duration, teams ) {
var players,
var _snowBalls = new org.bukkit.inventory.ItemStack(org.bukkit.Material.SNOW_BALL, 64); i,
_snowBalls = new ItemStack( Material.SNOW_BALL, 64 );
var _gameState = { var _gameState = {
teams: teams, teams: teams,
@ -127,16 +151,16 @@ var createGame = function(duration, teams) {
savedModes: {}, savedModes: {},
ammo: [ _snowBalls ] ammo: [ _snowBalls ]
}; };
if (typeof duration == "undefined"){ if ( typeof duration == 'undefined' ) {
duration = 60; duration = 60;
} }
if (typeof teams == "undefined"){ if ( typeof teams == 'undefined' ) {
/* /*
wph 20130511 use all players wph 20130511 use all players
*/ */
teams = []; teams = [];
var players = server.onlinePlayers; players = server.onlinePlayers;
for (var i = 0;i < players.length; i++){ for ( i = 0; i < players.length; i++ ) {
teams.push( players[i].name ); teams.push( players[i].name );
} }
} }
@ -146,24 +170,28 @@ var createGame = function(duration, teams) {
// //
if ( teams instanceof Array ) { if ( teams instanceof Array ) {
_gameState.teams = {}; _gameState.teams = {};
for (var i = 0;i < teams.length; i++) for ( i = 0;i < teams.length; i++ ) {
_gameState.teams[ teams[i] ] = [ teams[i] ]; _gameState.teams[ teams[i] ] = [ teams[i] ];
} }
}
/* /*
this function is called every time a player is damaged by another entity/player this function is called every time a player is damaged by another entity/player
*/ */
var _onSnowballHit = function( l, event ) { var _onSnowballHit = function( l, event ) {
var snowball = event.damager; var snowball = event.damager;
if (!snowball || !(snowball instanceof org.bukkit.entity.Snowball)) if ( !snowball || !( snowball instanceof Snowball ) ) {
return; return;
}
var throwersTeam = _getTeam( snowball.shooter, _gameState.teams ); var throwersTeam = _getTeam( snowball.shooter, _gameState.teams );
var damageeTeam = _getTeam( event.entity, _gameState.teams); var damageeTeam = _getTeam( event.entity, _gameState.teams);
if (!throwersTeam || !damageeTeam) if ( !throwersTeam || !damageeTeam ) {
return; // thrower/damagee wasn't in game return; // thrower/damagee wasn't in game
if (throwersTeam != damageeTeam) }
if ( throwersTeam != damageeTeam ) {
_gameState.teamScores[ throwersTeam ]++; _gameState.teamScores[ throwersTeam ]++;
else } else {
_gameState.teamScores[ throwersTeam ]--; _gameState.teamScores[ throwersTeam ]--;
}
}; };
return { return {
@ -171,8 +199,9 @@ var createGame = function(duration, teams) {
_startGame( _gameState ); _startGame( _gameState );
_gameState.listener = events.on('entity.EntityDamageByEntityEvent',_onSnowballHit); _gameState.listener = events.on('entity.EntityDamageByEntityEvent',_onSnowballHit);
new java.lang.Thread( function( ) { new java.lang.Thread( function( ) {
while (_gameState.duration--) while ( _gameState.duration-- ) {
java.lang.Thread.sleep( 1000 ); // sleep 1,000 millisecs (1 second) java.lang.Thread.sleep( 1000 ); // sleep 1,000 millisecs (1 second)
}
_endGame(_gameState); _endGame(_gameState);
} ).start( ); } ).start( );
} }

View file

@ -41,49 +41,58 @@ your own mini-game...
***/ ***/
var store = {}; var store = {},
Bukkit = org.bukkit.Bukkit,
var scoreboardConfig = { Cow = org.bukkit.entity.Cow,
cowclicker: {SIDEBAR: 'Cows Clicked'} Sound = org.bukkit.Sound,
OfflinePlayer = org.bukkit.OfflinePlayer,
scoreboardConfig = {
cowclicker: {
SIDEBAR: 'Cows Clicked'
}
}; };
var scoreboard = require('minigames/scoreboard')(scoreboardConfig); var scoreboard = require('minigames/scoreboard')(scoreboardConfig);
var _onPlayerInteract = function( listener, event ) { var _onPlayerInteract = function( listener, event ) {
var player = event.player; var player = event.player,
var Bukkit = org.bukkit.Bukkit; clickedEntity = event.rightClicked,
loc = clickedEntity.location;
if (!store[player.name]) if ( !store[ player.name ] ) {
return; return;
}
var clickedEntity = event.rightClicked;
var loc = clickedEntity.location;
var sound = function( snd, vol, pitch ) { var sound = function( snd, vol, pitch ) {
loc.world.playSound( loc, snd, vol, pitch ); loc.world.playSound( loc, snd, vol, pitch );
}; };
if (clickedEntity instanceof org.bukkit.entity.Cow)
{ if ( clickedEntity instanceof Cow) {
store[ player.name ].score++; store[ player.name ].score++;
scoreboard.update( 'cowclicker', player, store[ player.name ].score ); scoreboard.update( 'cowclicker', player, store[ player.name ].score );
Bukkit.dispatchCommand( player, 'me clicked a cow!' ); Bukkit.dispatchCommand( player, 'me clicked a cow!' );
sound(org.bukkit.Sound.CLICK,1,1); sound( Sound.CLICK, 1, 1 );
setTimeout( function( ) { setTimeout( function( ) {
sound(org.bukkit.Sound.COW_HURT,10,0.85) sound( Sound.COW_HURT, 10, 0.85 ) ;
}, 200 ); }, 200 );
} }
}; };
var _onPlayerQuit = function( listener, event ) { var _onPlayerQuit = function( listener, event ) {
_removePlayer(event.player) _removePlayer( event.player );
}; };
var _onPlayerJoin = function( listener, event ) { var _onPlayerJoin = function( listener, event ) {
var gamePlayer = store[event.player.name]; var gamePlayer = store[event.player.name];
if (gamePlayer) if ( gamePlayer ) {
_addPlayer( event.player, gamePlayer.score ); _addPlayer( event.player, gamePlayer.score );
}
}; };
var _startGame = function( ) { var _startGame = function( ) {
if (config.verbose) var p,
player;
if ( config.verbose ) {
console.log('Staring game: Cow Clicker'); console.log('Staring game: Cow Clicker');
}
events.on( 'player.PlayerQuitEvent', _onPlayerQuit ); events.on( 'player.PlayerQuitEvent', _onPlayerQuit );
events.on( 'player.PlayerJoinEvent', _onPlayerJoin ); events.on( 'player.PlayerJoinEvent', _onPlayerJoin );
@ -92,8 +101,8 @@ var _startGame = function(){
scoreboard.start(); scoreboard.start();
store = persist( 'cowclicker', store ); store = persist( 'cowclicker', store );
for (var p in store){ for ( p in store ) {
var player = server.getPlayer(p); player = server.getPlayer( p );
if ( player ) { if ( player ) {
/* /*
only add online players only add online players
@ -103,12 +112,14 @@ var _startGame = function(){
} }
} }
}; };
var _addPlayer = function(player,score){
if (config.verbose)
console.log('Adding player %s to Cow Clicker game',player);
if (typeof score == 'undefined') var _addPlayer = function( player, score ) {
if ( config.verbose ) {
console.log( 'Adding player %s to Cow Clicker game', player );
}
if ( typeof score == 'undefined' ) {
score = 0; score = 0;
}
store[ player.name ] = { score: score }; store[ player.name ] = { score: score };
scoreboard.update( 'cowclicker', player, store[ player.name ].score); scoreboard.update( 'cowclicker', player, store[ player.name ].score);
@ -117,13 +128,16 @@ var _addPlayer = function(player,score){
var _removePlayer = function( player, notify ) { var _removePlayer = function( player, notify ) {
if (player instanceof org.bukkit.OfflinePlayer && player.player) if ( player instanceof OfflinePlayer && player.player ) {
player = player.player; player = player.player;
}
if (!store[player.name]) if ( !store[player.name] ) {
return; return;
if (config.verbose) }
if ( config.verbose ) {
console.log( 'Removing player %s from Cow Clicker', player ); console.log( 'Removing player %s from Cow Clicker', player );
}
var playerScore = store[ player.name ].score; var playerScore = store[ player.name ].score;
@ -135,24 +149,31 @@ var _removePlayer = function(player,notify){
'You must be tired after all that clicking.' ); 'You must be tired after all that clicking.' );
} }
}; };
var _removeAllPlayers = function( notify ) { var _removeAllPlayers = function( notify ) {
if (typeof notify == 'undefined') if ( typeof notify == 'undefined' ) {
notify = false; notify = false;
}
for ( var p in store ) { for ( var p in store ) {
var player = server.getOfflinePlayer( p ); var player = server.getOfflinePlayer( p );
if (player) if ( player ) {
_removePlayer( player, notify ); _removePlayer( player, notify );
}
delete store[p]; delete store[p];
} }
} };
var _stopGame = function( removePlayers ) { var _stopGame = function( removePlayers ) {
if (typeof removePlayers == 'undefined') if ( typeof removePlayers == 'undefined' ) {
removePlayers = true; removePlayers = true;
if (config.verbose) }
if ( config.verbose ) {
console.log( 'Stopping game: Cow Clicker' ); console.log( 'Stopping game: Cow Clicker' );
}
scoreboard.stop(); scoreboard.stop();
if (!removePlayers) if ( !removePlayers ) {
return; return;
}
_removeAllPlayers( false ); _removeAllPlayers( false );
persist( 'cowclicker', store.pers, 'w' ); persist( 'cowclicker', store.pers, 'w' );
@ -165,10 +186,11 @@ _startGame();
players can join and leave the game by typing `jsp cowclicker` players can join and leave the game by typing `jsp cowclicker`
*/ */
command( 'cowclicker', function( params, sender ) { command( 'cowclicker', function( params, sender ) {
if (!store[sender.name]) if ( !store[sender.name] ) {
_addPlayer( sender ); _addPlayer( sender );
else } else {
_removePlayer( sender ); _removePlayer( sender );
}
}); });
/* /*
stop the game when ScriptCraft is unloaded. stop the game when ScriptCraft is unloaded.

View file

@ -16,10 +16,11 @@ press TAB. Visit
for a list of possible entities (creatures) which can be spawned. for a list of possible entities (creatures) which can be spawned.
***/ ***/
var entities = []; var entities = [],
var Types = org.bukkit.entity.EntityType EntityType = org.bukkit.entity.EntityType;
for (var t in Types){
if (Types[t] && Types[t].ordinal){ for ( var t in EntityType ) {
if ( EntityType[t] && EntityType[t].ordinal ) {
entities.push(t); entities.push(t);
} }
} }
@ -31,5 +32,5 @@ command('spawn', function(parameters, sender){
var location = sender.location; var location = sender.location;
var world = location.world; var world = location.world;
var type = ('' + parameters[0]).toUpperCase(); var type = ('' + parameters[0]).toUpperCase();
world.spawnEntity(location, org.bukkit.entity.EntityType[type]); world.spawnEntity( location, EntityType[type] );
}, entities ); }, entities );

View file

@ -3,17 +3,23 @@
*/ */
var __scboot = null; var __scboot = null;
(function(){ (function(){
var File = java.io.File var File = java.io.File,
,FileReader = java.io.FileReader FileReader = java.io.FileReader,
,FileOutputStream = java.io.FileOutputStream FileOutputStream = java.io.FileOutputStream,
,ZipInputStream = java.util.zip.ZipInputStream ZipInputStream = java.util.zip.ZipInputStream,
,jsPlugins = new File('plugins/scriptcraft') jsPlugins = new File('plugins/scriptcraft'),
,initScript = 'lib/scriptcraft.js'; initScript = 'lib/scriptcraft.js';
var unzip = function(path, logger, plugin) { var unzip = function(path, logger, plugin) {
var zis = new ZipInputStream(plugin.getResource(path)) var zis = new ZipInputStream(plugin.getResource(path)),
, entry , reason = null, unzipFile = false, zTime = 0 entry,
, fTime = 0, fout = null, c, newFile; reason = null,
unzipFile = false,
zTime = 0,
fTime = 0,
fout = null,
c,
newFile;
while ( ( entry = zis.nextEntry ) != null ) { while ( ( entry = zis.nextEntry ) != null ) {
@ -48,13 +54,18 @@ var __scboot = null;
} }
zis.close(); zis.close();
}; };
/*
Called from Java plugin
*/
__scboot = function ( plugin, engine ) __scboot = function ( plugin, engine )
{ {
var logger = plugin.logger, cfg = plugin.config var logger = plugin.logger,
,cfgName, initScriptFile = new File(jsPlugins,initScript) cfg = plugin.config,
,zips = ['lib','plugins','modules'] cfgName,
,i = 0 ,len = zips.length; initScriptFile = new File(jsPlugins,initScript),
zips = ['lib','plugins','modules'],
i = 0,
len = zips.length;
if (!jsPlugins.exists()){ if (!jsPlugins.exists()){
logger.info('Directory ' + jsPlugins.canonicalPath + ' does not exist.'); logger.info('Directory ' + jsPlugins.canonicalPath + ' does not exist.');