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...
var http = require('./http/request');
http.request({ url: "http://pixenate.com/pixenate/pxn8.pl",
method: "POST",
params: {script: "[]"}
}, function( responseCode, responseBody){
var jsObj = eval("(" + responseBody + ")");
http.request(
{
url: 'http://pixenate.com/pixenate/pxn8.pl',
method: 'POST',
params: {script: '[]'}
},
function( responseCode, responseBody ) {
var jsObj = eval('(' + responseBody + ')');
});
## sc-mqtt module
@ -1173,7 +1176,7 @@ package for scheduling processing of arrays.
- object : Additional (optional) information passed into the foreach method.
- 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
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
@ -2293,10 +2296,11 @@ Source Code ...
command( 'hello-byname', function( parameters, sender ) {
var playerName = parameters[0];
var recipient = utils.player( playerName );
if (recipient)
if ( recipient ) {
greetings.hello( recipient );
else
} else {
sender.sendMessage( 'Player ' + playerName + ' not found.' );
}
});
## 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.
*/
var _commands = {};
var _cmdInterceptors = [];
var _commands = {},
_cmdInterceptors = [];
/*
execute a JSP command.
*/
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');
var name = args[0];
var cmd = _commands[name];
}
name = args[0];
cmd = _commands[name];
if ( typeof cmd === 'undefined' ) {
// it's not a global command - pass it on to interceptors
var intercepted = false;
intercepted = false;
for ( var i = 0; i < _cmdInterceptors.length; i++ ) {
if ( _cmdInterceptors[i]( args, player ) )
intercepted = true;
}
if (!intercepted)
if ( !intercepted ) {
console.warn( 'Command %s is not recognised', name );
}
}else{
var result = null;
try {
result = cmd.callback( args.slice(1), player );
} catch ( e ) {
console.error( 'Error while trying to execute command: ' + JSON.stringify( args ) );
throw e;
}
return result;
}
return result;
};
/*
define a new JSP command.
*/
var defineCmd = function( name, func, options, intercepts ) {
if (typeof options == 'undefined')
if ( typeof options == 'undefined' ) {
options = [];
}
_commands[name] = { callback: func, options: options };
if (intercepts)
if ( intercepts ) {
_cmdInterceptors.push(func);
}
return func;
};
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
***/
var logger = __plugin.logger;
var logger = __plugin.logger,
logMethodName = 'log(java.util.logging.Level,java.lang.String)';
var argsToArray = function( args ) {
var result = [];
for (var i =0;i < args.length; i++)
for ( var i =0; i < args.length; i++ ) {
result.push(args[i]);
}
return result;
}
var log = function( level, restOfArgs ) {
var args = argsToArray( restOfArgs );
if ( args.length > 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 {
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( ) {
log( Level.INFO, arguments );
}
};
exports.warn = function( ) {
log( Level.WARNING, arguments );
};
exports.error = function( ) {
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 bkEvtExecutor = org.bukkit.plugin.EventExecutor;
var bkRegListener = org.bukkit.plugin.RegisteredListener;
var bkEvent = org.bukkit.event,
bkEvtExecutor = org.bukkit.plugin.EventExecutor,
bkRegListener = org.bukkit.plugin.RegisteredListener;
exports.on = function(
/* String or java Class */
@ -86,13 +86,16 @@ exports.on = function(
handler,
/* (optional) String (HIGH, HIGHEST, LOW, LOWEST, NORMAL, MONITOR), */
priority ) {
var handlerList,
listener = {},
eventExecutor;
if (typeof priority == "undefined"){
if ( typeof priority == 'undefined' ) {
priority = bkEvent.EventPriority.HIGHEST;
} else {
priority = bkEvent.EventPriority[priority];
}
if (typeof eventType == "string"){
if ( typeof eventType == 'string' ) {
/*
Nashorn doesn't support bracket notation for accessing packages.
E.g. java.net will work but java['net'] won't.
@ -106,9 +109,8 @@ exports.on = function(
eventType = eval( 'org.bukkit.event.' + eventType );
}
}
var handlerList = eventType.getHandlerList();
var listener = {};
var eventExecutor = new bkEvtExecutor(){
handlerList = eventType.getHandlerList( );
eventExecutor = new bkEvtExecutor( ) {
execute: function( l, e ) {
handler( listener.reg, e );
}

View file

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

View file

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

View file

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

View file

@ -93,7 +93,6 @@ module specification, the '.js' suffix is optional.
return "" + file.canonicalPath.replaceAll("\\\\","/");
};
var resolveModuleToFile = function(moduleName, parentDir) {
/**********************************************************************
### 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
***/
var resolveModuleToFile = function ( moduleName, parentDir ) {
var file = new File(moduleName);
if ( file.exists() ) {

View file

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

View file

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

View file

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

View file

@ -192,7 +192,7 @@ var blocks = {
oak: '126:8',
spruce: '126:9',
birch: '126:10',
jungle: '126:11',
jungle: '126:11'
}
},
cocoa: 127,
@ -252,7 +252,7 @@ var colors = {
red: ':14',
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++) {
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
clay blocks.
*/
blocks.rainbow = [blocks.wool.red,
blocks.rainbow = [
blocks.wool.red,
blocks.wool.orange,
blocks.wool.yellow,
blocks.wool.lime,
@ -277,5 +278,4 @@ blocks.rainbow = [blocks.wool.red,
blocks.wool.blue,
blocks.wool.purple];
module.exports = blocks;

View file

@ -68,7 +68,8 @@ var firework = function(location){
var effectBuilder = FireworkEffect.builder()
.flicker( Math.round( Math.random() ) == 0 )
.withColor( c1 )
.withFade(c2).trail(Math.round(Math.random())==0);
.withFade( c2 )
.trail( Math.round( Math.random() ) == 0 );
effectBuilder['with']( type );
var effect = effectBuilder.build();
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...
var http = require('./http/request');
http.request({ url: "http://pixenate.com/pixenate/pxn8.pl",
method: "POST",
params: {script: "[]"}
}, function( responseCode, responseBody){
var jsObj = eval("(" + responseBody + ")");
http.request(
{
url: 'http://pixenate.com/pixenate/pxn8.pl',
method: 'POST',
params: {script: '[]'}
},
function( responseCode, responseBody ) {
var jsObj = eval('(' + responseBody + ')');
});
***/
exports.request = function( request, callback)
{
exports.request = function( request, callback ) {
var paramsToString = function( params ) {
var result = "";
var paramNames = [];
for (var i in params){
var result = '',
paramNames = [],
i;
for ( i in params ) {
paramNames.push( i );
}
for (var i = 0;i < paramNames.length;i++){
result += paramNames[i] + "=" + encodeURI(params[paramNames[i]]);
for ( i = 0; i < paramNames.length; i++ ) {
result += paramNames[i] + '=' + encodeURI( params[ paramNames[i] ] );
if ( i < paramNames.length-1 )
result += "&";
result += '&';
}
return result;
};
server.scheduler.runTaskAsynchronously(__plugin,function()
{
server.scheduler.runTaskAsynchronously( __plugin, function() {
var url, paramsAsString, conn, requestMethod;
if (typeof request === "string"){
if (typeof request === 'string'){
url = request;
requestMethod = "GET";
requestMethod = 'GET';
}else{
paramsAsString = paramsToString( request.params );
if (request.method)
requestMethod = request.method
else
requestMethod = "GET";
if (requestMethod == "GET" && request.params){
if ( request.method ) {
requestMethod = request.method;
} else {
requestMethod = 'GET';
}
if ( requestMethod == 'GET' && request.params ) {
// append each parameter to the URL
url = request.url + "?" + paramsAsString;
url = request.url + '?' + paramsAsString;
}
}
conn = new java.net.URL( url ).openConnection();
@ -84,12 +86,12 @@ exports.request = function( request, callback)
conn.doOutput = true;
conn.instanceFollowRedirects = false;
if (conn.requestMethod == "POST"){
if ( conn.requestMethod == 'POST' ) {
conn.doInput = true;
// put each parameter in the outputstream
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", "" + paramsAsString.length);
conn.setRequestProperty('Content-Type', 'application/x-www-form-urlencoded');
conn.setRequestProperty('charset', 'utf-8');
conn.setRequestProperty('Content-Length', '' + paramsAsString.length);
conn.useCaches =false ;
wr = new java.io.DataOutputStream(conn.getOutputStream ());
wr.writeBytes(paramsAsString);

View file

@ -9,10 +9,12 @@ module.exports = function(options){
return {
start: function( ) {
var objective, slot;
var objective,
slot,
ccObj;
ccScoreboard = server.scoreboardManager.getNewScoreboard();
for ( objective in options ) {
var ccObj = ccScoreboard.registerNewObjective(objective,'dummy');
ccObj = ccScoreboard.registerNewObjective( objective, 'dummy' );
for ( slot in options[ objective ] ) {
ccObj.displaySlot = DisplaySlot[ slot ];
ccObj.displayName = options[ objective ][ slot ];
@ -29,17 +31,20 @@ module.exports = function(options){
}
},
update: function( objective, player, score ) {
if (player.scoreboard && player.scoreboard != ccScoreboard)
{
if ( player.scoreboard && player.scoreboard != ccScoreboard ) {
temp[player.name] = player.scoreboard;
player.scoreboard = ccScoreboard;
}
ccScoreboard.getObjective(objective).getScore(player).score = score;
ccScoreboard
.getObjective( objective )
.getScore( player )
.score = score;
},
restore: function( player ) {
// offlineplayers don't have a scoreboard
if (player.scoreboard)
if ( player.scoreboard ) {
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 );
client.setCallback( callback );
return {
connect: function( options ) {
if ( typeof options === 'undefined' ) {
client.connect();
@ -103,10 +102,11 @@ function Client(brokerUrl, clientId){
},
disconnect: function( quiesceTimeout ) {
if (typeof quiesceTimeout == 'undefined')
if ( typeof quiesceTimeout == 'undefined' ) {
client.disconnect();
else
} else {
client.disconnect( quiesceTimeout );
}
return client;
},
@ -150,7 +150,9 @@ function Client(brokerUrl, clientId){
}
};
}
/*
Return a new MQTT Client
*/
exports.client = function( brokerUrl, clientId, options ) {
if ( typeof org.walterhiggins.scriptcraft.ScriptCraftMqttCallback != 'function' ) {
throw MISSING_MQTT;

View file

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

View file

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

View file

@ -118,17 +118,19 @@ Location object.
***/
exports.locationFromJSON = function( json ) {
var world;
if ( json.constuctor == Array ) {
// 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] );
} 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 );
}
};
exports.player = _player;
exports.getPlayerObject = function( player ) {
console.warn( 'utils.getPlayerObject() is deprecated. Use utils.player() instead.' );
return _player(player);
@ -160,7 +162,6 @@ exports.getPlayerPos = function( player ) {
else
return player.location;
}
else
return null;
};
/************************************************************************
@ -189,11 +190,13 @@ The following code will strike lightning at the location the player is looking a
exports.getMousePos = function( player ) {
player = _player(player);
if (!player)
if ( !player ) {
return null;
}
// player might be CONSOLE or a CommandBlock
if (!player.getTargetBlock)
if ( !player.getTargetBlock ) {
return null;
}
var targetedBlock = player.getTargetBlock( null, 5 );
if ( targetedBlock == null || targetedBlock.isEmpty() ) {
return null;
@ -228,7 +231,7 @@ package for scheduling processing of arrays.
- object : Additional (optional) information passed into the foreach method.
- 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
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
@ -286,18 +289,24 @@ without hogging CPU usage...
utils.foreach (a, processItem, null, 10, onDone);
***/
var _foreach = function(array, callback, object, delay, onCompletion) {
if (array instanceof java.util.Collection)
var _foreach = function( array, callback, context, delay, onCompletion ) {
if ( array instanceof java.util.Collection ) {
array = array.toArray();
}
var i = 0;
var len = array.length;
if ( delay ) {
var next = function(){ callback(array[i],i,object,array); i++;};
var hasNext = function(){return i < len;};
var next = function( ) {
callback(array[i], i, context, array);
i++;
};
var hasNext = function( ) {
return i < len;
};
_nicely( next, hasNext, onCompletion, delay );
} else {
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 );
}, delay );
}else{
if (onDone)
if ( onDone ) {
onDone();
}
}
};
exports.nicely = _nicely;
/************************************************************************
@ -372,9 +382,9 @@ exports.at = function(time24hr, callback, worlds) {
var timeParts = time24hr.split( ':' );
var hrs = ( (timeParts[0] * 1000) + 18000 ) % 24000;
var mins;
if (timeParts.length > 1)
if ( timeParts.length > 1 ) {
mins = ( timeParts[1] / 60 ) * 1000;
}
var timeMc = hrs + mins;
if ( typeof worlds == 'undefined' ) {
worlds = server.worlds;
@ -416,11 +426,11 @@ exports.find = function( dir , filter){
var recurse = function( dir, store ) {
var files, dirfile = new java.io.File( dir );
if (typeof filter == 'undefined')
if ( typeof filter == 'undefined' ) {
files = dirfile.list();
else
} else {
files = dirfile.list(filter);
}
_foreach( files, function( file ) {
file = new java.io.File( dir + '/' + file );
if ( file.isDirectory() ) {
@ -429,7 +439,7 @@ exports.find = function( dir , filter){
store.push( file.canonicalPath );
}
});
}
};
recurse( dir, 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 global {alias} = {command-1} ; {command-2}\n \
/jsp alias list\n \
@ -61,7 +61,7 @@ Create a new alias : \n \
/jsp alias set cw = time set {1} ; weather {2}\n \
Execute the alias : \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
*/
@ -93,53 +93,53 @@ var _set = function(params, player){
var o = _processParams( params );
playerAliases[o.cmd] = o.aliases;
_store.players[player.name] = playerAliases;
player.sendMessage("Alias '" + o.cmd + "' created.");
player.sendMessage( 'Alias ' + o.cmd + ' created.' );
};
var _remove = function( params, player ) {
if (_store.players[player.name] &&
_store.players[player.name][params[0]]){
if ( _store.players[player.name] && _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{
player.sendMessage("Alias '" + params[0] + "' does not exist.");
player.sendMessage( 'Alias ' + params[0] + ' does not exist.' );
}
if ( player.op ) {
if (_store.global[params[0]])
if ( _store.global[params[0]] ) {
delete _store.global[params[0]];
}
}
};
var _global = function( params, player ) {
if ( !player.op ) {
player.sendMessage("Only operators can set global aliases. " +
"You need to be an operator to perform this command.");
player.sendMessage( 'Only operators can set global aliases. ' +
'You need to be an operator to perform this command.' );
return;
}
var o = _processParams( params );
_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 alias = 0;
try {
if ( _store.players[player.name] ) {
player.sendMessage("Your aliases:");
player.sendMessage('Your aliases:');
for ( alias in _store.players[player.name] ) {
player.sendMessage(alias + " = " +
player.sendMessage( alias + ' = ' +
JSON.stringify( _store.players[player.name][alias] ) );
}
} 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 ) {
player.sendMessage(alias + " = " + JSON.stringify(_store.global[alias]) );
player.sendMessage( alias + ' = ' + JSON.stringify( _store.global[alias] ) );
}
} catch( e ) {
console.error("Error in list function: " + e.message);
console.error( 'Error in list function: ' + e.message );
throw e;
}
};
@ -178,15 +178,17 @@ var aliasCmd = command('alias', function( params, invoker ) {
invoker.sendMessage( 'Usage:\n' + _usage );
});
var _intercept = function( msg, invoker, exec)
{
var _intercept = function( msg, invoker, exec ) {
if ( msg.trim().length == 0 )
return false;
var msgParts = msg.split(' '),
command = msg.match( /^\/*([^\s]+)/ )[1],
template = [], isAlias = false, cmds = [],
template = [],
isAlias = false,
cmds = [],
commandObj,
filledinCommand;
filledinCommand,
i;
if ( _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
*/
if (_store.players[invoker] &&
_store.players[invoker][command])
{
if ( _store.players[invoker] && _store.players[invoker][command] ) {
template = _store.players[invoker][command];
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 ) {
index = parseInt( index, 10 );
if (msgParts[index])
if ( msgParts[index] ) {
return msgParts[index];
else
} else {
return match;
}
});
cmds.push( filledinCommand );
}
for (var i = 0; i< cmds.length; i++){
for (i = 0; i< cmds.length; i++ ) {
exec( cmds[i] );
}
return isAlias;
@ -225,18 +225,25 @@ var _intercept = function( msg, invoker, exec)
*/
events.on( 'player.PlayerCommandPreprocessEvent', function( listener, evt ) {
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);
if (isAlias)
if ( isAlias ) {
evt.cancelled = true;
}
});
/* define a 'void' command because ServerCommandEvent can't be canceled */
command('void',function(){});
command('void',function( ) {
} );
events.on( 'server.ServerCommandEvent', function( listener, evt ) {
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 );
if (isAlias)
if ( isAlias ) {
evt.command = 'jsp void';
}
});

View file

@ -25,64 +25,32 @@ player23's arrows explosive.
***/
var signs = require('signs');
var fireworks = require('fireworks');
var utils = require('utils');
var _store = {players: {}};
var arrows = plugin("arrows",{
/*
turn a sign into a menu of arrow choices
*/
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);
var signs = require('signs'),
fireworks = require('fireworks'),
utils = require('utils'),
EXPLOSIVE_YIELD = 2.5,
_store = { players: { } },
arrows = plugin( 'arrows', { store: _store }, true ),
i,
type,
_types = [ 'Normal', 'Explosive', 'Teleport', 'Flourish', 'Lightning', 'Firework' ];
exports.arrows = arrows;
//
// setup functions for the arrow types
//
var _types = {normal: 0, explosive: 1, teleport: 2, flourish: 3, lightning: 4, firework: 5};
for (var type in _types)
{
for ( i = 0; i < _types.length; i++ ) {
type = _types[i].toLowerCase();
// iife (immediately-invoked function expression)
arrows[ type ] = ( function( n ) {
return function( player ) {
player = utils.player( player );
if (player)
if ( player ) {
arrows.store.players[ player.name ] = n;
else
} else {
console.warn('arrows.' + n + ' No player ' + player);
}
};
})(_types[type]);
} )( i );
}
/*
@ -91,13 +59,12 @@ for (var type in _types)
var _onMenuChoice = function( event ) {
arrows.store.players[ event.player.name ] = event.number;
};
var convertToArrowSign = signs.menu(
"Arrow",
["Normal","Explosive","Teleport","Flourish","Lightning","Firework"],
_onMenuChoice);
var convertToArrowSign = signs.menu( 'Arrow', _types, _onMenuChoice );
arrows.sign = function(cmdSender)
{
/*
turn a sign into a menu of arrow choices
*/
arrows.sign = function( cmdSender ) {
var sign = signs.getTargetedBy( cmdSender );
if ( !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
*/
var _onArrowHit = function(listener,event)
{
var projectile = event.entity;
var world = projectile.world;
var shooter = projectile.shooter;
var fireworkCount = 5;
if (projectile instanceof org.bukkit.entity.Arrow &&
shooter instanceof org.bukkit.entity.Player)
{
var arrowType = arrows.store.players[shooter.name];
var _onArrowHit = function( listener, event ) {
var projectile = event.entity,
world = projectile.world,
shooter = projectile.shooter,
fireworkCount = 5,
arrowType,
TeleportCause = org.bukkit.event.player.PlayerTeleportEvent.TeleportCause,
launch = function( ) {
fireworks.firework( projectile.location );
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 ) {
case 1:
projectile.remove();
world.createExplosion(projectile.location,arrows.explosiveYield);
world.createExplosion( projectile.location, EXPLOSIVE_YIELD );
break;
case 2:
projectile.remove();
var teleportCause =org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
shooter.teleport(projectile.location,
teleportCause.PLUGIN);
shooter.teleport( projectile.location, TeleportCause.PLUGIN );
break;
case 3:
projectile.remove();
@ -140,11 +113,6 @@ var _onArrowHit = function(listener,event)
break;
case 5:
projectile.remove();
var launch = function(){
fireworks.firework(projectile.location);
if (--fireworkCount)
setTimeout(launch,2000);
};
launch();
break;
}

View file

@ -1,11 +1,33 @@
/*
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
*/
exports.chat = plugin("chat", {
exports.chat = plugin( 'chat', {
/*
set the color of text for a given player
*/
@ -17,37 +39,33 @@ exports.chat = plugin("chat", {
},true);
var colors = [
"black", "blue", "darkgreen", "darkaqua", "darkred",
"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;
}
foreach( colors, function ( color, i ) {
colorCodes[color] = i.toString( 16 );
} );
events.on("player.AsyncPlayerChatEvent",function(l,e){
events.on( 'player.AsyncPlayerChatEvent', function( l, e ) {
var player = e.player;
var playerChatColor = _store.players[ player.name ];
if ( playerChatColor ) {
e.message = "§" + colorCodes[playerChatColor] + e.message;
e.message = '§' + colorCodes[ playerChatColor ] + e.message;
}
});
var listColors = function( params, sender ) {
var colorNamesInColor = [];
for (var i = 0;i < colors.length;i++)
colorNamesInColor[i] = "§"+colorCodes[colors[i]] + colors[i];
sender.sendMessage("valid chat colors are " + colorNamesInColor.join(", "));
foreach (colors, function( color ) {
colorNamesInColor.push( '§' + colorCodes[color] + color );
} );
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];
if ( colorCodes[color] ) {
chat.setColor( sender, color );
} else {
sender.sendMessage(color + " is not a valid color");
sender.sendMessage( color + ' is not a valid color' );
listColors();
}
}, colors );

View file

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

View file

@ -1,21 +1,22 @@
/*
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 times = {
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');
var commando = require('./commando').commando,
times = ['Dawn','Midday','Dusk','Midnight'];
},['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 ) {
var msg = '' + e.message;
var parts = msg.match( /^\/([^\s]+)/ );
if (!parts)
if ( !parts ) {
return;
if (parts.length < 2)
}
if ( parts.length < 2 ) {
return;
}
var command = parts[1];
if ( commands[command] ) {
e.message = "/jsp " + msg.replace(/^\//,"");
e.message = '/jsp ' + msg.replace( /^\//, '' );
}
} );
events.on( 'server.ServerCommandEvent', function( l, e ) {
var msg = '' + e.command;
var parts = msg.match( /^\/*([^\s]+)/ );
if (!parts)
if ( !parts ) {
return;
if (parts.length < 2)
}
if ( parts.length < 2 ) {
return;
}
var command = parts[1];
if ( commands[ command ] ) {
var newCmd = "jsp " + msg.replace(/^\//,"");
var newCmd = 'jsp ' + msg.replace( /^\//, '' );
if ( config.verbose ) {
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
*/
for (var c in bitmaps.raw){
var bits = bitmaps.raw[c];
var width = bits.length/5;
var bmInfo = {"width": width,"pixels":[]}
var c,
bits,
width,
bmInfo,
j;
for ( c in bitmaps.raw ) {
bits = bitmaps.raw[c];
width = bits.length/5;
bmInfo = { width: width, pixels:[] };
bitmaps.computed[c] = bmInfo;
for (var j = 0; j < bits.length; j++){
for ( j = 0; j < bits.length; 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 ) {
var bmfg,
bmbg,
lines,
lineCount,
h,
line,
i,
x,
y,
ch,
bits,
charWidth,
j;
this.chkpt('blocktext');
if (typeof fg == "undefined")
if ( typeof fg == 'undefined' ) {
fg = blocks.wool.black;
}
var bmfg = this._getBlockIdAndMeta(fg);
var bmbg = null;
if (typeof bg != "undefined")
bmfg = this._getBlockIdAndMeta( fg );
bmbg = null;
if ( typeof bg != 'undefined' ) {
bmbg = this._getBlockIdAndMeta( bg );
var lines = message.split("\n");
var lineCount = lines.length;
for (var h = 0;h < lineCount; h++) {
var line = lines[h];
line = line.toLowerCase().replace(/[^0-9a-z \.\-\+\/\;\'\:\!]/g,"");
}
lines = message.split( '\n' );
lineCount = lines.length;
for ( h = 0; h < lineCount; h++) {
line = lines[h];
line = line.toLowerCase().replace( /[^0-9a-z \.\-\+\/\;\'\:\!]/g, '' );
this.up( 7 * ( lineCount - ( h + 1 ) ) );
for (var i =0;i < line.length; i++) {
var ch = line.charAt(i)
var bits = bitmaps.computed[ch];
if (typeof bits == "undefined"){
for ( i =0; i < line.length; i++) {
ch = line.charAt( i );
bits = bitmaps.computed[ ch ];
if ( typeof bits == 'undefined' ) {
bits = bitmaps.computed[' '];
}
var charWidth = bits.width;
if (typeof bg != "undefined")
charWidth = bits.width;
if ( typeof bg != 'undefined' ) {
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' );
var x = bits.pixels[j][0];
var y = bits.pixels[j][1];
x = bits.pixels[ j ][ 0 ];
y = bits.pixels[ j ][ 1] ;
this.up( 6 - y ).right( x ).cuboidX( bmfg[ 0 ], bmfg[ 1 ] );
this.move( 'btbl' );
}
this.right( charWidth - 1 );
}
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
//
Drone.extend('castle', function(side, height)
{
Drone.extend('castle', function( side, height ) {
//
// use sensible default parameter values
// 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)
//
for (var corner = 0; corner < 4; corner++)
{
for ( var corner = 0; corner < 4; corner++ ) {
// construct a 'tower' fort
this.fort(towerSide,towerHeight);
// 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
* height - height of the chessboard
*/
Drone.extend("chessboard", function(whiteBlock, blackBlock, width, depth) {
this.chkpt('chessboard-start');
if (typeof whiteBlock == "undefined")
whiteBlock = blocks.wool.white;
if (typeof blackBlock == "undefined")
blackBlock = blocks.wool.black;
if (typeof width == "undefined")
width = 8;
if (typeof depth == "undefined")
depth = width;
Drone.extend('chessboard', function( whiteBlock, blackBlock, width, depth ) {
var i,
j,
block;
for(var i = 0; i < width; ++i) {
for(var j = 0; j < depth; ++j) {
var block = blackBlock;
if((i+j)%2 == 1) {
block = whiteBlock;
this.chkpt('chessboard-start');
if ( typeof whiteBlock == 'undefined' ) {
whiteBlock = blocks.wool.white;
}
this.box(block);
this.right();
if ( typeof blackBlock == 'undefined' ) {
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');
});

View file

@ -11,8 +11,7 @@ var Drone = require('../drone').Drone;
// /js drone.cottage();
//
Drone.extend('cottage',function ()
{
Drone.extend('cottage',function ( ) {
this.chkpt('cottage')
.box0(48,7,2,6) // 4 walls
.right(3).door() // door front and center
@ -22,7 +21,8 @@ Drone.extend('cottage',function ()
//
// 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');
});
@ -30,9 +30,8 @@ Drone.extend('cottage',function ()
// a more complex script that builds an tree-lined avenue with
// cottages on both sides.
//
Drone.extend('cottage_road', function(numberCottages)
{
if (typeof numberCottages == "undefined"){
Drone.extend('cottage_road', function( numberCottages ) {
if (typeof numberCottages == 'undefined'){
numberCottages = 6;
}
var i=0, distanceBetweenTrees = 11;
@ -41,10 +40,10 @@ Drone.extend('cottage_road', function(numberCottages)
//
var cottagesPerSide = Math.floor(numberCottages/2);
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
.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
@ -56,7 +55,7 @@ Drone.extend('cottage_road', function(numberCottages)
.left(5) // return to middle of road
.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.
function pathAndCottage( d ) {
@ -65,15 +64,14 @@ Drone.extend('cottage_road', function(numberCottages)
//
// step 3 build cottages on each side
//
for (i = 0;i < cottagesPerSide; i++)
{
this.fwd(distanceBetweenTrees+1).chkpt("r"+i);
for ( i = 0; i < cottagesPerSide; i++ ) {
this.fwd(distanceBetweenTrees+1).chkpt('r'+i);
// build cottage on left
pathAndCottage(this.turn(3)).move("r"+i);
pathAndCottage( this.turn(3) ).move( 'r' + i );
// 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 this.move("cottage_road");
return this.move('cottage_road');
});

View file

@ -3,17 +3,20 @@ var Drone = require('../drone').Drone;
//
// constructs a medieval fort
//
Drone.extend('fort', function(side, height)
{
if (typeof side == "undefined")
Drone.extend('fort', function( side, height ) {
if ( typeof side == 'undefined' ) {
side = 18;
if (typeof height == "undefined")
}
if ( typeof height == 'undefined' ) {
height = 6;
}
// make sure side is even
if (side%2)
if ( side % 2 ) {
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;
//
// build walls.
@ -33,7 +36,7 @@ Drone.extend('fort', function(side, height)
try {
this.boxa(turret,1,1,side-2).fwd(side-2).turn();
} 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.up(height-2).fwd().right().box('126:0',side-2,1,side-2);
var battlementWidth = 3;
if (side <= 12)
if ( side <= 12 ) {
battlementWidth = 2;
}
this.fwd(battlementWidth).right(battlementWidth)
.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,
intervalId = -1;
if (typeof bgColor == 'undefined')
if ( typeof bgColor == 'undefined' ) {
bgColor = '35:15'; // black wool
if (typeof fgColor == 'undefined')
}
if ( typeof fgColor == 'undefined' ) {
fgColor = 35 ; // white wool
}
if ( border ) {
drone.box(border,21,9,1);
drone.up().right();

View file

@ -19,16 +19,21 @@ Creates a Rainbow.
***/
Drone.extend('rainbow', function(radius){
if (typeof radius == "undefined")
var i,
colors,
bm;
if ( typeof radius == "undefined" ) {
radius = 18;
}
this.chkpt('rainbow');
this.down(radius);
// 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);
for (var i = 0;i < colors.length; i++) {
var bm = this._getBlockIdAndMeta(colors[i]);
for ( i = 0; i < colors.length; i++ ) {
bm = this._getBlockIdAndMeta( colors[i] );
this.arc({
blockType: bm[0],
meta: bm[1],

View file

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

View file

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

View file

@ -1,5 +1,9 @@
var utils = require('utils');
var blocks = require('blocks');
var utils = require('utils'),
blocks = require('blocks'),
Location = org.bukkit.Location,
Player = org.bukkit.entity.Player,
Sign = org.bukkit.block.Sign,
TreeType = org.bukkit.TreeType;
/*********************************************************************
## 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 ) {
if (typeof metadata == "undefined")
if ( typeof metadata == 'undefined' ) {
metadata = 0;
}
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 );
}
};
var putSign = function( texts, x, y, z, blockId, meta, world ) {
if (blockId != 63 && blockId != 68)
throw new Error("Invalid Parameter: blockId must be 63 or 68");
var i,
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 );
var block = world.getBlockAt(x,y,z);
var state = block.state;
if (state instanceof org.bukkit.block.Sign){
for (var i = 0;i < texts.length; i++)
block = world.getBlockAt( x, y, z );
state = block.state;
if ( state instanceof Sign ) {
for ( i = 0; i < texts.length; i++ ) {
state.setLine( i % 4, texts[ i ] );
}
state.update( true );
}
};
Drone = function(x,y,z,dir,world)
{
var Drone = function( x, y, z, dir, world ) {
this.record = false;
var usePlayerCoords = false;
var player = self;
if (x instanceof org.bukkit.entity.Player){
if ( x instanceof Player ) {
player = x;
}
var playerPos = utils.getPlayerPos( player );
@ -669,12 +680,12 @@ Drone = function(x,y,z,dir,world)
that.world = loc.world;
};
var mp = utils.getMousePos( player );
if (typeof x == "undefined" || x instanceof org.bukkit.entity.Player)
{
if ( typeof x == 'undefined' || x instanceof Player ) {
if ( mp ) {
populateFromLocation( mp );
if (playerPos)
if ( playerPos ) {
this.dir = _getDirFromRotation(playerPos.yaw);
}
} else {
// base it on the player's current location
usePlayerCoords = true;
@ -688,18 +699,18 @@ Drone = function(x,y,z,dir,world)
populateFromLocation( playerPos );
}
} else {
if (arguments[0] instanceof org.bukkit.Location){
if ( arguments[0] instanceof Location ) {
populateFromLocation( arguments[ 0 ] );
} else {
this.x = x;
this.y = y;
this.z = z;
if (typeof dir == "undefined"){
if ( typeof dir == 'undefined' ) {
this.dir = _getDirFromRotation( playerPos.yaw );
} else {
this.dir = dir%4;
}
if (typeof world == "undefined"){
if ( typeof world == 'undefined' ) {
this.world = playerPos.world;
} else {
this.world = world;
@ -727,12 +738,12 @@ exports.blocks = blocks;
//
// 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 ] = function( ) {
if (this.record)
if ( this.record ) {
this.history.push( [ name, arguments ] );
}
var oldVal = this.record;
this.record = false;
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 ) {
if (typeof numTimes == "undefined")
if ( typeof numTimes == 'undefined' ) {
numTimes = 2;
if (typeof commands == "undefined")
}
if ( typeof commands == 'undefined' ) {
commands = this.history.concat();
}
this.history = [ [ 'times', [ numTimes + 1, commands ] ] ];
var oldVal = this.record;
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++) {
var command = commands[i];
var methodName = command[0];
var args = command[1];
print ("command=" + JSON.stringify(command) + ",methodName=" + methodName);
print ('command=' + JSON.stringify(command ) + ',methodName=' + methodName );
this[ methodName ].apply( this, args );
}
}
@ -844,13 +856,13 @@ Drone.extend('chkpt',function(name){
} );
Drone.extend( 'move', function( ) {
if (arguments[0] instanceof org.bukkit.Location){
if ( arguments[0] instanceof Location ) {
this.x = arguments[0].x;
this.y = arguments[0].y;
this.z = arguments[0].z;
this.dir = _getDirFromRotation(arguments[0].yaw );
this.world = arguments[0].world;
}else if (typeof arguments[0] === "string"){
} else if ( typeof arguments[0] === 'string' ) {
var coords = this._checkpoints[arguments[0]];
if ( coords ) {
this.x = coords.x;
@ -867,67 +879,79 @@ Drone.extend('move', function() {
this.z = arguments[2];
case 2:
this.y = arguments[1];
case 1:n
case 1:
this.x = arguments[0];
}
}
} );
Drone.extend( 'turn', function ( n ) {
if (typeof n == "undefined")
if ( typeof n == 'undefined' ) {
n = 1;
}
this.dir += n;
this.dir %=4;
} );
Drone.extend( 'right', function( n ) {
if (typeof n == "undefined")
if ( typeof n == 'undefined' ) {
n = 1;
}
_movements[ this.dir ].right( this, n );
});
Drone.extend( 'left', function( n ) {
if (typeof n == "undefined")
if ( typeof n == 'undefined') {
n = 1;
}
_movements[ this.dir ].left( this, n );
});
Drone.extend( 'fwd', function( n ) {
if (typeof n == "undefined")
if ( typeof n == 'undefined' ) {
n = 1;
}
_movements[ this.dir ].fwd( this, n );
});
Drone.extend( 'back', function( n ) {
if (typeof n == "undefined")
if ( typeof n == 'undefined' ) {
n = 1;
}
_movements[ this.dir ].back( this, n );
});
Drone.extend( 'up', function( n ) {
if (typeof n == "undefined")
if ( typeof n == 'undefined' ) {
n = 1;
}
this.y+= n;
});
Drone.extend( 'down', function( n ) {
if (typeof n == "undefined")
if ( typeof n == 'undefined' ) {
n = 1;
}
this.y-= n;
});
//
// position
//
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
//
Drone.extend( 'sign', function( message, block ) {
if (message.constructor == Array){
}else{
if ( message.constructor != Array ) {
message = [message];
}
var bm = this._getBlockIdAndMeta( block );
block = bm[0];
var meta = bm[1];
if ( block != 63 && block != 68 ) {
print("ERROR: Invalid block id for use in signs");
print('ERROR: Invalid block id for use in signs');
return;
}
if ( block == 68 ) {
@ -942,6 +966,7 @@ Drone.extend('sign',function(message,block){
this.fwd();
}
});
Drone.prototype.cuboida = function(/* Array */ blocks, w, h, d ) {
var properBlocks = [];
var len = blocks.length;
@ -949,16 +974,17 @@ Drone.prototype.cuboida = function(/* Array */ blocks,w,h,d){
var bm = this._getBlockIdAndMeta( blocks[ i ] );
properBlocks.push( [ bm[0], bm[1] ] );
}
if (typeof h == "undefined")
if ( typeof h == 'undefined' ) {
h = 1;
if (typeof d == "undefined")
}
if ( typeof d == 'undefined' ) {
d = 1;
if (typeof w == "undefined")
}
if ( typeof w == 'undefined' ) {
w = 1;
}
var that = this;
var dir = this.dir;
var pl = org.bukkit.entity.Player;
var cs = org.bukkit.command.BlockCommandSender;
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 ) {
if (typeof h == "undefined")
if ( typeof h == 'undefined' ) {
h = 1;
if (typeof d == "undefined")
}
if ( typeof d == 'undefined' ) {
d = 1;
if (typeof w == "undefined")
}
if ( typeof w == 'undefined' ) {
w = 1;
}
var that = this;
var dir = this.dir;
@ -1005,7 +1034,6 @@ Drone.prototype.cuboidX = function(blockType, meta, w, h, d){
var widthFunc = function( ) {
_traverseHeight( that, h, heightFunc );
};
_traverse[dir].width( that, w, widthFunc );
return this;
@ -1015,6 +1043,7 @@ Drone.prototype.cuboid = function(block,w,h,d){
var bm = this._getBlockIdAndMeta( block );
return this.cuboidX( bm[0], bm[1], w, h, d );
};
Drone.prototype.cuboid0 = function( block, w, h, d ) {
this.chkpt( 'start_point' );
@ -1029,16 +1058,21 @@ Drone.prototype.cuboid0 = function(block,w,h,d){
return this.move( 'start_point' );
};
Drone.extend( 'door', function( door ) {
if (typeof door == "undefined"){
if ( typeof door == 'undefined' ) {
door = 64;
} else {
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 ) {
if (typeof door == "undefined"){
if ( typeof door == 'undefined' ) {
door = 64;
} else {
door = 71;
@ -1057,7 +1091,8 @@ Drone.PLAYER_STAIRS_FACING = [0,2,1,3];
Drone.PLAYER_SIGN_FACING = [ 4, 2, 5, 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
,108: 45 // brick
,109: 98 // stone brick
@ -1077,8 +1112,7 @@ var _prism = function(block,w,d) {
var d2 = 0;
var middle = Math.floor( d/2 );
var uc = 0,dc = 0;
while (d2 < d)
{
while ( d2 < d ) {
var di = (d2 < middle?this.dir:(this.dir+2 )%4 );
var bd = block + ':' + Drone.PLAYER_STAIRS_FACING[di];
var putStep = true;
@ -1087,8 +1121,9 @@ var _prism = function(block,w,d) {
putStep = false;
}
}
if (putStep)
if ( putStep ) {
this.cuboid(bd,w );
}
if ( d2 < middle-1 ) {
this.up( );
uc++;
@ -1146,8 +1181,8 @@ Drone.extend('boxa',Drone.prototype.cuboida);
// show the Drone's position and direction
//
Drone.prototype.toString = function( ) {
var dirs = ["east","south","west","north"];
return "x: " + this.x + " y: "+this.y + " z: " + this.z + " dir: " + this.dir + " "+dirs[this.dir];
var dirs = ['east','south','west','north'];
return 'x: ' + this.x + ' y: '+this.y + ' z: ' + this.z + ' dir: ' + this.dir + ' '+dirs[this.dir];
};
Drone.prototype.debug = function( ) {
print(this.toString( ) );
@ -1183,13 +1218,8 @@ var _bresenham = function(x0,y0,radius, setPixel, quadrants){
if ( quadrants.topleft || quadrants.bottomleft )
setPixel(x0 - radius, y0 ); // quadrant II/III leftmost
while(x < y)
{
// ddF_x == 2 * x + 1;
// ddF_y == -2 * y;
// f == x*x + y*y - radius*radius + 2*x - y + 1;
if(f >= 0)
{
while ( x < y ) {
if(f >= 0 ) {
y--;
ddF_y += 2;
f += ddF_y;
@ -1236,7 +1266,7 @@ var _getStrokeDir = function(x,y){
var _arc2 = function( params ) {
var drone = params.drone;
var orientation = params.orientation?params.orientation:"horizontal";
var orientation = params.orientation?params.orientation:'horizontal';
var quadrants = params.quadrants?params.quadrants:{
topright:1,
topleft:2,
@ -1249,7 +1279,7 @@ var _arc2 = function( params ) {
drone.chkpt('arc2' );
var x0, y0, gotoxy,setPixel;
if (orientation == "horizontal"){
if ( orientation == 'horizontal' ) {
gotoxy = function( x,y ) { return drone.right(x ).fwd(y );};
drone.right(radius ).fwd(radius ).chkpt('center' );
switch ( drone.dir ) {
@ -1438,8 +1468,7 @@ var _paste = function(name)
//
// need to adjust blocks which face a direction
//
switch (cb)
{
switch ( cb ) {
//
// doors
//
@ -1684,20 +1713,19 @@ Drone.extend('rand',function(dist,w,h,d){
this.boxa(randomized,w,h,d );
} );
var _trees = {
oak: org.bukkit.TreeType.BIG_TREE ,
birch: org.bukkit.TreeType.BIRCH ,
jungle: org.bukkit.TreeType.JUNGLE,
spruce: org.bukkit.TreeType.REDWOOD
oak: TreeType.BIG_TREE ,
birch: TreeType.BIRCH ,
jungle: TreeType.JUNGLE,
spruce: TreeType.REDWOOD
};
for (var p in _trees)
{
for ( var p in _trees ) {
Drone.extend(p, function( v ) {
return function( ) {
var block = this.world.getBlockAt(this.x,this.y,this.z );
if ( block.typeId == 2 ) {
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 );
if ( block.typeId == 2 ) {
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.
***/
Drone.extend('sphere', function(block,radius)
{
var lastRadius = radius;
var slices = [[radius,0]];
var diameter = radius*2;
var bm = this._getBlockIdAndMeta(block);
Drone.extend( 'sphere', function( block, radius ) {
var lastRadius = radius,
slices = [ [ radius , 0 ] ],
diameter = radius * 2,
bm = this._getBlockIdAndMeta( block ),
r2 = radius * radius,
i = 0,
newRadius,
yOffset,
sr,
sh,
v,
h;
var r2 = radius*radius;
for (var i = 0; i <= radius;i++){
var newRadius = Math.round(Math.sqrt(r2 - i*i));
if (newRadius == lastRadius)
for ( i = 0; i <= radius; i++ ) {
newRadius = Math.round( Math.sqrt( r2 - i * i ) );
if ( newRadius == lastRadius ) {
slices[ slices.length - 1 ][ 1 ]++;
else
} else {
slices.push( [ newRadius , 1 ] );
}
lastRadius = newRadius;
}
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] } )
.down( radius - slices[0][1] );
var yOffset = -1;
for (var i = 1; i < slices.length;i++)
{
yOffset = -1;
for ( i = 1; i < slices.length; i++ ) {
yOffset += slices[i-1][1];
var sr = slices[i][0];
var sh = slices[i][1];
var v = radius + yOffset, h = radius-sr;
sr = slices[i][0];
sh = slices[i][1];
v = radius + yOffset;
h = radius - sr;
// 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] } )
.left(h).back(h).down(v);
.left( h )
.back( h )
.down( v );
// southern hemisphere
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] } )
.left(h).back(h). down(v);
.left( h )
.back( h )
.down( v );
}
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)
{
/*
this.sphere(block,radius)
.fwd().right().up()
.sphere(0,radius-1)
.back().left().down();
var lastRadius = radius,
slices = [ [ radius, 0 ] ],
diameter = radius * 2,
bm = this._getBlockIdAndMeta( block ),
r2 = radius*radius,
i,
newRadius,
sr,
sh,
v,
h,
len,
yOffset;
*/
var lastRadius = radius;
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)
for ( i = 0; i <= radius; i++ ) {
newRadius = Math.round( Math.sqrt( r2 - i * i ) );
if ( newRadius == lastRadius ) {
slices[ slices.length - 1 ][ 1 ]++;
else
} else {
slices.push( [ newRadius, 1 ] );
}
lastRadius = newRadius;
}
this.chkpt( 'sphere0' );
//
// mid section
//
//.cylinder(block,radius,(slices[0][1]*2)-1,{blockType: bm[0],meta: bm[1]})
this.up( radius - slices[0][1] )
.arc({ blockType: bm[0],
meta: bm[1],
@ -125,14 +140,14 @@ Drone.extend('sphere0', function(block,radius)
})
.down( radius - slices[0][1] );
var yOffset = -1;
var len = slices.length;
for (var i = 1; i < len;i++)
{
yOffset = -1;
len = slices.length;
for ( i = 1; i < len; i++ ) {
yOffset += slices[i-1][1];
var sr = slices[i][0];
var sh = slices[i][1];
var v = radius + yOffset, h = radius-sr;
sr = slices[i][0];
sh = slices[i][1];
v = radius + yOffset;
h = radius-sr;
// northern hemisphere
// .cylinder(block,sr,sh,{blockType: bm[0],meta: bm[1]})
this.up( v ).fwd( h ).right( h )
@ -148,7 +163,6 @@ Drone.extend('sphere0', function(block,radius)
// southern hemisphere
v = radius - ( yOffset + sh + 1 );
//.cylinder(block,sr,sh,{blockType: bm[0],meta: bm[1]})
this.up( v ).fwd( h ).right( h )
.arc({
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 ) {
var lastRadius = radius;
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)
var lastRadius = radius,
slices = [ [ radius, 0 ] ],
diameter = radius * 2,
bm = this._getBlockIdAndMeta(block),
r2 = radius * radius,
i = 0,
newRadius;
for ( i = 0; i <= radius; i++ ) {
newRadius = Math.round( Math.sqrt( r2 - i * i ) );
if ( newRadius == lastRadius ) {
slices[ slices.length - 1 ][ 1 ]++;
else
} else {
slices.push( [ newRadius, 1 ] );
}
lastRadius = newRadius;
}
this.chkpt( 'hsphere' );
//
// mid section
//
if (northSouth == "north"){
if ( northSouth == 'north' ) {
this.cylinder( block, radius, slices[0][1], { blockType: bm[0], meta: bm[1] } );
} else {
this.up( radius - slices[0][1] )
@ -213,13 +229,12 @@ Drone.extend('hemisphere', function(block,radius, northSouth){
}
var yOffset = -1;
for (var i = 1; i < slices.length;i++)
{
for ( i = 1; i < slices.length; i++ ) {
yOffset += slices[i-1][1];
var sr = slices[i][0];
var sh = slices[i][1];
var v = yOffset, h = radius-sr;
if (northSouth == "north") {
if ( northSouth == 'north' ) {
// northern hemisphere
this.up( v ).fwd( h ).right( h )
.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' );
});
/************************************************************************
### 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 ) {
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 )
.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 ) {
var playerName = parameters[0];
var recipient = utils.player( playerName );
if (recipient)
if ( recipient ) {
greetings.hello( recipient );
else
} else {
sender.sendMessage( 'Player ' + playerName + ' not found.' );
}
});
***/
@ -49,8 +50,9 @@ var greetings = require('./example-1-hello-module');
command( 'hello-byname', function( parameters, sender ) {
var playerName = parameters[0];
var recipient = utils.player( playerName );
if (recipient)
if ( recipient ) {
greetings.hello( recipient );
else
} else {
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.
***/
var utils = require('utils');
var _store = {
var utils = require('utils'),
TeleportCause = org.bukkit.event.player.PlayerTeleportEvent.TeleportCause,
_store = {
houses: { },
openHouses: { },
invites: { }
};
/*
*/
var homes = plugin("homes", {
var homes = plugin( 'homes', {
help: function( ) {
return [
/* basic functions */
"/jsp home : Return to your own home",
"/jsp home <player> : Go to player's home",
"/jsp home set : Set your current location as home",
"/jsp home delete : Delete your home location",
'/jsp home : Return to your own home',
'/jsp home <player> : Go to player home',
'/jsp home set : Set your current location as home',
'/jsp home delete : Delete your home location',
/* social */
"/jsp home list : List homes you can visit",
"/jsp home ilist : List players who can visit your home",
"/jsp home invite <player> : Invite <player> to your home",
"/jsp home uninvite <player> : Uninvite <player> to your home",
"/jsp home public : Open your home to all players",
"/jsp home private : Make your home private",
'/jsp home list : List homes you can visit',
'/jsp home ilist : List players who can visit your home',
'/jsp home invite <player> : Invite <player> to your home',
'/jsp home uninvite <player> : Uninvite <player> to your home',
'/jsp home public : Open your home to all players',
'/jsp home private : Make your home private',
/* administration */
"/jsp home listall : Show all houses (ops only)",
"/jsp home clear <player> : Clears player's home location (ops only)"
'/jsp home listall : Show all houses (ops only)',
'/jsp home clear <player> : Clears player home location (ops only)'
];
},
/* ========================================================================
@ -94,43 +96,54 @@ var homes = plugin("homes", {
======================================================================== */
go: function( guest, host ) {
if (typeof host == "undefined")
var loc,
homeLoc;
if ( typeof host == 'undefined' ) {
host = guest;
}
guest = utils.player( guest );
host = utils.player( host );
var loc = _store.houses[host.name];
loc = _store.houses[ host.name ];
if ( !loc ) {
guest.sendMessage(host.name + " has no home");
guest.sendMessage( host.name + ' has no home' );
return;
}
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;
}
var teleportCause = org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
var homeLoc = utils.locationFromJSON(loc);
guest.teleport(homeLoc, teleportCause.PLUGIN);
homeLoc = utils.locationFromJSON( loc );
guest.teleport(homeLoc, TeleportCause.PLUGIN);
},
/*
determine whether a guest is allow visit a host's home
*/
_canVisit: function( guest, host ) {
if (guest == host)
var invitations,
i;
if ( guest == host ) {
return true;
if (_store.openHouses[host.name])
}
if ( _store.openHouses[ host.name ] ) {
return true;
var invitations = _store.invites[host.name];
if (invitations)
for (var i = 0;i < invitations.length;i++)
if (invitations[i] == guest.name)
}
invitations = _store.invites[ host.name ];
if ( invitations ) {
for ( i = 0; i < invitations.length; i++ ) {
if ( invitations[i] == guest.name ) {
return true;
}
}
}
return false;
},
set: function( player ) {
player = utils.player( player );
var loc = player.location;
_store.houses[player.name] = utils.locationToJSON( loc );
},
remove: function( player ) {
player = utils.player( player );
delete _store.houses[ player.name ];
@ -143,36 +156,48 @@ var homes = plugin("homes", {
list homes which the player can visit
*/
list: function( player ) {
var result = [];
for (var ohp in _store.openHouses)
var result = [],
ohp,
host,
guests,
i;
for ( ohp in _store.openHouses ) {
result.push(ohp);
}
player = utils.player(player);
for (var host in _store.invites){
var guests = _store.invites[host];
for (var i = 0;i < guests.length; i++)
if (guests[i] == player.name)
for ( host in _store.invites ) {
guests = _store.invites[host];
for ( i = 0; i < guests.length; i++ ) {
if ( guests[i] == player.name ) {
result.push(host);
}
}
}
return result;
},
/*
list who can visit the player's home
list who can visit the player home
*/
ilist: function( player ) {
var result = [],
onlinePlayers,
i;
player = utils.player( player );
var result = [];
// if home is public - all players
if ( _store.openHouses[player.name] ) {
var online = org.bukkit.Bukkit.getOnlinePlayers();
for (var i = 0;i < online.length; i++)
if (online[i].name != player.name)
result.push(online[i].name);
onlinePlayers = org.bukkit.Bukkit.getOnlinePlayers();
for ( i = 0; i < onlinePlayers.length; i++ ) {
if ( onlinePlayers[i].name != player.name) {
result.push( onlinePlayers[i].name );
}
}
} else {
if (_store.invites[player.name])
if ( _store.invites[player.name] ) {
result = _store.invites[ player.name ];
else
} else {
result = [];
}
}
return result;
},
/*
@ -182,39 +207,48 @@ var homes = plugin("homes", {
host = utils.player( host );
guest = utils.player( guest );
var invitations = [];
if (_store.invites[host.name])
if ( _store.invites[host.name] ) {
invitations = _store.invites[host.name];
}
invitations.push( guest.name );
_store.invites[host.name] = invitations;
guest.sendMessage(host.name + " has invited you to their home.");
guest.sendMessage("type '/jsp home " + host.name + "' to accept");
guest.sendMessage( host.name + ' has invited you to their home.' );
guest.sendMessage( 'type "/jsp home ' + host.name + '" to accept' );
},
/*
Uninvite someone to the home
*/
uninvite: function( host, guest ) {
var invitations,
revisedInvites,
i;
host = utils.player( host );
guest = utils.player( guest );
var invitations = _store.invites[host.name];
if (!invitations)
invitations = _store.invites[ host.name ];
if ( !invitations ) {
return;
var revisedInvites = [];
for (var i =0;i < invitations.length; i++)
if (invitations[i] != guest.name)
}
revisedInvites = [];
for ( i = 0; i < invitations.length; i++ ) {
if ( invitations[i] != guest.name ) {
revisedInvites.push( invitations[i] );
}
}
_store.invites[host.name] = revisedInvites;
},
/*
make the player's house public
make the player house public
*/
open: function( player, optionalMsg ) {
player = utils.player( player );
_store.openHouses[ player.name ] = true;
if (typeof optionalMsg != "undefined")
if ( typeof optionalMsg != 'undefined' ) {
__plugin.server.broadcastMessage( optionalMsg );
}
},
/*
make the player's house private
make the player house private
*/
close: function( player ) {
player = utils.player( player );
@ -225,10 +259,12 @@ var homes = plugin("homes", {
======================================================================== */
listall: function( ) {
var result = [];
for (var home in _store.houses)
for ( var home in _store.houses ) {
result.push(home);
}
return result;
},
clear: function( player ) {
player = utils.player( player );
delete _store.houses[ player.name ];
@ -243,96 +279,124 @@ exports.homes = homes;
define a set of command options that can be used by players
*/
var options = {
'set': function(params, sender){ homes.set(sender); },
'delete': function(params, sender ){ homes.remove(sender);},
'help': function(params, sender){ sender.sendMessage(homes.help());},
'set': function( params, sender ) {
homes.set( sender );
},
'delete': function( params, sender ) {
homes.remove( sender );
},
'help': function( params, sender ) {
sender.sendMessage( homes.help() );
},
'list': function( params, sender ) {
var visitable = homes.list();
if ( visitable.length == 0 ) {
sender.sendMessage("There are no homes to visit");
sender.sendMessage( 'There are no homes to visit' );
return;
} else {
sender.sendMessage([
"You can visit any of these " + visitable.length + " homes"
,visitable.join(", ")
'You can visit any of these ' + visitable.length + ' homes'
,visitable.join(', ')
]);
}
},
'ilist': function( params, sender ) {
var potentialVisitors = homes.ilist();
if (potentialVisitors.length == 0)
sender.sendMessage("No one can visit your home");
else
if ( potentialVisitors.length == 0 ) {
sender.sendMessage('No one can visit your home');
} else {
sender.sendMessage([
"These " + potentialVisitors.length + "players can visit your home",
potentialVisitors.join(", ")]);
'These ' + potentialVisitors.length + 'players can visit your home',
potentialVisitors.join(', ')]);
}
},
'invite': function( params, sender ) {
if ( params.length == 1 ) {
sender.sendMessage("You must provide a player's name");
sender.sendMessage( 'You must provide a player name' );
return;
}
var playerName = params[1];
var guest = utils.player( playerName );
if (!guest)
sender.sendMessage(playerName + " is not here");
else
if ( !guest ) {
sender.sendMessage( playerName + ' is not here' );
} else {
homes.invite( sender, guest );
}
},
'uninvite': function( params, sender ) {
if ( params.length == 1 ) {
sender.sendMessage("You must provide a player's name");
sender.sendMessage( 'You must provide a player name' );
return;
}
var playerName = params[1];
var guest = utils.player( playerName );
if (!guest)
sender.sendMessage(playerName + " is not here");
else
if ( !guest ) {
sender.sendMessage( playerName + ' is not here' );
} else {
homes.uninvite( sender, guest );
}
},
'public': function( params, sender ) {
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 ) {
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 ) {
if (!sender.isOp())
sender.sendMessage("Only operators can do this");
else
sender.sendMessage(homes.listall().join(", "));
if ( !sender.isOp() ) {
sender.sendMessage( 'Only operators can do this' );
} else {
sender.sendMessage( homes.listall().join(', ') );
}
},
'clear': function( params, sender ) {
if (!sender.isOp())
sender.sendMessage("Only operators can do this");
else
if ( !sender.isOp() ) {
sender.sendMessage( 'Only operators can do this' );
} else {
homes.clear( params[1], sender );
}
}
};
var optionList = [];
for (var o in options)
for ( var o in options ) {
optionList.push(o);
}
/*
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 ) {
homes.go( sender, sender );
return;
}
var option = options[params[0]];
if (option)
option = options[ params[0] ];
if ( option ) {
option( params, sender );
else{
var host = utils.player(params[0]);
if (!host)
sender.sendMessage(params[0] + " is not here");
else
} else {
host = utils.player( params[0] );
if ( !host ) {
sender.sendMessage( params[0] + ' is not here' );
} else {
homes.go( sender, host );
}
}
}, 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.
***/
var Prompt = org.bukkit.conversations.Prompt,
ConversationFactory = org.bukkit.conversations.ConversationFactory,
ConversationPrefix = org.bukkit.conversations.ConversationPrefix;
var sb = function( cmd ) {
org.bukkit.Bukkit.dispatchCommand(server.consoleSender, 'scoreboard ' + cmd)
org.bukkit.Bukkit.dispatchCommand( server.consoleSender, 'scoreboard ' + cmd ) ;
};
exports.Game_NumberGuess = {
@ -29,50 +32,56 @@ exports.Game_NumberGuess = {
sb( 'players set ' + sender.name + ' NumberGuess ' + guesses );
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 prompt = new Prompt()
{
var prompt = new Prompt( ) {
getPromptText: function( ctx ) {
var hint = "";
var h = ctx.getSessionData("hint");
var hint = '';
var h = ctx.getSessionData( 'hint' );
if ( 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)
{
s = s.replace(/^[^0-9]+/,""); // strip leading non-numeric characters (e.g. '/' )
acceptInput: function( ctx, s ) {
s = s.replace( /^[^0-9]+/, '' ); // strip leading non-numeric characters (e.g. '/' )
s = parseInt( s );
if ( s == number ) {
setTimeout(function( ) {
ctx.forWhom.sendRawMessage("You guessed Correct!");
ctx.forWhom.sendRawMessage( 'You guessed Correct!' );
sb( 'objectives remove NumberGuess' );
}, 100 );
return null;
} else {
if (s < number)
ctx.setSessionData("hint","too low\n");
if (s > number)
ctx.setSessionData("hint","too high\n");
if ( s < number ) {
ctx.setSessionData( 'hint', 'too low\n' );
}
if ( s > number ) {
ctx.setSessionData( 'hint', 'too high\n' );
}
guesses++;
sb( 'players set ' + sender.name + ' NumberGuess ' + guesses );
return prompt;
}
},
blocksForInput: function(ctx){ return true; }
};
var cf = new ConversationFactory(__plugin);
var conv = cf.withModality(true)
.withFirstPrompt(prompt)
.withPrefix(new ConversationPrefix(){ getPrefix: function(ctx){ return "[1-10] ";} })
.buildConversation(sender);
conv.begin();
blocksForInput: function( ctx ) {
return true;
}
};
var convPrefix = new ConversationPrefix( ) {
getPrefix: function( ctx ) {
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 i,
teamName,
team,
player;
// don't let game start if already in progress (wait for game to finish)
if ( gameState.inProgress ) {
return;
@ -52,17 +63,17 @@ var _startGame = function(gameState){
gameState.duration = gameState.originalDuration;
// put all players in survival mode and give them each 200 snowballs
// 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 ] );
}
for (var teamName in gameState.teams)
{
for ( teamName in gameState.teams ) {
gameState.teamScores[teamName] = 0;
var team = gameState.teams[teamName];
for (var i = 0;i < team.length;i++) {
var player = server.getPlayer(team[i]);
team = gameState.teams[ teamName ];
for ( i = 0; i < team.length; i++ ) {
player = server.getPlayer( team[i] );
gameState.savedModes[ player.name ] = player.gameMode;
player.gameMode = org.bukkit.GameMode.SURVIVAL;
player.gameMode = GameMode.SURVIVAL;
player.inventory.addItem( gameState.ammo );
}
}
@ -71,30 +82,37 @@ var _startGame = function(gameState){
end the game
*/
var _endGame = function( gameState ) {
var scores = [];
var scores = [],
leaderBoard = [],
tn,
i,
teamName,
team,
player,
handlerList;
var leaderBoard = [];
for (var tn in gameState.teamScores){
leaderBoard = [];
for ( tn in gameState.teamScores){
leaderBoard.push([tn,gameState.teamScores[tn]]);
}
leaderBoard.sort(function(a,b){ return b[1] - a[1];});
for (var i = 0;i < leaderBoard.length; i++){
scores.push("Team " + leaderBoard[i][0] + " scored " + leaderBoard[i][1]);
for ( i = 0; i < leaderBoard.length; i++ ) {
scores.push( 'Team ' + leaderBoard[i][0] + ' scored ' + leaderBoard[i][1] );
}
for (var teamName in gameState.teams) {
var team = gameState.teams[teamName];
for (var i = 0;i < team.length;i++) {
for ( teamName in gameState.teams ) {
team = gameState.teams[teamName];
for ( i = 0; i < team.length; i++ ) {
// 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.inventory.removeItem( gameState.ammo );
player.sendMessage("GAME OVER.");
player.sendMessage( 'GAME OVER.' );
player.sendMessage( scores );
}
}
var handlerList = org.bukkit.event.entity.EntityDamageByEntityEvent.getHandlerList();
handlerList = EntityDamageByEntityEvent.getHandlerList();
handlerList.unregister( gameState.listener );
gameState.inProgress = false;
};
@ -102,20 +120,26 @@ var _endGame = function(gameState){
get the team the player belongs to
*/
var _getTeam = function( player, pteams ) {
for (var teamName in pteams) {
var team = pteams[teamName];
for (var i = 0;i < team.length; i++)
if (team[i] == player.name)
var teamName,
team,
i;
for ( teamName in pteams ) {
team = pteams[ teamName ];
for ( i = 0; i < team.length; i++ ) {
if ( team[i] == player.name ) {
return teamName;
}
}
}
return null;
};
/*
construct a new game
*/
var createGame = function( duration, teams ) {
var _snowBalls = new org.bukkit.inventory.ItemStack(org.bukkit.Material.SNOW_BALL, 64);
var players,
i,
_snowBalls = new ItemStack( Material.SNOW_BALL, 64 );
var _gameState = {
teams: teams,
@ -127,16 +151,16 @@ var createGame = function(duration, teams) {
savedModes: {},
ammo: [ _snowBalls ]
};
if (typeof duration == "undefined"){
if ( typeof duration == 'undefined' ) {
duration = 60;
}
if (typeof teams == "undefined"){
if ( typeof teams == 'undefined' ) {
/*
wph 20130511 use all players
*/
teams = [];
var players = server.onlinePlayers;
for (var i = 0;i < players.length; i++){
players = server.onlinePlayers;
for ( i = 0; i < players.length; i++ ) {
teams.push( players[i].name );
}
}
@ -146,24 +170,28 @@ var createGame = function(duration, teams) {
//
if ( teams instanceof Array ) {
_gameState.teams = {};
for (var i = 0;i < teams.length; i++)
for ( i = 0;i < teams.length; i++ ) {
_gameState.teams[ teams[i] ] = [ teams[i] ];
}
}
/*
this function is called every time a player is damaged by another entity/player
*/
var _onSnowballHit = function( l, event ) {
var snowball = event.damager;
if (!snowball || !(snowball instanceof org.bukkit.entity.Snowball))
if ( !snowball || !( snowball instanceof Snowball ) ) {
return;
}
var throwersTeam = _getTeam( snowball.shooter, _gameState.teams );
var damageeTeam = _getTeam( event.entity, _gameState.teams);
if (!throwersTeam || !damageeTeam)
if ( !throwersTeam || !damageeTeam ) {
return; // thrower/damagee wasn't in game
if (throwersTeam != damageeTeam)
}
if ( throwersTeam != damageeTeam ) {
_gameState.teamScores[ throwersTeam ]++;
else
} else {
_gameState.teamScores[ throwersTeam ]--;
}
};
return {
@ -171,8 +199,9 @@ var createGame = function(duration, teams) {
_startGame( _gameState );
_gameState.listener = events.on('entity.EntityDamageByEntityEvent',_onSnowballHit);
new java.lang.Thread( function( ) {
while (_gameState.duration--)
while ( _gameState.duration-- ) {
java.lang.Thread.sleep( 1000 ); // sleep 1,000 millisecs (1 second)
}
_endGame(_gameState);
} ).start( );
}

View file

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

View file

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