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

@ -787,7 +787,7 @@ To call the fireworks.firework() function directly, you must provide a
location. For example... location. For example...
/js var fireworks = require('fireworks'); /js var fireworks = require('fireworks');
/js fireworks.firework(self.location); /js fireworks.firework( self.location );
![firework example](img/firework.png) ![firework example](img/firework.png)
@ -829,11 +829,14 @@ The following example illustrates how to use http.request to make a request to a
... The following example illustrates a more complex use-case POSTing parameters to a CGI process on a server... ... The following example illustrates a more complex use-case POSTing parameters to a CGI process on a server...
var http = require('./http/request'); var http = require('./http/request');
http.request({ url: "http://pixenate.com/pixenate/pxn8.pl", http.request(
method: "POST", {
params: {script: "[]"} url: 'http://pixenate.com/pixenate/pxn8.pl',
}, function( responseCode, responseBody){ method: 'POST',
var jsObj = eval("(" + responseBody + ")"); params: {script: '[]'}
},
function( responseCode, responseBody ) {
var jsObj = eval('(' + responseBody + ')');
}); });
## sc-mqtt module ## sc-mqtt module
@ -870,24 +873,24 @@ present in the CraftBukkit classpath. To use this module, you should
// create a new client // create a new client
var client = mqtt.client('tcp://localhost:1883', 'uniqueClientId'); var client = mqtt.client( 'tcp://localhost:1883', 'uniqueClientId' );
// connect to the broker // connect to the broker
client.connect({ keepAliveInterval: 15 }); client.connect( { keepAliveInterval: 15 } );
// publish a message to the broker // publish a message to the broker
client.publish('minecraft','loaded'); client.publish( 'minecraft', 'loaded' );
// subscribe to messages on 'arduino' topic // subscribe to messages on 'arduino' topic
client.subscribe('arduino'); client.subscribe( 'arduino' );
// do something when an incoming message arrives... // do something when an incoming message arrives...
client.onMessageArrived(function(topic, message){ client.onMessageArrived( function( topic, message ) {
console.log('Message arrived: topic=' + topic + ', message=' + message); console.log( 'Message arrived: topic=' + topic + ', message=' + message );
}); });
The `sc-mqtt` module provides a very simple minimal wrapper around the The `sc-mqtt` module provides a very simple minimal wrapper around the
@ -1023,7 +1026,7 @@ Example
------- -------
/js var boldGoldText = "Hello World".bold().gold(); /js var boldGoldText = "Hello World".bold().gold();
/js self.sendMessage(boldGoldText); /js self.sendMessage( boldGoldText );
<p style="color:gold;font-weight:bold">Hello World</p> <p style="color:gold;font-weight:bold">Hello World</p>
@ -1173,7 +1176,7 @@ package for scheduling processing of arrays.
- object : Additional (optional) information passed into the foreach method. - object : Additional (optional) information passed into the foreach method.
- array : The entire array. - array : The entire array.
* object (optional) : An object which may be used by the callback. * context (optional) : An object which may be used by the callback.
* delay (optional, numeric) : If a delay is specified (in ticks - 20 * delay (optional, numeric) : If a delay is specified (in ticks - 20
ticks = 1 second), then the processing will be scheduled so that ticks = 1 second), then the processing will be scheduled so that
each item will be processed in turn with a delay between the completion of each each item will be processed in turn with a delay between the completion of each
@ -1273,8 +1276,8 @@ To warn players when night is approaching...
utils.at( '19:00', function() { utils.at( '19:00', function() {
utils.foreach( server.onlinePlayers, function(player){ utils.foreach( server.onlinePlayers, function( player ) {
player.chat('The night is dark and full of terrors!'); player.chat( 'The night is dark and full of terrors!' );
}); });
}); });
@ -1410,7 +1413,7 @@ Drones can be created in any of the following ways...
block is broken at the block's location you would do so like block is broken at the block's location you would do so like
this... this...
events.on('block.BlockBreakEvent',function(listener,event){ events.on('block.BlockBreakEvent',function( listener,event) {
var location = event.block.location; var location = event.block.location;
var drone = new Drone(location); var drone = new Drone(location);
// do more stuff with the drone here... // do more stuff with the drone here...
@ -1552,7 +1555,7 @@ Markers are created and returned to using the followng two methods...
// //
// the drone can now go off on a long excursion // the drone can now go off on a long excursion
// //
for (i = 0; i< 100; i++){ for ( i = 0; i< 100; i++) {
drone.fwd(12).box(6); drone.fwd(12).box(6);
} }
// //
@ -1624,11 +1627,11 @@ arc() takes a single parameter - an object with the following named properties..
* radius - The radius of the arc. * radius - The radius of the arc.
* blockType - The type of block to use - this is the block Id only (no meta). See [Data Values][dv]. * blockType - The type of block to use - this is the block Id only (no meta). See [Data Values][dv].
* meta - The metadata value. See [Data Values][dv]. * meta - The metadata value. See [Data Values][dv].
* orientation (default: 'horizontal') - the orientation of the arc - can be 'vertical' or 'horizontal'. * orientation (default: 'horizontal' ) - the orientation of the arc - can be 'vertical' or 'horizontal'.
* stack (default: 1) - the height or length of the arc (depending on * stack (default: 1 ) - the height or length of the arc (depending on
the orientation - if orientation is horizontal then this parameter the orientation - if orientation is horizontal then this parameter
refers to the height, if vertical then it refers to the length). refers to the height, if vertical then it refers to the length ).
* strokeWidth (default: 1) - the width of the stroke (how many * strokeWidth (default: 1 ) - the width of the stroke (how many
blocks) - if drawing nested arcs it's usually a good idea to set blocks) - if drawing nested arcs it's usually a good idea to set
strokeWidth to at least 2 so that there are no gaps between each strokeWidth to at least 2 so that there are no gaps between each
arc. The arc method uses a [bresenham algorithm][bres] to plot arc. The arc method uses a [bresenham algorithm][bres] to plot
@ -1652,7 +1655,7 @@ To draw a 1/4 circle (top right quadrant only) with a radius of 10 and stroke wi
orientation: 'vertical', orientation: 'vertical',
stack: 1, stack: 1,
fill: false fill: false
}); } );
![arc example 1](img/arcex1.png) ![arc example 1](img/arcex1.png)
@ -1715,7 +1718,7 @@ To create a free-standing sign...
... to create a wall mounted sign... ... to create a wall mounted sign...
drone.sign(["Welcome","to","Scriptopia"], 68); drone.sign(["Welcome","to","Scriptopia"], 68 );
![wall sign](img/signex2.png) ![wall sign](img/signex2.png)
@ -1730,13 +1733,13 @@ To create a free-standing sign...
To create 4 trees in a row, point the cross-hairs at the ground then type `/js ` and ... To create 4 trees in a row, point the cross-hairs at the ground then type `/js ` and ...
up().oak().right(8).spruce().right(8).birch().right(8).jungle(); up( ).oak( ).right(8 ).spruce( ).right(8 ).birch( ).right(8 ).jungle( );
Trees won't always generate unless the conditions are right. You Trees won't always generate unless the conditions are right. You
should use the tree methods when the drone is directly above the should use the tree methods when the drone is directly above the
ground. Trees will usually grow if the drone's current location is ground. Trees will usually grow if the drone's current location is
occupied by Air and is directly above an area of grass (That is why occupied by Air and is directly above an area of grass (That is why
the `up()` method is called first). the `up( )` method is called first).
![tree example](img/treeex1.png) ![tree example](img/treeex1.png)
@ -1795,7 +1798,7 @@ pasting the copied area elsewhere...
#### Example #### Example
drone.copy('somethingCool',10,5,10).right(12).paste('somethingCool'); drone.copy('somethingCool',10,5,10 ).right(12 ).paste('somethingCool' );
### Drone.paste() method ### Drone.paste() method
@ -1807,9 +1810,9 @@ To copy a 10x5x10 area (using the drone's coordinates as the starting
point) into memory. the copied area can be referenced using the name point) into memory. the copied area can be referenced using the name
'somethingCool'. The drone moves 12 blocks right then pastes the copy. 'somethingCool'. The drone moves 12 blocks right then pastes the copy.
drone.copy('somethingCool',10,5,10) drone.copy('somethingCool',10,5,10 )
.right(12) .right(12 )
.paste('somethingCool'); .paste('somethingCool' );
### Chaining ### Chaining
@ -1866,9 +1869,9 @@ Use this method to add new methods (which also become chainable global functions
#### Example #### Example
// submitted by [edonaldson][edonaldson] // submitted by [edonaldson][edonaldson]
Drone.extend('pyramid', function(block,height){ Drone.extend('pyramid', function( block,height) {
this.chkpt('pyramid'); this.chkpt('pyramid');
for (var i = height; i > 0; i -= 2) { for ( var i = height; i > 0; i -= 2) {
this.box(block, i, 1, i).up().right().fwd(); this.box(block, i, 1, i).up().right().fwd();
} }
return this.move('pyramid'); return this.move('pyramid');
@ -1931,7 +1934,7 @@ Say you want to do the same thing over and over. You have a couple of options...
* You can use a for loop... * You can use a for loop...
d = new Drone(); for (var i =0;i < 4; i++){ d.cottage().right(8); } d = new Drone(); for ( var i =0;i < 4; i++) { d.cottage().right(8); }
While this will fit on the in-game prompt, it's awkward. You need to While this will fit on the in-game prompt, it's awkward. You need to
declare a new Drone object first, then write a for loop to create the declare a new Drone object first, then write a for loop to create the
@ -1940,7 +1943,7 @@ syntax for what should really be simple.
* You can use a while loop... * You can use a while loop...
d = new Drone(); var i=4; while (i--){ d.cottage().right(8); } d = new Drone(); var i=4; while (i--) { d.cottage().right(8); }
... which is slightly shorter but still too much syntax. Each of the ... which is slightly shorter but still too much syntax. Each of the
above statements is fine for creating a 1-dimensional array of above statements is fine for creating a 1-dimensional array of
@ -2218,9 +2221,9 @@ This example demonstrates adding and using parameters in commands.
This differs from example 3 in that the greeting can be changed from This differs from example 3 in that the greeting can be changed from
a fixed 'Hello ' to anything you like by passing a parameter. a fixed 'Hello ' to anything you like by passing a parameter.
command('hello-params', function (parameters, player) { command( 'hello-params', function ( parameters, player ) {
var salutation = parameters[0] ; var salutation = parameters[0] ;
player.sendMessage( salutation + ' ' + player.name); player.sendMessage( salutation + ' ' + player.name );
}); });
## Example Plugin #5 - Re-use - Using your own and others modules. ## Example Plugin #5 - Re-use - Using your own and others modules.
@ -2253,8 +2256,8 @@ this example, we use that module...
Source Code... Source Code...
var greetings = require('./example-1-hello-module'); var greetings = require('./example-1-hello-module');
command('hello-module', function( parameters, player ){ command( 'hello-module', function( parameters, player ) {
greetings.hello(player); greetings.hello( player );
}); });
## Example Plugin #6 - Re-use - Using 'utils' to get Player objects. ## Example Plugin #6 - Re-use - Using 'utils' to get Player objects.
@ -2290,13 +2293,14 @@ Source Code ...
var utils = require('utils'); var utils = require('utils');
var greetings = require('./example-1-hello-module'); var greetings = require('./example-1-hello-module');
command('hello-byname', function( parameters, sender ) { command( 'hello-byname', function( parameters, sender ) {
var playerName = parameters[0]; var playerName = parameters[0];
var recipient = utils.player(playerName); var recipient = utils.player( playerName );
if (recipient) if ( recipient ) {
greetings.hello(recipient); greetings.hello( recipient );
else } else {
sender.sendMessage('Player ' + playerName + ' not found.'); sender.sendMessage( 'Player ' + playerName + ' not found.' );
}
}); });
## Example Plugin #7 - Listening for events, Greet players when they join the game. ## Example Plugin #7 - Listening for events, Greet players when they join the game.
@ -2379,8 +2383,8 @@ cleaner and more readable. Similarly where you see a method like
[bksaf]: http://jd.bukkit.org/dev/apidocs/org/bukkit/entity/Player.html#setAllowFlight() [bksaf]: http://jd.bukkit.org/dev/apidocs/org/bukkit/entity/Player.html#setAllowFlight()
[bkapi]: http://jd.bukkit.org/dev/apidocs/ [bkapi]: http://jd.bukkit.org/dev/apidocs/
events.on('player.PlayerJoinEvent', function (listener, event){ events.on( 'player.PlayerJoinEvent', function( listener, event ) {
if (event.player.op) { if ( event.player.op ) {
event.player.sendMessage('Welcome to ' + __plugin); event.player.sendMessage('Welcome to ' + __plugin);
} }
}); });
@ -2506,11 +2510,11 @@ to every student in a Minecraft classroom environment.
To allow all players (and any players who connect to the server) to To allow all players (and any players who connect to the server) to
use the `js` and `jsp` commands... use the `js` and `jsp` commands...
/js classroom.allowScripting(true,self) /js classroom.allowScripting( true, self )
To disallow scripting (and prevent players who join the server from using the commands)... To disallow scripting (and prevent players who join the server from using the commands)...
/js classroom.allowScripting(false,self) /js classroom.allowScripting( false, self )
Only ops users can run the classroom.allowScripting() function - this is so that students Only ops users can run the classroom.allowScripting() function - this is so that students
don't try to bar themselves and each other from scripting. don't try to bar themselves and each other from scripting.

View file

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

View file

@ -35,35 +35,39 @@ ScriptCraft uses Java's [String.format()][strfmt] so any string substitution ide
[webcons]: https://developer.mozilla.org/en-US/docs/Web/API/console [webcons]: https://developer.mozilla.org/en-US/docs/Web/API/console
***/ ***/
var logger = __plugin.logger; var logger = __plugin.logger,
var argsToArray = function(args){ logMethodName = 'log(java.util.logging.Level,java.lang.String)';
var argsToArray = function( args ) {
var result = []; var result = [];
for (var i =0;i < args.length; i++) for ( var i =0; i < args.length; i++ ) {
result.push(args[i]); result.push(args[i]);
}
return result; return result;
} }
var log = function(level, restOfArgs){ var log = function( level, restOfArgs ) {
var args = argsToArray(restOfArgs); var args = argsToArray( restOfArgs );
if (args.length > 1){ if ( args.length > 1 ) {
var msg = java.lang.String.format(args[0],args.slice(1)); var msg = java.lang.String.format( args[0], args.slice(1) );
logger['log(java.util.logging.Level,java.lang.String)'](level,msg); logger[logMethodName]( level, msg );
}else{ } else {
logger['log(java.util.logging.Level,java.lang.String)'](level, args[0]); logger[logMethodName]( level, args[0] );
} }
}; };
var Level = java.util.logging.Level; var Level = java.util.logging.Level;
exports.log = function(){ exports.log = function( ) {
log(Level.INFO, arguments); log( Level.INFO, arguments );
}; };
exports.info = function(){ exports.info = function( ) {
log(Level.INFO, arguments); log( Level.INFO, arguments );
}
exports.warn = function(){
log(Level.WARNING, arguments);
}; };
exports.error = function(){
log(Level.SEVERE, 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 bkEvent = org.bukkit.event,
var bkEvtExecutor = org.bukkit.plugin.EventExecutor; bkEvtExecutor = org.bukkit.plugin.EventExecutor,
var bkRegListener = org.bukkit.plugin.RegisteredListener; bkRegListener = org.bukkit.plugin.RegisteredListener;
exports.on = function( exports.on = function(
/* String or java Class */ /* String or java Class */
@ -86,31 +86,33 @@ exports.on = function(
handler, handler,
/* (optional) String (HIGH, HIGHEST, LOW, LOWEST, NORMAL, MONITOR), */ /* (optional) String (HIGH, HIGHEST, LOW, LOWEST, NORMAL, MONITOR), */
priority ) { priority ) {
var handlerList,
listener = {},
eventExecutor;
if (typeof priority == "undefined"){ if ( typeof priority == 'undefined' ) {
priority = bkEvent.EventPriority.HIGHEST; priority = bkEvent.EventPriority.HIGHEST;
}else{ } else {
priority = bkEvent.EventPriority[priority]; priority = bkEvent.EventPriority[priority];
} }
if (typeof eventType == "string"){ if ( typeof eventType == 'string' ) {
/* /*
Nashorn doesn't support bracket notation for accessing packages. Nashorn doesn't support bracket notation for accessing packages.
E.g. java.net will work but java['net'] won't. E.g. java.net will work but java['net'] won't.
https://bugs.openjdk.java.net/browse/JDK-8031715 https://bugs.openjdk.java.net/browse/JDK-8031715
*/ */
if (typeof Java != 'undefined'){ if ( typeof Java != 'undefined' ) {
// nashorn environment // nashorn environment
eventType = Java.type('org.bukkit.event.' + eventType); eventType = Java.type( 'org.bukkit.event.' + eventType );
} else { } else {
eventType = eval('org.bukkit.event.' + eventType); eventType = eval( 'org.bukkit.event.' + eventType );
} }
} }
var handlerList = eventType.getHandlerList(); handlerList = eventType.getHandlerList( );
var listener = {}; eventExecutor = new bkEvtExecutor( ) {
var eventExecutor = new bkEvtExecutor(){ execute: function( l, e ) {
execute: function(l,e){ handler( listener.reg, e );
handler(listener.reg,e);
} }
}; };
/* /*
@ -121,7 +123,7 @@ exports.on = function(
The workaround is to make the ScriptCraftPlugin java class a Listener. The workaround is to make the ScriptCraftPlugin java class a Listener.
Should only unregister() registered plugins in ScriptCraft js code. Should only unregister() registered plugins in ScriptCraft js code.
*/ */
listener.reg = new bkRegListener( __plugin, eventExecutor, priority, __plugin, true); listener.reg = new bkRegListener( __plugin, eventExecutor, priority, __plugin, true );
handlerList.register(listener.reg); handlerList.register( listener.reg );
return listener.reg; return listener.reg;
}; };

View file

@ -1,33 +1,36 @@
module.exports = function($){ module.exports = function( $ ) {
// wph 20140105 trim not availabe in String on Mac OS. // wph 20140105 trim not availabe in String on Mac OS.
if (typeof String.prototype.trim == 'undefined'){ if ( typeof String.prototype.trim == 'undefined' ) {
String.prototype.trim = function(){ String.prototype.trim = function( ) {
return this.replace(/^\s+|\s+$/g,''); return this.replace( /^\s+|\s+$/g, '' );
}; };
} }
$.setTimeout = function( callback, delayInMillis){ $.setTimeout = function( callback, delayInMillis ) {
/* /*
javascript programmers familiar with setTimeout know that it expects javascript programmers familiar with setTimeout know that it expects
a delay in milliseconds. However, bukkit's scheduler expects a delay in ticks a delay in milliseconds. However, bukkit's scheduler expects a delay in ticks
(where 1 tick = 1/20th second) (where 1 tick = 1/20th second)
*/ */
var bukkitTask = server.scheduler.runTaskLater(__plugin, callback, delayInMillis/50); var bukkitTask = server.scheduler.runTaskLater( __plugin, callback, delayInMillis/50 );
return bukkitTask; return bukkitTask;
}; };
$.clearTimeout = function(bukkitTask){
$.clearTimeout = function( bukkitTask ) {
bukkitTask.cancel(); bukkitTask.cancel();
}; };
$.setInterval = function(callback, intervalInMillis){ $.setInterval = function( callback, intervalInMillis ) {
var delay = intervalInMillis/ 50; var delay = intervalInMillis/ 50;
var bukkitTask = server.scheduler.runTaskTimer(__plugin, callback, delay, delay); var bukkitTask = server.scheduler.runTaskTimer( __plugin, callback, delay, delay );
return bukkitTask; return bukkitTask;
}; };
$.clearInterval = function(bukkitTask){
$.clearInterval = function( bukkitTask ) {
bukkitTask.cancel(); bukkitTask.cancel();
}; };
}; };

View file

@ -1,36 +1,49 @@
var _dataDir = null,
_persistentData = {};
var _dataDir = null; module.exports = function( rootDir, $ ) {
var _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'); _dataDir = new java.io.File( rootDir, 'data' );
$.persist = function(name, data, write){ $.persist = function( name, data, write ) {
var i, dataFromFile; var i,
if (typeof data == 'undefined') dataFromFile;
if ( typeof data == 'undefined' ) {
data = {}; data = {};
if (typeof write == 'undefined') }
if ( typeof write == 'undefined' ) {
write = false; write = false;
if (!write){ }
dataFromFile = $.scload(_dataDir.canonicalPath + '/' + name + '-store.json'); if ( !write ) {
if (dataFromFile){ dataFromFile = _load( name );
for (i in dataFromFile){ if ( dataFromFile ) {
for ( i in dataFromFile ) {
data[i] = dataFromFile[i]; data[i] = dataFromFile[i];
} }
} }
}else{ } else {
// flush data to file // flush data to file
$.scsave(data, _dataDir.canonicalPath + '/' + name + '-store.json'); _save( name, data );
} }
_persistentData[name] = data; _persistentData[name] = data;
return data; return data;
}; };
/*
$.addUnloadHandler(function(){ persist on shutdown
for (var name in _persistentData){ */
var data = _persistentData[name]; $.addUnloadHandler( function( ) {
$.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'; 'use strict';
var console = require('./console'), var console = require('./console'),
File = java.io.File, File = java.io.File,
FileWriter = java.io.FileWriter, FileWriter = java.io.FileWriter,
@ -8,22 +9,22 @@ var console = require('./console'),
*/ */
var _plugins = {}; var _plugins = {};
var _plugin = function(/* String */ moduleName, /* Object */ moduleObject, isPersistent) var _plugin = function(/* String */ moduleName, /* Object */ moduleObject, isPersistent ) {
{
// //
// don't load plugin more than once // don't load plugin more than once
// //
if (typeof _plugins[moduleName] != 'undefined') if ( typeof _plugins[moduleName] != 'undefined' ) {
return _plugins[moduleName].module; return _plugins[moduleName].module;
}
var pluginData = {persistent: isPersistent, module: moduleObject}; var pluginData = { persistent: isPersistent, module: moduleObject };
if (typeof moduleObject.store == 'undefined') if ( typeof moduleObject.store == 'undefined' ) {
moduleObject.store = {}; moduleObject.store = {};
}
_plugins[moduleName] = pluginData; _plugins[moduleName] = pluginData;
if (isPersistent){ if ( isPersistent ) {
moduleObject.store = persist(moduleName, moduleObject.store); moduleObject.store = persist( moduleName, moduleObject.store );
} }
return moduleObject; return moduleObject;
}; };
@ -34,30 +35,31 @@ var scriptCraftDir = null;
var pluginDir = null; var pluginDir = null;
var dataDir = null; var dataDir = null;
exports.autoload = function(dir,logger) { exports.autoload = function( dir, logger ) {
scriptCraftDir = dir; scriptCraftDir = dir;
pluginDir = new File(dir, 'plugins'); pluginDir = new File( dir, 'plugins' );
dataDir = new File(dir, 'data'); dataDir = new File( dir, 'data' );
var _canonize = function(file){ var _canonize = function( file ) {
return '' + file.canonicalPath.replaceAll('\\\\','/'); return '' + file.canonicalPath.replaceAll('\\\\','/');
}; };
/* /*
recursively walk the given directory and return a list of all .js files recursively walk the given directory and return a list of all .js files
*/ */
var _listSourceFiles = function(store,dir) var _listSourceFiles = function( store, dir ) {
{ var files = dir.listFiles(),
var files = dir.listFiles(); file;
if (!files) if ( !files ) {
return; return;
for (var i = 0;i < files.length; i++) { }
var file = files[i]; for ( var i = 0; i < files.length; i++ ) {
if (file.isDirectory()){ file = files[i];
_listSourceFiles(store,file); if ( file.isDirectory( ) ) {
_listSourceFiles( store, file );
}else{ }else{
if ( file.canonicalPath.endsWith('.js') ){ if ( file.canonicalPath.endsWith( '.js' ) ) {
store.push(file); store.push( file );
} }
} }
} }
@ -65,30 +67,33 @@ exports.autoload = function(dir,logger) {
/* /*
Reload all of the .js files in the given directory Reload all of the .js files in the given directory
*/ */
var _reload = function(pluginDir) (function( pluginDir ) {
{ var sourceFiles = [],
var sourceFiles = []; property,
_listSourceFiles(sourceFiles,pluginDir); module,
pluginPath;
_listSourceFiles( sourceFiles, pluginDir );
var len = sourceFiles.length; var len = sourceFiles.length;
if (config.verbose) if ( config.verbose ) {
console.info(len + ' scriptcraft plugins found.'); console.info( len + ' scriptcraft plugins found.' );
for (var i = 0;i < len; i++){ }
var pluginPath = _canonize(sourceFiles[i]); for ( var i = 0; i < len; i++ ) {
var module = {}; pluginPath = _canonize( sourceFiles[i] );
module = {};
try { try {
module = require(pluginPath); module = require( pluginPath );
for (var property in module){ for ( property in module ) {
/* /*
all exports in plugins become global all exports in plugins become global
*/ */
global[property] = module[property]; global[property] = module[property];
} }
}catch (e){ } catch ( e ) {
logger.severe('Plugin ' + pluginPath + ' ' + e); logger.severe( 'Plugin ' + pluginPath + ' ' + e );
} }
} }
}; }(pluginDir));
_reload(pluginDir);
}; };

View file

@ -54,26 +54,26 @@ module specification, the '.js' suffix is optional.
[cjsmodules]: http://wiki.commonjs.org/wiki/Modules/1.1.1. [cjsmodules]: http://wiki.commonjs.org/wiki/Modules/1.1.1.
***/ ***/
(function (rootDir, modulePaths, hooks) { (function ( rootDir, modulePaths, hooks ) {
var File = java.io.File; var File = java.io.File;
var readModuleFromDirectory = function(dir){ var readModuleFromDirectory = function( dir ) {
// look for a package.json file // look for a package.json file
var pkgJsonFile = new File(dir, './package.json'); var pkgJsonFile = new File( dir, './package.json' );
if (pkgJsonFile.exists()){ if ( pkgJsonFile.exists() ) {
var pkg = scload(pkgJsonFile); var pkg = scload( pkgJsonFile );
var mainFile = new File(dir, pkg.main); var mainFile = new File( dir, pkg.main );
if (mainFile.exists()){ if ( mainFile.exists() ) {
return mainFile; return mainFile;
} else { } else {
return null; return null;
} }
}else{ } else {
// look for an index.js file // look for an index.js file
var indexJsFile = new File(dir + './index.js'); var indexJsFile = new File( dir + './index.js' );
if (indexJsFile.exists()){ if ( indexJsFile.exists() ) {
return indexJsFile; return indexJsFile;
} else { } else {
return null; return null;
@ -81,10 +81,10 @@ module specification, the '.js' suffix is optional.
} }
}; };
var fileExists = function(file) { var fileExists = function( file ) {
if (file.isDirectory()){ if ( file.isDirectory() ) {
return readModuleFromDirectory(file); return readModuleFromDirectory( file );
}else { } else {
return file; return file;
} }
}; };
@ -93,7 +93,6 @@ module specification, the '.js' suffix is optional.
return "" + file.canonicalPath.replaceAll("\\\\","/"); return "" + file.canonicalPath.replaceAll("\\\\","/");
}; };
var resolveModuleToFile = function(moduleName, parentDir) {
/********************************************************************** /**********************************************************************
### module name resolution ### module name resolution
@ -128,12 +127,13 @@ When resolving module names to file paths, ScriptCraft uses the following rules.
3.2 if no package.json file exists then look for an index.js file in the directory 3.2 if no package.json file exists then look for an index.js file in the directory
***/ ***/
var resolveModuleToFile = function ( moduleName, parentDir ) {
var file = new File(moduleName); var file = new File(moduleName);
if (file.exists()){ if ( file.exists() ) {
return fileExists(file); return fileExists(file);
} }
if (moduleName.match(/^[^\.\/]/)){ if ( moduleName.match( /^[^\.\/]/ ) ) {
// it's a module named like so ... 'events' , 'net/http' // it's a module named like so ... 'events' , 'net/http'
// //
var resolvedFile; var resolvedFile;

View file

@ -413,127 +413,140 @@ var server = org.bukkit.Bukkit.server;
/* /*
private implementation private implementation
*/ */
function __onEnable (__engine, __plugin, __script) function __onEnable ( __engine, __plugin, __script )
{ {
var File = java.io.File var File = java.io.File,
,FileReader = java.io.FileReader FileReader = java.io.FileReader,
,BufferedReader = java.io.BufferedReader BufferedReader = java.io.BufferedReader,
,PrintWriter = java.io.PrintWriter PrintWriter = java.io.PrintWriter,
,FileWriter = java.io.FileWriter; FileWriter = java.io.FileWriter;
var _canonize = function(file){ var _canonize = function( file ) {
return "" + file.getCanonicalPath().replaceAll("\\\\","/"); return '' + file.getCanonicalPath().replaceAll( '\\\\', '/' );
}; };
// lib (assumes scriptcraft.js is in craftbukkit/plugins/scriptcraft/lib directory
var libDir = __script.parentFile; // lib (assumes scriptcraft.js is in craftbukkit/plugins/scriptcraft/lib directory var libDir = __script.parentFile,
var jsPluginsRootDir = libDir.parentFile; // scriptcraft jsPluginsRootDir = libDir.parentFile, // scriptcraft
var jsPluginsRootDirName = _canonize(jsPluginsRootDir); jsPluginsRootDirName = _canonize(jsPluginsRootDir),
var logger = __plugin.logger; logger = __plugin.logger;
/* /*
Save a javascript object to a file (saves using JSON notation) Save a javascript object to a file (saves using JSON notation)
*/ */
var _save = function(object, filename){ var _save = function( object, filename ) {
var objectToStr = null; var objectToStr = null,
try{ f,
objectToStr = JSON.stringify(object,null,2); out;
}catch(e){ try {
print("ERROR: " + e.getMessage() + " while saving " + filename); objectToStr = JSON.stringify( object, null, 2 );
} catch( e ) {
print( 'ERROR: ' + e.getMessage() + ' while saving ' + filename );
return; return;
} }
var f = (filename instanceof File) ? filename : new File(filename); f = (filename instanceof File) ? filename : new File(filename);
var out = new PrintWriter(new FileWriter(f)); out = new PrintWriter(new FileWriter(f));
out.println( objectToStr ); out.println( objectToStr );
out.close(); out.close();
}; };
/* /*
make sure eval is present make sure eval is present
*/ */
if (typeof eval == 'undefined'){ if ( typeof eval == 'undefined' ) {
global.eval = function(str){ global.eval = function( str ) {
return __engine.eval(str); return __engine.eval( str );
}; };
} }
/* /*
Load the contents of the file and evaluate as javascript Load the contents of the file and evaluate as javascript
*/ */
var _load = function(filename,warnOnFileNotFound) var _load = function( filename, warnOnFileNotFound )
{ {
var result = null var result = null,
,file = filename file = filename,
,r = undefined; r,
parent,
reader,
br,
code,
wrappedCode;
if (!(filename instanceof File)) if ( !( filename instanceof File ) ) {
file = new File(filename); file = new File(filename);
}
var canonizedFilename = _canonize( file );
var canonizedFilename = _canonize(file); if ( file.exists() ) {
parent = file.getParentFile();
if (file.exists()) { reader = new FileReader( file );
var parent = file.getParentFile(); br = new BufferedReader( reader );
var reader = new FileReader(file); code = '';
var br = new BufferedReader(reader); try {
var code = ""; while ( (r = br.readLine()) !== null ) {
var wrappedCode; code += r + '\n';
try{ }
while ((r = br.readLine()) !== null) wrappedCode = '(' + code + ')';
code += r + "\n"; result = __engine.eval( wrappedCode );
wrappedCode = "(" + code + ")";
result = __engine.eval(wrappedCode);
// issue #103 avoid side-effects of || operator on Mac Rhino // issue #103 avoid side-effects of || operator on Mac Rhino
}catch (e){ } catch ( e ) {
logger.severe("Error evaluating " + canonizedFilename + ", " + e ); logger.severe( 'Error evaluating ' + canonizedFilename + ', ' + e );
} }
finally { finally {
try { try {
reader.close(); reader.close();
}catch (re){ } catch ( re ) {
// fail silently on reader close error // fail silently on reader close error
} }
} }
}else{ } else {
if (warnOnFileNotFound) if ( warnOnFileNotFound ) {
logger.warning(canonizedFilename + " not found"); logger.warning( canonizedFilename + ' not found' );
}
} }
return result; return result;
}; };
/* /*
now that load is defined, use it to load a global config object now that load is defined, use it to load a global config object
*/ */
var config = _load(new File(jsPluginsRootDir, 'data/global-config.json' )); var config = _load( new File(jsPluginsRootDir, 'data/global-config.json' ) );
if (!config) if ( !config ) {
config = {verbose: false}; config = { verbose: false };
}
global.config = config; global.config = config;
global.__plugin = __plugin; global.__plugin = __plugin;
/* /*
wph 20131229 Issue #103 JSON is not bundled with javax.scripting / Rhino on Mac. wph 20131229 Issue #103 JSON is not bundled with javax.scripting / Rhino on Mac.
*/ */
var jsonLoaded = __engine["eval(java.io.Reader)"](new FileReader(new File(jsPluginsRootDirName + '/lib/json2.js'))); (function(){
var jsonFileReader = new FileReader( new File( jsPluginsRootDirName + '/lib/json2.js' ) );
var jsonLoaded = __engine['eval(java.io.Reader)']( jsonFileReader );
}());
/* /*
Unload Handlers Unload Handlers
*/ */
var unloadHandlers = []; var unloadHandlers = [];
var _addUnloadHandler = function(f) { var _addUnloadHandler = function( f ) {
unloadHandlers.push(f); unloadHandlers.push( f );
}; };
var _runUnloadHandlers = function() { var _runUnloadHandlers = function() {
for (var i = 0; i < unloadHandlers.length; i++) { for ( var i = 0; i < unloadHandlers.length; i++ ) {
unloadHandlers[i](); unloadHandlers[i]( );
} }
}; };
global.addUnloadHandler = _addUnloadHandler;
global.refresh = function(){
__plugin.pluginLoader.disablePlugin(__plugin); global.refresh = function( ) {
__plugin.pluginLoader.enablePlugin(__plugin); __plugin.pluginLoader.disablePlugin( __plugin );
__plugin.pluginLoader.enablePlugin( __plugin );
}; };
var _echo = function (msg) { var _echo = function ( msg ) {
if (typeof self == "undefined"){ if ( typeof self == 'undefined' ) {
return; return;
} }
self.sendMessage(msg); self.sendMessage( msg );
}; };
global.echo = _echo; global.echo = _echo;
@ -541,37 +554,37 @@ function __onEnable (__engine, __plugin, __script)
global.scload = _load; global.scload = _load;
global.scsave = _save; global.scsave = _save;
global.addUnloadHandler = _addUnloadHandler; var configRequire = _load( jsPluginsRootDirName + '/lib/require.js', true );
var configRequire = _load(jsPluginsRootDirName + '/lib/require.js',true);
/* /*
setup paths to search for modules setup paths to search for modules
*/ */
var modulePaths = [jsPluginsRootDirName + '/lib/', var modulePaths = [ jsPluginsRootDirName + '/lib/',
jsPluginsRootDirName + '/modules/']; jsPluginsRootDirName + '/modules/' ];
if (config.verbose){ if ( config.verbose ) {
logger.info('Setting up CommonJS-style module system. Root Directory: ' + jsPluginsRootDirName); logger.info( 'Setting up CommonJS-style module system. Root Directory: ' + jsPluginsRootDirName );
logger.info('Module paths: ' + JSON.stringify(modulePaths)); logger.info( 'Module paths: ' + JSON.stringify(modulePaths) );
} }
var requireHooks = { var requireHooks = {
loading: function(path){ loading: function( path ) {
if (config.verbose) if ( config.verbose ) {
logger.info('loading ' + path); logger.info( 'loading ' + path );
}
}, },
loaded: function(path){ loaded: function( path ) {
if (config.verbose) if ( config.verbose ) {
logger.info('loaded ' + path); logger.info( 'loaded ' + path );
}
} }
}; };
global.require = configRequire(jsPluginsRootDirName, modulePaths,requireHooks ); global.require = configRequire( jsPluginsRootDirName, modulePaths, requireHooks );
require('js-patch')(global); require('js-patch')( global );
global.console = require('console'); global.console = require('console');
/* /*
setup persistence setup persistence
*/ */
require('persistence')(jsPluginsRootDir,global); require('persistence')( jsPluginsRootDir, global );
var cmdModule = require('command'); var cmdModule = require('command');
global.command = cmdModule.command; global.command = cmdModule.command;
@ -580,9 +593,9 @@ function __onEnable (__engine, __plugin, __script)
global.plugin = plugins.plugin; global.plugin = plugins.plugin;
var events = require('events'); var events = require('events');
events.on('server.PluginDisableEvent',function(l,e){ events.on( 'server.PluginDisableEvent', function( l, e ) {
// save config // save config
_save(global.config, new File(jsPluginsRootDir, 'data/global-config.json' )); _save( global.config, new File( jsPluginsRootDir, 'data/global-config.json' ) );
_runUnloadHandlers(); _runUnloadHandlers();
org.bukkit.event.HandlerList['unregisterAll(org.bukkit.plugin.Plugin)'](__plugin); org.bukkit.event.HandlerList['unregisterAll(org.bukkit.plugin.Plugin)'](__plugin);
@ -594,12 +607,12 @@ function __onEnable (__engine, __plugin, __script)
global.__onCommand = function( sender, cmd, label, args) { global.__onCommand = function( sender, cmd, label, args) {
var jsArgs = []; var jsArgs = [];
var i = 0; var i = 0;
for (;i < args.length; i++) { for ( ; i < args.length ; i++ ) {
jsArgs.push('' + args[i]); jsArgs.push( '' + args[i] );
} }
var result = false; var result = false;
var cmdName = ('' + cmd.name).toLowerCase(); var cmdName = ( '' + cmd.name ).toLowerCase();
if (cmdName == 'js') if (cmdName == 'js')
{ {
result = true; result = true;
@ -608,43 +621,49 @@ function __onEnable (__engine, __plugin, __script)
global.__engine = __engine; global.__engine = __engine;
try { try {
var jsResult = __engine.eval(fnBody); var jsResult = __engine.eval(fnBody);
if (jsResult) if ( jsResult ) {
sender.sendMessage(jsResult); sender.sendMessage(jsResult);
}catch (e){ }
logger.severe("Error while trying to evaluate javascript: " + fnBody + ", Error: "+ e); } catch ( e ) {
logger.severe( 'Error while trying to evaluate javascript: ' + fnBody + ', Error: '+ e );
throw e; throw e;
}finally{ } finally {
delete global.self; delete global.self;
delete global.__engine; delete global.__engine;
} }
} }
if (cmdName == 'jsp'){ if ( cmdName == 'jsp' ) {
cmdModule.exec(jsArgs, sender); cmdModule.exec( jsArgs, sender );
result = true; result = true;
} }
return result; return result;
}; };
plugins.autoload(jsPluginsRootDir,logger); plugins.autoload( jsPluginsRootDir, logger );
/* /*
wph 20140102 - warn if legacy 'craftbukkit/js-plugins' or 'craftbukkit/scriptcraft' directories are present wph 20140102 - warn if legacy 'craftbukkit/js-plugins' or 'craftbukkit/scriptcraft' directories are present
*/ */
var cbPluginsDir = jsPluginsRootDir.parentFile; (function(){
var cbDir = new File(cbPluginsDir.canonicalPath).parentFile; var cbPluginsDir = jsPluginsRootDir.parentFile,
var legacyDirs = [ cbDir = new File(cbPluginsDir.canonicalPath).parentFile,
new File(cbDir, 'js-plugins'), legacyExists = false,
new File(cbDir, 'scriptcraft') legacyDirs = [new File( cbDir, 'js-plugins' ),
]; new File( cbDir, 'scriptcraft' )];
var legacyExists = false;
for (var i = 0; i < legacyDirs.length; i++){ for ( var i = 0; i < legacyDirs.length; i++ ) {
if (legacyDirs[i].exists() && legacyDirs[i].isDirectory()){ if ( legacyDirs[i].exists()
&& legacyDirs[i].isDirectory() ) {
legacyExists = true; legacyExists = true;
console.warn('Legacy ScriptCraft directory %s was found. This directory is no longer used.', console.warn('Legacy ScriptCraft directory %s was found. This directory is no longer used.',
legacyDirs[i].canonicalPath); legacyDirs[i].canonicalPath);
} }
} }
if (legacyExists){ if ( legacyExists ) {
console.info('Please note that the working directory for %s is %s', console.info( 'Please note that the working directory for %s is %s',
__plugin, jsPluginsRootDir.canonicalPath); __plugin, jsPluginsRootDir.canonicalPath );
} }
})();
} }

View file

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

View file

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

View file

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

View file

@ -27,7 +27,7 @@ To call the fireworks.firework() function directly, you must provide a
location. For example... location. For example...
/js var fireworks = require('fireworks'); /js var fireworks = require('fireworks');
/js fireworks.firework(self.location); /js fireworks.firework( self.location );
![firework example](img/firework.png) ![firework example](img/firework.png)
@ -36,15 +36,15 @@ location. For example...
/* /*
create a firework at the given location create a firework at the given location
*/ */
var firework = function(location){ var firework = function( location ) {
var Color = org.bukkit.Color; var Color = org.bukkit.Color;
var FireworkEffect = org.bukkit.FireworkEffect; var FireworkEffect = org.bukkit.FireworkEffect;
var EntityType = org.bukkit.entity.EntityType; var EntityType = org.bukkit.entity.EntityType;
var randInt = function(n){ var randInt = function( n ) {
return Math.floor(Math.random() * n); return Math.floor( Math.random() * n );
}; };
var getColor = function(i){ var getColor = function( i ) {
var colors = [ var colors = [
Color.AQUA, Color.BLACK, Color.BLUE, Color.FUCHSIA, Color.GRAY, Color.AQUA, Color.BLACK, Color.BLUE, Color.FUCHSIA, Color.GRAY,
Color.GREEN, Color.LIME, Color.MAROON, Color.NAVY, Color.OLIVE, Color.GREEN, Color.LIME, Color.MAROON, Color.NAVY, Color.OLIVE,
@ -59,21 +59,22 @@ var firework = function(location){
FireworkEffect.Type.BURST, FireworkEffect.Type.BURST,
FireworkEffect.Type.CREEPER, FireworkEffect.Type.CREEPER,
FireworkEffect.Type.STAR]; FireworkEffect.Type.STAR];
var type = fwTypes[randInt(5)]; var type = fwTypes[ randInt( 5 ) ];
var r1i = randInt(17); var r1i = randInt( 17 );
var r2i = randInt(17); var r2i = randInt( 17 );
var c1 = getColor(r1i); var c1 = getColor( r1i );
var c2 = getColor(r2i); var c2 = getColor( r2i );
var effectBuilder = FireworkEffect.builder() var effectBuilder = FireworkEffect.builder()
.flicker(Math.round(Math.random())==0) .flicker( Math.round( Math.random() ) == 0 )
.withColor(c1) .withColor( c1 )
.withFade(c2).trail(Math.round(Math.random())==0); .withFade( c2 )
effectBuilder['with'](type); .trail( Math.round( Math.random() ) == 0 );
effectBuilder['with']( type );
var effect = effectBuilder.build(); var effect = effectBuilder.build();
fwm.addEffect(effect); fwm.addEffect( effect );
fwm.setPower(randInt(2)+1); fwm.setPower( randInt( 2 ) + 1 );
fw.setFireworkMeta(fwm); fw.setFireworkMeta( fwm );
}; };
exports.firework = firework; exports.firework = firework;

View file

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

View file

@ -2,44 +2,49 @@
The scoreboard is a simple wrapper around the Bukkit Scoreboard API. The scoreboard is a simple wrapper around the Bukkit Scoreboard API.
It's only concerned with display of scores, not maintaining them - that's the game's job. It's only concerned with display of scores, not maintaining them - that's the game's job.
*/ */
module.exports = function(options){ module.exports = function( options ) {
var temp = {}; var temp = {};
var ccScoreboard; var ccScoreboard;
var DisplaySlot = org.bukkit.scoreboard.DisplaySlot; var DisplaySlot = org.bukkit.scoreboard.DisplaySlot;
return { return {
start: function(){ start: function( ) {
var objective, slot; var objective,
slot,
ccObj;
ccScoreboard = server.scoreboardManager.getNewScoreboard(); ccScoreboard = server.scoreboardManager.getNewScoreboard();
for (objective in options){ for ( objective in options ) {
var ccObj = ccScoreboard.registerNewObjective(objective,'dummy'); ccObj = ccScoreboard.registerNewObjective( objective, 'dummy' );
for (slot in options[objective]){ for ( slot in options[ objective ] ) {
ccObj.displaySlot = DisplaySlot[slot]; ccObj.displaySlot = DisplaySlot[ slot ];
ccObj.displayName = options[objective][slot]; ccObj.displayName = options[ objective ][ slot ];
} }
} }
}, },
stop: function(){ stop: function(){
var objective, slot; var objective, slot;
for (objective in options){ for ( objective in options ) {
ccScoreboard.getObjective(objective).unregister(); ccScoreboard.getObjective(objective).unregister();
for (slot in options[objective]){ for ( slot in options[ objective ] ) {
ccScoreboard.clearSlot(DisplaySlot[slot]); ccScoreboard.clearSlot( DisplaySlot[ slot ] );
} }
} }
}, },
update: function(objective,player,score){ update: function( objective, player, score ) {
if (player.scoreboard && player.scoreboard != ccScoreboard) if ( player.scoreboard && player.scoreboard != ccScoreboard ) {
{
temp[player.name] = player.scoreboard; temp[player.name] = player.scoreboard;
player.scoreboard = ccScoreboard; player.scoreboard = ccScoreboard;
} }
ccScoreboard.getObjective(objective).getScore(player).score = score; ccScoreboard
.getObjective( objective )
.getScore( player )
.score = score;
}, },
restore: function(player){ restore: function( player ) {
// offlineplayers don't have a scoreboard // offlineplayers don't have a scoreboard
if (player.scoreboard) if ( player.scoreboard ) {
player.scoreboard = temp[player.name]; player.scoreboard = temp[ player.name ];
}
} }
}; };
}; };

View file

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

View file

@ -34,24 +34,24 @@ present in the CraftBukkit classpath. To use this module, you should
// create a new client // create a new client
var client = mqtt.client('tcp://localhost:1883', 'uniqueClientId'); var client = mqtt.client( 'tcp://localhost:1883', 'uniqueClientId' );
// connect to the broker // connect to the broker
client.connect({ keepAliveInterval: 15 }); client.connect( { keepAliveInterval: 15 } );
// publish a message to the broker // publish a message to the broker
client.publish('minecraft','loaded'); client.publish( 'minecraft', 'loaded' );
// subscribe to messages on 'arduino' topic // subscribe to messages on 'arduino' topic
client.subscribe('arduino'); client.subscribe( 'arduino' );
// do something when an incoming message arrives... // do something when an incoming message arrives...
client.onMessageArrived(function(topic, message){ client.onMessageArrived( function( topic, message ) {
console.log('Message arrived: topic=' + topic + ', message=' + message); console.log( 'Message arrived: topic=' + topic + ', message=' + message );
}); });
The `sc-mqtt` module provides a very simple minimal wrapper around the The `sc-mqtt` module provides a very simple minimal wrapper around the
@ -66,35 +66,34 @@ var MISSING_MQTT = '\nMissing class org.walterhiggins.scriptcraft.ScriptCraftMqt
'Make sure sc-mqtt.jar is in the classpath.\n' + 'Make sure sc-mqtt.jar is in the classpath.\n' +
'See http://github.com/walterhiggins/scriptcraft-extras-mqtt for details.\n'; 'See http://github.com/walterhiggins/scriptcraft-extras-mqtt for details.\n';
function Client(brokerUrl, clientId){ function Client( brokerUrl, clientId ) {
var Callback = org.walterhiggins.scriptcraft.ScriptCraftMqttCallback; var Callback = org.walterhiggins.scriptcraft.ScriptCraftMqttCallback;
var MqttClient = org.eclipse.paho.client.mqttv3.MqttClient; var MqttClient = org.eclipse.paho.client.mqttv3.MqttClient;
var callback = new Callback( var callback = new Callback(
function(err){ function( err ) {
console.log('connectionLost: ' + err); console.log( 'connectionLost: ' + err );
}, },
function(topic, message){ function( topic, message ) {
console.log('messageArrived ' + topic + '> ' + message); console.log( 'messageArrived ' + topic + '> ' + message );
}, },
function(token){ function( token ) {
console.log('deliveryComplete:' + token); console.log( 'deliveryComplete:' + token );
} }
); );
if (!brokerUrl){ if ( !brokerUrl ) {
brokerUrl = 'tcp://localhost:1883'; brokerUrl = 'tcp://localhost:1883';
} }
if (!clientId){ if ( !clientId ) {
clientId = 'scriptcraft' + new Date().getTime(); clientId = 'scriptcraft' + new Date().getTime();
} }
var client = new MqttClient(brokerUrl, clientId, null); var client = new MqttClient( brokerUrl, clientId, null );
client.setCallback(callback); client.setCallback( callback );
return { return {
connect: function( options ) {
connect: function(options){ if ( typeof options === 'undefined' ) {
if (typeof options === 'undefined'){
client.connect(); client.connect();
}else{ }else{
client.connect(options); client.connect(options);
@ -102,17 +101,18 @@ function Client(brokerUrl, clientId){
return client; return client;
}, },
disconnect: function(quiesceTimeout){ disconnect: function( quiesceTimeout ) {
if (typeof quiesceTimeout == 'undefined') if ( typeof quiesceTimeout == 'undefined' ) {
client.disconnect(); client.disconnect();
else } else {
client.disconnect(quiesceTimeout); client.disconnect( quiesceTimeout );
}
return client; return client;
}, },
publish: function(topic, message, qos, retained){ publish: function( topic, message, qos, retained ) {
if (typeof message == 'string'){ if ( typeof message == 'string' ) {
message = new java.lang.String(message).bytes; message = new java.lang.String( message ).bytes;
} }
if (typeof qos == 'undefined'){ if (typeof qos == 'undefined'){
qos = 1; qos = 1;
@ -120,41 +120,43 @@ function Client(brokerUrl, clientId){
if (typeof retained == 'undefined'){ if (typeof retained == 'undefined'){
retained = false; retained = false;
} }
client.publish(topic, message,qos, retained); client.publish( topic, message,qos, retained );
return client; return client;
}, },
subscribe: function(topic){ subscribe: function( topic ) {
client.subscribe(topic); client.subscribe( topic );
return client; return client;
}, },
unsubscribe: function(topic){ unsubscribe: function( topic ) {
client.unsubscribe(topic); client.unsubscribe( topic );
return client; return client;
}, },
onMessageArrived: function(fn){ onMessageArrived: function( fn ) {
callback.setMesgArrived(fn); callback.setMesgArrived( fn );
return client; return client;
}, },
onDeliveryComplete: function(fn){ onDeliveryComplete: function( fn ) {
callback.setDeliveryComplete(fn); callback.setDeliveryComplete( fn );
return client; return client;
}, },
onConnectionLost: function(fn){ onConnectionLost: function( fn ) {
callback.setConnLost(fn); callback.setConnLost( fn );
return client; return client;
} }
}; };
} }
/*
exports.client = function(brokerUrl, clientId, options){ Return a new MQTT Client
if (typeof org.walterhiggins.scriptcraft.ScriptCraftMqttCallback != 'function'){ */
exports.client = function( brokerUrl, clientId, options ) {
if ( typeof org.walterhiggins.scriptcraft.ScriptCraftMqttCallback != 'function' ) {
throw MISSING_MQTT; throw MISSING_MQTT;
} }
return new Client(brokerUrl, clientId, options); return new Client( brokerUrl, clientId, options );
}; };

View file

@ -16,27 +16,31 @@ var signs = plugin("signs", {
/* Function */ onInteract, /* Function */ onInteract,
/* Number */ defaultSelection ){}, /* Number */ defaultSelection ){},
store: _store store: _store
},true); },
true);
module.exports = signs; module.exports = signs;
/* /*
redraw a menu sign redraw a menu sign
*/ */
var _redrawMenuSign = function(p_sign,p_selectedIndex,p_displayOptions) var _redrawMenuSign = function( p_sign, p_selectedIndex, p_displayOptions ) {
{ var optLen = p_displayOptions.length,
var optLen = p_displayOptions.length; i,
text;
// the offset is where the menu window begins // the offset is where the menu window begins
var offset = Math.max(0, Math.min(optLen-3, Math.floor(p_selectedIndex/3) * 3)); var offset = Math.max( 0, Math.min( optLen-3, Math.floor( p_selectedIndex/3 ) * 3) );
for (var i = 0;i < 3; i++){ for ( i = 0;i < 3; i++ ) {
var text = ""; text = "";
if (offset+i < optLen) if ( offset+i < optLen ) {
text = p_displayOptions[offset+i]; text = p_displayOptions[offset+i];
if (offset+i == p_selectedIndex)
text = ("" + text).replace(/^ /,">");
p_sign.setLine(i+1,text);
} }
p_sign.update(true); if ( offset+i == p_selectedIndex ) {
text = ('' + text).replace(/^ /,">");
}
p_sign.setLine( i+1, text );
}
p_sign.update( true );
}; };
var _updaters = {}; var _updaters = {};
@ -44,26 +48,22 @@ var _updaters = {};
construct an interactive menu to be subsequently attached to construct an interactive menu to be subsequently attached to
one or more Signs. one or more Signs.
*/ */
signs.menu = function( signs.menu = function( /* String */ label, /* Array */ options, /* Function */ callback, /* Number */ selectedIndex ) {
/* String */ label,
/* Array */ options,
/* Function */ callback,
/* Number */ selectedIndex
)
{
if (typeof selectedIndex == "undefined") if ( typeof selectedIndex == "undefined" ) {
selectedIndex = 0; selectedIndex = 0;
}
// //
// variables common to all instances of this menu can go here // variables common to all instances of this menu can go here
// //
var labelPadding = "---------------"; var labelPadding = "---------------";
var optionPadding = " "; var optionPadding = " ";
var i;
var paddedLabel = (labelPadding+label+labelPadding).substr(((label.length+30)/2)-7,15); var paddedLabel = ( labelPadding + label + labelPadding)
.substr( ( ( label.length+30 ) / 2 ) - 7, 15 );
var optLen = options.length; var optLen = options.length;
var displayOptions = []; var displayOptions = [];
for (var i =0;i < options.length;i++){ for ( i = 0; i < options.length; i++ ) {
displayOptions[i] = (" " + options[i] + optionPadding).substring(0,15); displayOptions[i] = (" " + options[i] + optionPadding).substring(0,15);
} }
/* /*
@ -72,22 +72,23 @@ signs.menu = function(
signs.menu is for use by Plugin Authors. signs.menu is for use by Plugin Authors.
The function returned by signs.menu is for use by admins/ops. The function returned by signs.menu is for use by admins/ops.
*/ */
var convertToMenuSign = function(/* Sign */ sign, save) var convertToMenuSign = function(/* Sign */ sign, save) {
{ var mouseLoc;
if (typeof save == "undefined") if (typeof save == "undefined") {
save = true; save = true;
}
/* /*
@deprecated start @deprecated start
all calls should explicitly provide a [org.bukkit.block.Sign][buksign] parameter. all calls should explicitly provide a [org.bukkit.block.Sign][buksign] parameter.
*/ */
if (typeof sign == "undefined"){ if ( typeof sign == "undefined" ) {
var mouseLoc = utils.getMousePos(); mouseLoc = utils.getMousePos();
if (mouseLoc){ if ( mouseLoc ) {
sign = mouseLoc.block.state; sign = mouseLoc.block.state;
if (!(sign && sign.setLine)){ if ( !( sign && sign.setLine ) ) {
throw new Error("You must first provide a sign!"); throw new Error("You must first provide a sign!");
} }
}else{ } else {
throw new Error("You must first provide a sign!"); throw new Error("You must first provide a sign!");
} }
} }
@ -98,31 +99,32 @@ signs.menu = function(
// per-sign variables go here // per-sign variables go here
// //
var cSelectedIndex = selectedIndex; var cSelectedIndex = selectedIndex;
sign.setLine(0,paddedLabel.bold()); sign.setLine( 0, paddedLabel.bold() );
var _updateSign = function(p_player,p_sign) { var _updateSign = function( p_player, p_sign ) {
cSelectedIndex = (cSelectedIndex+1) % optLen; cSelectedIndex = ( cSelectedIndex + 1 ) % optLen;
_redrawMenuSign(p_sign,cSelectedIndex,displayOptions); _redrawMenuSign( p_sign, cSelectedIndex, displayOptions );
var signSelectionEvent = {player: p_player, var signSelectionEvent = {
player: p_player,
sign: p_sign, sign: p_sign,
text: options[cSelectedIndex], text: options[ cSelectedIndex ],
number:cSelectedIndex}; number: cSelectedIndex
};
callback(signSelectionEvent); callback( signSelectionEvent );
}; };
/* /*
get a unique ID for this particular sign instance get a unique ID for this particular sign instance
*/ */
var signLoc = sign.block.location; var signLoc = sign.block.location;
var menuSignSaveData = utils.locationToJSON(signLoc); var menuSignSaveData = utils.locationToJSON( signLoc );
var menuSignUID = JSON.stringify(menuSignSaveData); var menuSignUID = JSON.stringify( menuSignSaveData );
/* /*
keep a reference to the update function for use by the event handler keep a reference to the update function for use by the event handler
*/ */
_updaters[menuSignUID] = _updateSign; _updaters[ menuSignUID ] = _updateSign;
// initialize the sign // initialize the sign
_redrawMenuSign(sign,cSelectedIndex,displayOptions); _redrawMenuSign( sign, cSelectedIndex, displayOptions );
/* /*
whenever a sign is placed somewhere in the world whenever a sign is placed somewhere in the world
@ -130,13 +132,15 @@ signs.menu = function(
save its location for loading and initialization save its location for loading and initialization
when the server starts up again. when the server starts up again.
*/ */
if (save){ if ( save ) {
if (typeof _store.menus == "undefined") if ( typeof _store.menus == "undefined") {
_store.menus = {}; _store.menus = {};
}
var signLocations = _store.menus[label]; var signLocations = _store.menus[label];
if (typeof signLocations == "undefined") if ( typeof signLocations == "undefined" ) {
signLocations = _store.menus[label] = []; signLocations = _store.menus[label] = [];
signLocations.push(menuSignSaveData); }
signLocations.push( menuSignSaveData );
} }
return sign; return sign;
}; };
@ -148,27 +152,26 @@ signs.menu = function(
world with this same label and make dynamic again. world with this same label and make dynamic again.
*/ */
if (_store.menus && _store.menus[label]) if ( _store.menus && _store.menus[label] ) {
{ var signsOfSameLabel = _store.menus[ label ];
var signsOfSameLabel = _store.menus[label];
var defragged = []; var defragged = [];
var len = signsOfSameLabel.length; var len = signsOfSameLabel.length;
for (var i = 0; i < len ; i++) for ( i = 0; i < len; i++ ) {
{
var loc = signsOfSameLabel[i]; var loc = signsOfSameLabel[i];
var world = org.bukkit.Bukkit.getWorld(loc.world); var world = org.bukkit.Bukkit.getWorld(loc.world);
if (!world) if ( !world ) {
continue; continue;
var block = world.getBlockAt(loc.x,loc.y,loc.z); }
if (block.state instanceof org.bukkit.block.Sign){ var block = world.getBlockAt( loc.x, loc.y, loc.z );
convertToMenuSign(block.state,false); if ( block.state instanceof org.bukkit.block.Sign ) {
defragged.push(loc); convertToMenuSign( block.state, false );
defragged.push( loc );
} }
} }
/* /*
remove data for signs which no longer exist. remove data for signs which no longer exist.
*/ */
if (defragged.length != len){ if ( defragged.length != len ) {
_store.menus[label] = defragged; _store.menus[label] = defragged;
} }
} }
@ -178,18 +181,20 @@ signs.menu = function(
// //
// update it every time player interacts with it. // update it every time player interacts with it.
// //
events.on('player.PlayerInteractEvent',function(listener, event) { events.on( 'player.PlayerInteractEvent', function( listener, event ) {
/* /*
look up our list of menu signs. If there's a matching location and there's look up our list of menu signs. If there's a matching location and there's
a sign, then update it. a sign, then update it.
*/ */
if (! event.clickedBlock.state instanceof org.bukkit.block.Sign) if ( ! event.clickedBlock.state instanceof org.bukkit.block.Sign ) {
return; return;
}
var evtLocStr = utils.locationToString(event.clickedBlock.location); var evtLocStr = utils.locationToString(event.clickedBlock.location);
var signUpdater = _updaters[evtLocStr] var signUpdater = _updaters[evtLocStr];
if (signUpdater) if ( signUpdater ) {
signUpdater(event.player, event.clickedBlock.state); signUpdater( event.player, event.clickedBlock.state );
}
}); });

View file

@ -92,16 +92,18 @@ the entity has targeted. It is a utility function for use by plugin authors.
var utils = require('utils'); var utils = require('utils');
var menu = require('./menu'); var menu = require('./menu');
// include all menu exports // include all menu exports
for (var i in menu){ for ( var i in menu ) {
exports[i] = menu[i]; exports[i] = menu[i];
} }
exports.getTargetedBy = function( livingEntity ){ exports.getTargetedBy = function( livingEntity ) {
var location = utils.getMousePos( livingEntity ); var location = utils.getMousePos( livingEntity );
if (!location) if ( !location ) {
return null; return null;
}
var state = location.block.state; var state = location.block.state;
if (!(state || state.setLine)) if ( ! (state || state.setLine) ) {
return null; return null;
}
return state; return state;
}; };

View file

@ -37,7 +37,7 @@ Example
------- -------
/js var boldGoldText = "Hello World".bold().gold(); /js var boldGoldText = "Hello World".bold().gold();
/js self.sendMessage(boldGoldText); /js self.sendMessage( boldGoldText );
<p style="color:gold;font-weight:bold">Hello World</p> <p style="color:gold;font-weight:bold">Hello World</p>
@ -72,8 +72,8 @@ var formattingCodes = {
underline: c.UNDERLINE, underline: c.UNDERLINE,
reset: c.RESET reset: c.RESET
}; };
for (var method in formattingCodes){ for ( var method in formattingCodes ) {
String.prototype[method] = function(c){ String.prototype[method] = function( c ) {
return function(){return c+this;}; return function(){ return c + this; };
}(formattingCodes[method]); }( formattingCodes[method] );
} }

View file

@ -36,15 +36,15 @@ String, then it tries to find the player with that name.
***/ ***/
var _player = function ( playerName ) { var _player = function ( playerName ) {
if (typeof playerName == 'undefined'){ if ( typeof playerName == 'undefined' ) {
if (typeof self == 'undefined'){ if ( typeof self == 'undefined' ) {
return null; return null;
} else { } else {
return self; return self;
} }
} else { } else {
if (typeof playerName == 'string') if ( typeof playerName == 'string' )
return org.bukkit.Bukkit.getPlayer(playerName); return org.bukkit.Bukkit.getPlayer( playerName );
else else
return playerName; // assumes it's a player object return playerName; // assumes it's a player object
} }
@ -73,7 +73,7 @@ This can be useful if you write a plugin that needs to store location data since
A JSON object in the above form. A JSON object in the above form.
***/ ***/
var _locationToJSON = function(location){ var _locationToJSON = function( location ) {
return { return {
world: ''+location.world.name, world: ''+location.world.name,
x: location.x, x: location.x,
@ -102,8 +102,8 @@ keys in a lookup table.
lookupTable[key] = player.name; lookupTable[key] = player.name;
***/ ***/
exports.locationToString = function(location){ exports.locationToString = function( location ) {
return JSON.stringify(_locationToJSON(location)); return JSON.stringify( _locationToJSON( location ) );
}; };
exports.locationToJSON = _locationToJSON; exports.locationToJSON = _locationToJSON;
@ -117,20 +117,22 @@ returned by locationToJSON() and reconstructs and returns a bukkit
Location object. Location object.
***/ ***/
exports.locationFromJSON = function(json){ exports.locationFromJSON = function( json ) {
if (json.constuctor == Array){ var world;
if ( json.constuctor == Array ) {
// for support of legacy format // for support of legacy format
var world = org.bukkit.Bukkit.getWorld(json[0]); world = org.bukkit.Bukkit.getWorld( json[0] );
return new org.bukkit.Location(world, json[1], json[2] , json[3]); return new org.bukkit.Location( world, json[1], json[2] , json[3] );
}else{ } else {
var world = org.bukkit.Bukkit.getWorld(json.world); world = org.bukkit.Bukkit.getWorld( json.world );
return new org.bukkit.Location(world, json.x, json.y , json.z, json.yaw, json.pitch); return new org.bukkit.Location( world, json.x, json.y , json.z, json.yaw, json.pitch );
} }
}; };
exports.player = _player; exports.player = _player;
exports.getPlayerObject = function(player){
console.warn('utils.getPlayerObject() is deprecated. Use utils.player() instead.'); exports.getPlayerObject = function( player ) {
console.warn( 'utils.getPlayerObject() is deprecated. Use utils.player() instead.' );
return _player(player); return _player(player);
}; };
/************************************************************************* /*************************************************************************
@ -153,14 +155,13 @@ An [org.bukkit.Location][bkloc] object.
[bksndr]: http://jd.bukkit.org/dev/apidocs/index.html?org/bukkit/command/CommandSender.html [bksndr]: http://jd.bukkit.org/dev/apidocs/index.html?org/bukkit/command/CommandSender.html
***/ ***/
exports.getPlayerPos = function( player ) { exports.getPlayerPos = function( player ) {
player = _player(player); player = _player( player );
if (player){ if ( player ) {
if (player instanceof org.bukkit.command.BlockCommandSender) if ( player instanceof org.bukkit.command.BlockCommandSender )
return player.block.location; return player.block.location;
else else
return player.location; return player.location;
} }
else
return null; return null;
}; };
/************************************************************************ /************************************************************************
@ -186,16 +187,18 @@ The following code will strike lightning at the location the player is looking a
} }
***/ ***/
exports.getMousePos = function (player) { exports.getMousePos = function( player ) {
player = _player(player); player = _player(player);
if (!player) if ( !player ) {
return null; return null;
}
// player might be CONSOLE or a CommandBlock // player might be CONSOLE or a CommandBlock
if (!player.getTargetBlock) if ( !player.getTargetBlock ) {
return null; return null;
var targetedBlock = player.getTargetBlock(null,5); }
if (targetedBlock == null || targetedBlock.isEmpty()){ var targetedBlock = player.getTargetBlock( null, 5 );
if ( targetedBlock == null || targetedBlock.isEmpty() ) {
return null; return null;
} }
return targetedBlock.location; return targetedBlock.location;
@ -228,7 +231,7 @@ package for scheduling processing of arrays.
- object : Additional (optional) information passed into the foreach method. - object : Additional (optional) information passed into the foreach method.
- array : The entire array. - array : The entire array.
* object (optional) : An object which may be used by the callback. * context (optional) : An object which may be used by the callback.
* delay (optional, numeric) : If a delay is specified (in ticks - 20 * delay (optional, numeric) : If a delay is specified (in ticks - 20
ticks = 1 second), then the processing will be scheduled so that ticks = 1 second), then the processing will be scheduled so that
each item will be processed in turn with a delay between the completion of each each item will be processed in turn with a delay between the completion of each
@ -286,18 +289,24 @@ without hogging CPU usage...
utils.foreach (a, processItem, null, 10, onDone); utils.foreach (a, processItem, null, 10, onDone);
***/ ***/
var _foreach = function(array, callback, object, delay, onCompletion) { var _foreach = function( array, callback, context, delay, onCompletion ) {
if (array instanceof java.util.Collection) if ( array instanceof java.util.Collection ) {
array = array.toArray(); array = array.toArray();
}
var i = 0; var i = 0;
var len = array.length; var len = array.length;
if (delay){ if ( delay ) {
var next = function(){ callback(array[i],i,object,array); i++;}; var next = function( ) {
var hasNext = function(){return i < len;}; callback(array[i], i, context, array);
_nicely(next,hasNext,onCompletion,delay); i++;
}else{ };
for (;i < len; i++){ var hasNext = function( ) {
callback(array[i],i,object,array); return i < len;
};
_nicely( next, hasNext, onCompletion, delay );
} else {
for ( ;i < len; i++ ) {
callback( array[i], i, context, array );
} }
} }
}; };
@ -327,16 +336,17 @@ function and the start of the next `next()` function.
See the source code to utils.foreach for an example of how utils.nicely is used. See the source code to utils.foreach for an example of how utils.nicely is used.
***/ ***/
var _nicely = function(next, hasNext, onDone, delay){ var _nicely = function( next, hasNext, onDone, delay ) {
if (hasNext()){ if ( hasNext() ){
next(); next();
server.scheduler.runTaskLater(__plugin,function(){ server.scheduler.runTaskLater( __plugin, function() {
_nicely(next,hasNext,onDone,delay); _nicely( next, hasNext, onDone, delay );
},delay); }, delay );
}else{ }else{
if (onDone) if ( onDone ) {
onDone(); onDone();
} }
}
}; };
exports.nicely = _nicely; exports.nicely = _nicely;
/************************************************************************ /************************************************************************
@ -360,34 +370,34 @@ To warn players when night is approaching...
utils.at( '19:00', function() { utils.at( '19:00', function() {
utils.foreach( server.onlinePlayers, function(player){ utils.foreach( server.onlinePlayers, function( player ) {
player.chat('The night is dark and full of terrors!'); player.chat( 'The night is dark and full of terrors!' );
}); });
}); });
***/ ***/
exports.at = function(time24hr, callback, worlds) { exports.at = function( time24hr, callback, worlds ) {
var forever = function(){ return true;}; var forever = function(){ return true; };
var timeParts = time24hr.split(':'); var timeParts = time24hr.split( ':' );
var hrs = ((timeParts[0] * 1000) + 18000) % 24000; var hrs = ( (timeParts[0] * 1000) + 18000 ) % 24000;
var mins; var mins;
if (timeParts.length > 1) if ( timeParts.length > 1 ) {
mins = (timeParts[1] / 60) * 1000; mins = ( timeParts[1] / 60 ) * 1000;
}
var timeMc = hrs + mins; var timeMc = hrs + mins;
if (typeof worlds == 'undefined'){ if ( typeof worlds == 'undefined' ) {
worlds = server.worlds; worlds = server.worlds;
} }
_nicely(function(){ _nicely( function() {
_foreach (worlds, function (world){ _foreach( worlds, function ( world ) {
var time = world.getTime(); var time = world.getTime();
var diff = timeMc - time; var diff = timeMc - time;
if (diff > 0 && diff < 100){ if ( diff > 0 && diff < 100 ) {
callback(); callback();
} }
}); });
},forever, null, 100); }, forever, null, 100 );
}; };
/************************************************************************ /************************************************************************
@ -411,25 +421,25 @@ a given directory and recursiving trawling all sub-directories.
}); });
***/ ***/
exports.find = function( dir , filter){ exports.find = function( dir , filter ) {
var result = []; var result = [];
var recurse = function(dir, store){ var recurse = function( dir, store ) {
var files, dirfile = new java.io.File(dir); var files, dirfile = new java.io.File( dir );
if (typeof filter == 'undefined') if ( typeof filter == 'undefined' ) {
files = dirfile.list(); files = dirfile.list();
else } else {
files = dirfile.list(filter); files = dirfile.list(filter);
}
_foreach(files, function (file){ _foreach( files, function( file ) {
file = new java.io.File(dir + '/' + file); file = new java.io.File( dir + '/' + file );
if (file.isDirectory()){ if ( file.isDirectory() ) {
recurse(file.canonicalPath, store); recurse( file.canonicalPath, store );
}else{ } else {
store.push(file.canonicalPath); store.push( file.canonicalPath );
} }
}); });
} };
recurse(dir,result); recurse( dir, result );
return result; return result;
} };

View file

@ -52,7 +52,7 @@ console. Aliases will not be able to avail of command autocompletion
***/ ***/
var _usage = "\ var _usage = '\
/jsp alias set {alias} = {comand-1} ;{command-2}\n \ /jsp alias set {alias} = {comand-1} ;{command-2}\n \
/jsp alias global {alias} = {command-1} ; {command-2}\n \ /jsp alias global {alias} = {command-1} ; {command-2}\n \
/jsp alias list\n \ /jsp alias list\n \
@ -61,7 +61,7 @@ Create a new alias : \n \
/jsp alias set cw = time set {1} ; weather {2}\n \ /jsp alias set cw = time set {1} ; weather {2}\n \
Execute the alias : \n \ Execute the alias : \n \
/cw 4000 sun \n \ /cw 4000 sun \n \
...is the same as '/time set 4000' and '/weather sun'"; ...is the same as \'/time set 4000\' and \'/weather sun\'';
/* /*
persist aliases persist aliases
*/ */
@ -74,80 +74,80 @@ var _store = {
_processParams is a private function which takes an array of parameters _processParams is a private function which takes an array of parameters
used for the 'set' and 'global' options. used for the 'set' and 'global' options.
*/ */
var _processParams = function(params){ var _processParams = function( params ) {
var paramStr = params.join(' '), var paramStr = params.join(' '),
eqPos = paramStr.indexOf('='), eqPos = paramStr.indexOf('='),
aliasCmd = paramStr.substring(0,eqPos).trim(), aliasCmd = paramStr.substring( 0, eqPos).trim(),
aliasValue = paramStr.substring(eqPos+1).trim(); aliasValue = paramStr.substring( eqPos + 1 ).trim();
return { return {
cmd: aliasCmd, cmd: aliasCmd,
aliases: aliasValue.split(/\s*;\s*/) aliases: aliasValue.split( /\s*;\s*/ )
}; };
}; };
var _set = function(params, player){ var _set = function( params, player ) {
var playerAliases = _store.players[player.name]; var playerAliases = _store.players[player.name];
if (!playerAliases){ if (!playerAliases ) {
playerAliases = {}; playerAliases = {};
} }
var o = _processParams(params); var o = _processParams( params );
playerAliases[o.cmd] = o.aliases; playerAliases[o.cmd] = o.aliases;
_store.players[player.name] = playerAliases; _store.players[player.name] = playerAliases;
player.sendMessage("Alias '" + o.cmd + "' created."); player.sendMessage( 'Alias ' + o.cmd + ' created.' );
}; };
var _remove = function(params, player){ var _remove = function( params, player ) {
if (_store.players[player.name] && if ( _store.players[player.name] && _store.players[player.name][ params[0] ] ) {
_store.players[player.name][params[0]]){
delete _store.players[player.name][params[0]]; delete _store.players[player.name][params[0]];
player.sendMessage("Alias '" + params[0] + "' removed."); player.sendMessage( 'Alias ' + params[0] + ' removed.' );
} }
else{ else{
player.sendMessage("Alias '" + params[0] + "' does not exist."); player.sendMessage( 'Alias ' + params[0] + ' does not exist.' );
} }
if (player.op){ if ( player.op ) {
if (_store.global[params[0]]) if ( _store.global[params[0]] ) {
delete _store.global[params[0]]; delete _store.global[params[0]];
} }
}
}; };
var _global = function(params, player){ var _global = function( params, player ) {
if (!player.op){ if ( !player.op ) {
player.sendMessage("Only operators can set global aliases. " + player.sendMessage( 'Only operators can set global aliases. ' +
"You need to be an operator to perform this command."); 'You need to be an operator to perform this command.' );
return; return;
} }
var o = _processParams(params); var o = _processParams( params );
_store.global[o.cmd] = o.aliases; _store.global[o.cmd] = o.aliases;
player.sendMessage("Global alias '" + o.cmd + "' created."); player.sendMessage( 'Global alias ' + o.cmd + ' created.' );
}; };
var _list = function(params, player){ var _list = function( params, player ) {
var alias = 0; var alias = 0;
try { try {
if (_store.players[player.name]){ if ( _store.players[player.name] ) {
player.sendMessage("Your aliases:"); player.sendMessage('Your aliases:');
for (alias in _store.players[player.name]){ for ( alias in _store.players[player.name] ) {
player.sendMessage(alias + " = " + player.sendMessage( alias + ' = ' +
JSON.stringify(_store.players[player.name][alias])); JSON.stringify( _store.players[player.name][alias] ) );
} }
}else{ } else {
player.sendMessage("You have no player-specific aliases."); player.sendMessage( 'You have no player-specific aliases.' );
} }
player.sendMessage("Global aliases:"); player.sendMessage( 'Global aliases:' );
for (alias in _store.global){ for ( alias in _store.global ) {
player.sendMessage(alias + " = " + JSON.stringify(_store.global[alias]) ); player.sendMessage( alias + ' = ' + JSON.stringify( _store.global[alias] ) );
} }
}catch(e){ } catch( e ) {
console.error("Error in list function: " + e.message); console.error( 'Error in list function: ' + e.message );
throw e; throw e;
} }
}; };
var _help = function(params, player){ var _help = function( params, player ) {
player.sendMessage('Usage:\n' + _usage); player.sendMessage( 'Usage:\n' + _usage );
}; };
var alias = plugin('alias', { var alias = plugin( 'alias', {
store: _store, store: _store,
set: _set, set: _set,
global: _global, global: _global,
@ -156,11 +156,11 @@ var alias = plugin('alias', {
help: _help help: _help
}, true ); }, true );
var aliasCmd = command('alias', function( params, invoker ) { var aliasCmd = command( 'alias', function( params, invoker ) {
var operation = params[0], var operation = params[0],
fn; fn;
if (!operation){ if ( !operation ) {
invoker.sendMessage('Usage:\n' + _usage); invoker.sendMessage( 'Usage:\n' + _usage );
return; return;
} }
/* /*
@ -168,53 +168,53 @@ var aliasCmd = command('alias', function( params, invoker ) {
accessing object properties by array index notation accessing object properties by array index notation
in JRE8 alias[operation] returns null - definitely a bug in Nashorn. in JRE8 alias[operation] returns null - definitely a bug in Nashorn.
*/ */
for (var key in alias){ for ( var key in alias ) {
if (key == operation){ if ( key == operation ) {
fn = alias[key]; fn = alias[key];
fn(params.slice(1),invoker); fn( params.slice(1), invoker );
return; return;
} }
} }
invoker.sendMessage('Usage:\n' + _usage); invoker.sendMessage( 'Usage:\n' + _usage );
}); });
var _intercept = function( msg, invoker, exec) var _intercept = function( msg, invoker, exec ) {
{ if ( msg.trim().length == 0 )
if (msg.trim().length == 0)
return false; return false;
var msgParts = msg.split(' '), var msgParts = msg.split(' '),
command = msg.match(/^\/*([^\s]+)/)[1], command = msg.match( /^\/*([^\s]+)/ )[1],
template = [], isAlias = false, cmds = [], template = [],
isAlias = false,
cmds = [],
commandObj, commandObj,
filledinCommand; filledinCommand,
i;
if (_store.global[command]){ if ( _store.global[command] ) {
template = _store.global[command]; template = _store.global[command];
isAlias = true; isAlias = true;
} }
/* /*
allows player-specific aliases to override global aliases allows player-specific aliases to override global aliases
*/ */
if (_store.players[invoker] && if ( _store.players[invoker] && _store.players[invoker][command] ) {
_store.players[invoker][command])
{
template = _store.players[invoker][command]; template = _store.players[invoker][command];
isAlias = true; isAlias = true;
} }
for (var i = 0;i < template.length; i++) for ( i = 0; i < template.length; i++) {
{ filledinCommand = template[i].replace( /{([0-9]+)}/g, function( match, index ) {
filledinCommand = template[i].replace(/{([0-9]+)}/g, function (match,index){ index = parseInt( index, 10 );
index = parseInt(index,10); if ( msgParts[index] ) {
if (msgParts[index])
return msgParts[index]; return msgParts[index];
else } else {
return match; return match;
}
}); });
cmds.push(filledinCommand); cmds.push( filledinCommand );
} }
for (var i = 0; i< cmds.length; i++){ for (i = 0; i< cmds.length; i++ ) {
exec(cmds[i]); exec( cmds[i] );
} }
return isAlias; return isAlias;
@ -223,20 +223,27 @@ var _intercept = function( msg, invoker, exec)
Intercept all command processing and replace with aliased commands if the Intercept all command processing and replace with aliased commands if the
command about to be issued matches an alias. command about to be issued matches an alias.
*/ */
events.on('player.PlayerCommandPreprocessEvent', function(listener,evt){ events.on( 'player.PlayerCommandPreprocessEvent', function( listener, evt ) {
var invoker = evt.player; var invoker = evt.player;
var exec = function(cmd){ invoker.performCommand(cmd);}; var exec = function( cmd ) {
var isAlias = _intercept(''+evt.message, ''+invoker.name, exec); invoker.performCommand(cmd);
if (isAlias) };
var isAlias = _intercept( ''+evt.message, ''+invoker.name, exec);
if ( isAlias ) {
evt.cancelled = true; evt.cancelled = true;
}
}); });
/* define a 'void' command because ServerCommandEvent can't be canceled */ /* define a 'void' command because ServerCommandEvent can't be canceled */
command('void',function(){}); command('void',function( ) {
} );
events.on('server.ServerCommandEvent', function(listener,evt){ events.on( 'server.ServerCommandEvent', function( listener, evt ) {
var invoker = evt.sender; var invoker = evt.sender;
var exec = function(cmd){ invoker.server.dispatchCommand(invoker, cmd); }; var exec = function( cmd ) {
var isAlias = _intercept(''+evt.command, ''+ invoker.name, exec); invoker.server.dispatchCommand( invoker, cmd);
if (isAlias) };
var isAlias = _intercept( ''+evt.command, ''+ invoker.name, exec );
if ( isAlias ) {
evt.command = 'jsp void'; evt.command = 'jsp void';
}
}); });

View file

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

View file

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

View file

@ -1,4 +1,4 @@
var utils = require('utils'); var foreach = require('utils').foreach;
/************************************************************************ /************************************************************************
## Classroom Plugin ## Classroom Plugin
@ -32,45 +32,47 @@ to every student in a Minecraft classroom environment.
To allow all players (and any players who connect to the server) to To allow all players (and any players who connect to the server) to
use the `js` and `jsp` commands... use the `js` and `jsp` commands...
/js classroom.allowScripting(true,self) /js classroom.allowScripting( true, self )
To disallow scripting (and prevent players who join the server from using the commands)... To disallow scripting (and prevent players who join the server from using the commands)...
/js classroom.allowScripting(false,self) /js classroom.allowScripting( false, self )
Only ops users can run the classroom.allowScripting() function - this is so that students Only ops users can run the classroom.allowScripting() function - this is so that students
don't try to bar themselves and each other from scripting. don't try to bar themselves and each other from scripting.
***/ ***/
var _store = {enableScripting: false}; var _store = { enableScripting: false };
var classroom = plugin("classroom", { var classroom = plugin('classroom', {
allowScripting: function (/* boolean: true or false */ canScript, sender) { allowScripting: function (/* boolean: true or false */ canScript, sender ) {
if (typeof sender == 'undefined'){ if ( typeof sender == 'undefined' ) {
console.log("Attempt to set classroom scripting without credentials"); console.log( 'Attempt to set classroom scripting without credentials' );
console.log("classroom.allowScripting(boolean, sender)"); console.log( 'classroom.allowScripting(boolean, sender)' );
return; return;
} }
if (!sender.op){ if ( !sender.op ) {
console.log("Attempt to set classroom scripting without credentials: " + sender.name); console.log( 'Attempt to set classroom scripting without credentials: ' + sender.name );
return; return;
} }
/* /*
only operators should be allowed run this function only operators should be allowed run this function
*/ */
if (!sender.isOp()) if ( !sender.isOp() ) {
return; return;
if (canScript){ }
utils.foreach( server.onlinePlayers, function (player) { if ( canScript ) {
player.addAttachment(__plugin, "scriptcraft.*", true); foreach( server.onlinePlayers, function( player ) {
player.addAttachment( __plugin, 'scriptcraft.*', true );
}); });
}else{ } else {
utils.foreach( server.onlinePlayers, function(player) { foreach( server.onlinePlayers, function( player ) {
utils.foreach(player.getEffectivePermissions(), function(perm) { foreach( player.getEffectivePermissions(), function( perm ) {
if ((""+perm.permission).indexOf("scriptcraft.") == 0){ if ( (''+perm.permission).indexOf( 'scriptcraft.' ) == 0 ) {
if (perm.attachment) if ( perm.attachment ) {
perm.attachment.remove(); perm.attachment.remove();
} }
}
}); });
}); });
} }
@ -81,10 +83,10 @@ var classroom = plugin("classroom", {
exports.classroom = classroom; exports.classroom = classroom;
events.on('player.PlayerLoginEvent', function(listener, event) { events.on( 'player.PlayerLoginEvent', function( listener, event ) {
var player = event.player; var player = event.player;
if (_store.enableScripting){ if ( _store.enableScripting ) {
player.addAttachment(__plugin, "scriptcraft.*", true); player.addAttachment( __plugin, 'scriptcraft.*', true );
} }
}, 'HIGHEST'); }, 'HIGHEST');

View file

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

View file

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

View file

@ -307,14 +307,22 @@ var bitmaps = {
/* /*
wph 20130121 compute the width, and x,y coords of pixels ahead of time wph 20130121 compute the width, and x,y coords of pixels ahead of time
*/ */
for (var c in bitmaps.raw){ var c,
var bits = bitmaps.raw[c]; bits,
var width = bits.length/5; width,
var bmInfo = {"width": width,"pixels":[]} bmInfo,
j;
for ( c in bitmaps.raw ) {
bits = bitmaps.raw[c];
width = bits.length/5;
bmInfo = { width: width, pixels:[] };
bitmaps.computed[c] = bmInfo; bitmaps.computed[c] = bmInfo;
for (var j = 0; j < bits.length; j++){ for ( j = 0; j < bits.length; j++ ) {
if (bits.charAt(j) != ' '){ if ( bits.charAt(j) != ' ' ) {
bmInfo.pixels.push([j%width,Math.ceil(j/width)]); bmInfo.pixels.push( [
j % width,
Math.ceil( j / width )
] );
} }
} }
} }
@ -328,46 +336,72 @@ for (var c in bitmaps.raw){
// bg // bg
// background material, optional. The negative space within the bounding box of the text. // background material, optional. The negative space within the bounding box of the text.
// //
Drone.extend('blocktype', function(message,fg,bg){ Drone.extend('blocktype', function( message, fg, bg ) {
var bmfg,
bmbg,
lines,
lineCount,
h,
line,
i,
x,
y,
ch,
bits,
charWidth,
j;
this.chkpt('blocktext'); this.chkpt('blocktext');
if (typeof fg == "undefined") if ( typeof fg == 'undefined' ) {
fg = blocks.wool.black; fg = blocks.wool.black;
}
var bmfg = this._getBlockIdAndMeta(fg); bmfg = this._getBlockIdAndMeta( fg );
var bmbg = null; bmbg = null;
if (typeof bg != "undefined") if ( typeof bg != 'undefined' ) {
bmbg = this._getBlockIdAndMeta(bg); bmbg = this._getBlockIdAndMeta( bg );
var lines = message.split("\n"); }
var lineCount = lines.length; lines = message.split( '\n' );
for (var h = 0;h < lineCount; h++) { lineCount = lines.length;
var line = lines[h];
line = line.toLowerCase().replace(/[^0-9a-z \.\-\+\/\;\'\:\!]/g,"");
this.up(7*(lineCount-(h+1)));
for (var i =0;i < line.length; i++) { for ( h = 0; h < lineCount; h++) {
var ch = line.charAt(i)
var bits = bitmaps.computed[ch]; line = lines[h];
if (typeof bits == "undefined"){ line = line.toLowerCase().replace( /[^0-9a-z \.\-\+\/\;\'\:\!]/g, '' );
this.up( 7 * ( lineCount - ( h + 1 ) ) );
for ( i =0; i < line.length; i++) {
ch = line.charAt( i );
bits = bitmaps.computed[ ch ];
if ( typeof bits == 'undefined' ) {
bits = bitmaps.computed[' ']; bits = bitmaps.computed[' '];
} }
var charWidth = bits.width; charWidth = bits.width;
if (typeof bg != "undefined")
this.cuboidX(bmbg[0],bmbg[1],charWidth,7,1); if ( typeof bg != 'undefined' ) {
for (var j = 0;j < bits.pixels.length;j++){ this.cuboidX( bmbg[0], bmbg[1], charWidth, 7, 1 );
this.chkpt('btbl');
var x = bits.pixels[j][0];
var 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');
} }
return this.move('blocktext'); for ( j = 0; j < bits.pixels.length; j++ ) {
this.chkpt( 'btbl' );
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' );
}
return this.move( 'blocktext' );
}); });

View file

@ -3,17 +3,16 @@ var Drone = require('../drone').Drone;
// //
// a castle is just a big wide fort with 4 taller forts at each corner // a castle is just a big wide fort with 4 taller forts at each corner
// //
Drone.extend('castle', function(side, height) Drone.extend('castle', function( side, height ) {
{
// //
// use sensible default parameter values // use sensible default parameter values
// if no parameters are supplied // if no parameters are supplied
// //
if (typeof side == "undefined") if ( typeof side == "undefined" )
side = 24; side = 24;
if (typeof height == "undefined") if ( typeof height == "undefined" )
height = 10; height = 10;
if (height < 8 || side < 20) if ( height < 8 || side < 20 )
throw new java.lang.RuntimeException("Castles must be at least 20 wide X 8 tall"); throw new java.lang.RuntimeException("Castles must be at least 20 wide X 8 tall");
// //
// remember where the drone is so it can return 'home' // remember where the drone is so it can return 'home'
@ -40,8 +39,7 @@ Drone.extend('castle', function(side, height)
// //
// now place 4 towers at each corner (each tower is another fort) // now place 4 towers at each corner (each tower is another fort)
// //
for (var corner = 0; corner < 4; corner++) for ( var corner = 0; corner < 4; corner++ ) {
{
// construct a 'tower' fort // construct a 'tower' fort
this.fort(towerSide,towerHeight); this.fort(towerSide,towerHeight);
// move forward the length of the castle then turn right // move forward the length of the castle then turn right

View file

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

View file

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

View file

@ -3,17 +3,20 @@ var Drone = require('../drone').Drone;
// //
// constructs a medieval fort // constructs a medieval fort
// //
Drone.extend('fort', function(side, height) Drone.extend('fort', function( side, height ) {
{ if ( typeof side == 'undefined' ) {
if (typeof side == "undefined")
side = 18; side = 18;
if (typeof height == "undefined") }
if ( typeof height == 'undefined' ) {
height = 6; height = 6;
}
// make sure side is even // make sure side is even
if (side%2) if ( side % 2 ) {
side++; side++;
if (height < 4 || side < 10) }
throw new java.lang.RuntimeException("Forts must be at least 10 wide X 4 tall"); if ( height < 4 || side < 10 ) {
throw new java.lang.RuntimeException('Forts must be at least 10 wide X 4 tall');
}
var brick = 98; var brick = 98;
// //
// build walls. // build walls.
@ -23,17 +26,17 @@ Drone.extend('fort', function(side, height)
// build battlements // build battlements
// //
this.up(height-1); this.up(height-1);
for (i = 0;i <= 3;i++){ for ( i = 0; i <= 3; i++ ) {
var turret = []; var turret = [];
this.box(brick) // solid brick corners this.box(brick) // solid brick corners
.up().box('50:5').down() // light a torch on each corner .up().box('50:5').down() // light a torch on each corner
.fwd(); .fwd();
turret.push('109:'+ Drone.PLAYER_STAIRS_FACING[this.dir]); turret.push('109:'+ Drone.PLAYER_STAIRS_FACING[this.dir]);
turret.push('109:'+ Drone.PLAYER_STAIRS_FACING[(this.dir+2)%4]); turret.push('109:'+ Drone.PLAYER_STAIRS_FACING[(this.dir+2)%4]);
try{ try {
this.boxa(turret,1,1,side-2).fwd(side-2).turn(); this.boxa(turret,1,1,side-2).fwd(side-2).turn();
}catch(e){ } catch( e ) {
console.log("ERROR: " + e.toString()); console.log('ERROR: ' + e.toString());
} }
} }
// //
@ -42,9 +45,9 @@ Drone.extend('fort', function(side, height)
this.move('fort'); this.move('fort');
this.up(height-2).fwd().right().box('126:0',side-2,1,side-2); this.up(height-2).fwd().right().box('126:0',side-2,1,side-2);
var battlementWidth = 3; var battlementWidth = 3;
if (side <= 12) if ( side <= 12 ) {
battlementWidth = 2; battlementWidth = 2;
}
this.fwd(battlementWidth).right(battlementWidth) this.fwd(battlementWidth).right(battlementWidth)
.box(0,side-((1+battlementWidth)*2),1,side-((1+battlementWidth)*2)); .box(0,side-((1+battlementWidth)*2),1,side-((1+battlementWidth)*2));
// //

View file

@ -17,21 +17,21 @@ exports.LCDClock = function(drone, fgColor,bgColor,border) {
world = drone.world, world = drone.world,
intervalId = -1; intervalId = -1;
if (typeof bgColor == 'undefined') if ( typeof bgColor == 'undefined' ) {
bgColor = '35:15'; // black wool bgColor = '35:15'; // black wool
}
if (typeof fgColor == 'undefined') if ( typeof fgColor == 'undefined' ) {
fgColor = 35 ; // white wool fgColor = 35 ; // white wool
}
if (border){ if ( border ) {
drone.box(border,21,9,1); drone.box(border,21,9,1);
drone.up().right(); drone.up().right();
} }
drone.blocktype('00:00',fgColor,bgColor); drone.blocktype('00:00',fgColor,bgColor);
return { return {
start24: function(){ start24: function( ) {
var clock = this; var clock = this;
function tick(){ function tick() {
var rolloverMins = 24*60; var rolloverMins = 24*60;
var timeOfDayInMins = Math.floor(((world.time + 6000) % 24000) / 16.6667); var timeOfDayInMins = Math.floor(((world.time + 6000) % 24000) / 16.6667);
timeOfDayInMins = timeOfDayInMins % rolloverMins; timeOfDayInMins = timeOfDayInMins % rolloverMins;
@ -40,10 +40,10 @@ exports.LCDClock = function(drone, fgColor,bgColor,border) {
}; };
intervalId = setInterval(tick, 800); intervalId = setInterval(tick, 800);
}, },
stop24: function(){ stop24: function() {
clearInterval(intervalId); clearInterval( intervalId );
}, },
update: function(secs){ update: function(secs) {
var digits = [0,0,0,0], var digits = [0,0,0,0],
s = secs % 60; s = secs % 60;
m = (secs - s) / 60; m = (secs - s) / 60;

View file

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

View file

@ -12,7 +12,7 @@ var Drone = require('../drone').Drone;
* depth - (Optional) depth of the cube, defaults to width * depth - (Optional) depth of the cube, defaults to width
*/ */
Drone.extend("rboxcall", function(callback, probability, width, height, depth) { Drone.extend("rboxcall", function( callback, probability, width, height, depth ) {
this.chkpt('rboxcall-start'); this.chkpt('rboxcall-start');
for(var i = 0; i < width; ++i) { for(var i = 0; i < width; ++i) {

View file

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

View file

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

View file

@ -3,19 +3,19 @@ var Drone = require('../drone').Drone;
// constructs a mayan temple // constructs a mayan temple
// //
Drone.extend('temple', function(side) { Drone.extend('temple', function(side) {
if (!side) { if ( !side ) {
side = 20; side = 20;
} }
var stone = '98:1'; var stone = '98:1';
var stair = '109:' + Drone.PLAYER_STAIRS_FACING[this.dir]; var stair = '109:' + Drone.PLAYER_STAIRS_FACING[ this.dir ];
this.chkpt('temple'); this.chkpt('temple');
while (side > 4) { while ( side > 4 ) {
var middle = Math.round((side-2)/2); var middle = Math.round( (side-2) / 2 );
this.chkpt('corner') this.chkpt('corner')
.box(stone, side, 1, side) .box( stone, side, 1, side )
.right(middle).box(stair).right().box(stair) .right( middle ).box( stair ).right().box( stair )
.move('corner').up().fwd().right(); .move('corner').up().fwd().right();
side = side - 2; side = side - 2;
} }

View file

@ -1,6 +1,6 @@
var fireworks = require('fireworks'); var fireworks = require('fireworks');
var Drone = require('./drone').Drone; var Drone = require('./drone').Drone;
Drone.extend('firework',function() { Drone.extend( 'firework', function( ) {
fireworks.firework(this.getLocation()); fireworks.firework( this.getLocation() );
}); });

File diff suppressed because it is too large Load diff

View file

@ -22,49 +22,64 @@ Spheres are time-consuming to make. You *can* make large spheres (250 radius) bu
server to be very busy for a couple of minutes while doing so. server to be very busy for a couple of minutes while doing so.
***/ ***/
Drone.extend('sphere', function(block,radius) Drone.extend( 'sphere', function( block, radius ) {
{ var lastRadius = radius,
var lastRadius = radius; slices = [ [ radius , 0 ] ],
var slices = [[radius,0]]; diameter = radius * 2,
var diameter = radius*2; bm = this._getBlockIdAndMeta( block ),
var bm = this._getBlockIdAndMeta(block); r2 = radius * radius,
i = 0,
newRadius,
yOffset,
sr,
sh,
v,
h;
var r2 = radius*radius; for ( i = 0; i <= radius; i++ ) {
for (var i = 0; i <= radius;i++){ newRadius = Math.round( Math.sqrt( r2 - i * i ) );
var newRadius = Math.round(Math.sqrt(r2 - i*i)); if ( newRadius == lastRadius ) {
if (newRadius == lastRadius) slices[ slices.length - 1 ][ 1 ]++;
slices[slices.length-1][1]++; } else {
else slices.push( [ newRadius , 1 ] );
slices.push([newRadius,1]); }
lastRadius = newRadius; lastRadius = newRadius;
} }
this.chkpt('sphere'); this.chkpt( 'sphere' );
// //
// mid section // mid section
// //
this.up(radius - slices[0][1]) this.up( radius - slices[0][1] )
.cylinder(block,radius,(slices[0][1]*2)-1,{blockType: bm[0],meta: bm[1]}) .cylinder( block, radius, ( slices[0][1]*2 ) - 1, { blockType: bm[0], meta: bm[1] } )
.down(radius-slices[0][1]); .down( radius - slices[0][1] );
var yOffset = -1; yOffset = -1;
for (var i = 1; i < slices.length;i++) for ( i = 1; i < slices.length; i++ ) {
{
yOffset += slices[i-1][1]; yOffset += slices[i-1][1];
var sr = slices[i][0]; sr = slices[i][0];
var sh = slices[i][1]; sh = slices[i][1];
var v = radius + yOffset, h = radius-sr; v = radius + yOffset;
h = radius - sr;
// northern hemisphere // northern hemisphere
this.up(v).fwd(h).right(h) this.up( v )
.cylinder(block,sr,sh,{blockType: bm[0],meta: bm[1]}) .fwd( h )
.left(h).back(h).down(v); .right( h )
.cylinder( block, sr, sh, { blockType: bm[0], meta: bm[1] } )
.left( h )
.back( h )
.down( v );
// southern hemisphere // southern hemisphere
v = radius - (yOffset+sh+1); v = radius - ( yOffset + sh + 1 );
this.up(v).fwd(h).right(h) this.up( v )
.cylinder(block,sr,sh,{blockType: bm[0],meta: bm[1]}) .fwd( h )
.left(h).back(h). down(v); .right( h )
.cylinder( block, sr, sh, { blockType: bm[0], meta: bm[1] } )
.left( h )
.back( h )
.down( v );
} }
return this.move('sphere'); return this.move( 'sphere' );
}); });
/************************************************************************ /************************************************************************
### Drone.sphere0() method ### Drone.sphere0() method
@ -88,79 +103,78 @@ server to be very busy for a couple of minutes while doing so.
***/ ***/
Drone.extend('sphere0', function(block,radius) Drone.extend('sphere0', function(block,radius)
{ {
/* var lastRadius = radius,
this.sphere(block,radius) slices = [ [ radius, 0 ] ],
.fwd().right().up() diameter = radius * 2,
.sphere(0,radius-1) bm = this._getBlockIdAndMeta( block ),
.back().left().down(); r2 = radius*radius,
i,
newRadius,
sr,
sh,
v,
h,
len,
yOffset;
*/ for ( i = 0; i <= radius; i++ ) {
newRadius = Math.round( Math.sqrt( r2 - i * i ) );
var lastRadius = radius; if ( newRadius == lastRadius ) {
var slices = [[radius,0]]; slices[ slices.length - 1 ][ 1 ]++;
var diameter = radius*2; } else {
var bm = this._getBlockIdAndMeta(block); slices.push( [ newRadius, 1 ] );
}
var r2 = radius*radius;
for (var i = 0; i <= radius;i++){
var newRadius = Math.round(Math.sqrt(r2 - i*i));
if (newRadius == lastRadius)
slices[slices.length-1][1]++;
else
slices.push([newRadius,1]);
lastRadius = newRadius; lastRadius = newRadius;
} }
this.chkpt('sphere0'); this.chkpt( 'sphere0' );
// //
// mid section // mid section
// //
//.cylinder(block,radius,(slices[0][1]*2)-1,{blockType: bm[0],meta: bm[1]}) this.up( radius - slices[0][1] )
this.up(radius - slices[0][1]) .arc({ blockType: bm[0],
.arc({blockType: bm[0],
meta: bm[1], meta: bm[1],
radius: radius, radius: radius,
strokeWidth: 2, strokeWidth: 2,
stack: (slices[0][1]*2)-1, stack: (slices[0][1]*2)-1,
fill: false fill: false
}) })
.down(radius-slices[0][1]); .down( radius - slices[0][1] );
var yOffset = -1; yOffset = -1;
var len = slices.length; len = slices.length;
for (var i = 1; i < len;i++) for ( i = 1; i < len; i++ ) {
{
yOffset += slices[i-1][1]; yOffset += slices[i-1][1];
var sr = slices[i][0]; sr = slices[i][0];
var sh = slices[i][1]; sh = slices[i][1];
var v = radius + yOffset, h = radius-sr; v = radius + yOffset;
h = radius-sr;
// northern hemisphere // northern hemisphere
// .cylinder(block,sr,sh,{blockType: bm[0],meta: bm[1]}) // .cylinder(block,sr,sh,{blockType: bm[0],meta: bm[1]})
this.up(v).fwd(h).right(h) this.up( v ).fwd( h ).right( h )
.arc({ .arc({
blockType: bm[0], blockType: bm[0],
meta: bm[1], meta: bm[1],
radius: sr, radius: sr,
stack: sh, stack: sh,
fill: false, fill: false,
strokeWidth: i<len-1?1+(sr-slices[i+1][0]):1 strokeWidth: i < len - 1 ? 1 + ( sr - slices[ i + 1 ][ 0 ] ) : 1
}) })
.left(h).back(h).down(v); .left( h ).back( h ).down( v );
// southern hemisphere // southern hemisphere
v = radius - (yOffset+sh+1); v = radius - ( yOffset + sh + 1 );
//.cylinder(block,sr,sh,{blockType: bm[0],meta: bm[1]}) this.up( v ).fwd( h ).right( h )
this.up(v).fwd(h).right(h)
.arc({ .arc({
blockType: bm[0], blockType: bm[0],
meta: bm[1], meta: bm[1],
radius: sr, radius: sr,
stack: sh, stack: sh,
fill: false, fill: false,
strokeWidth: i<len-1?1+(sr-slices[i+1][0]):1 strokeWidth: i < len - 1 ? 1 + ( sr - slices[ i + 1 ][ 0 ] ) : 1
}) })
.left(h).back(h). down(v); .left( h ).back( h ). down( v );
} }
this.move('sphere0'); this.move( 'sphere0' );
return this; return this;
@ -185,55 +199,55 @@ To create a wood 'north' hemisphere with a radius of 7 blocks...
![hemisphere example](img/hemisphereex1.png) ![hemisphere example](img/hemisphereex1.png)
***/ ***/
Drone.extend('hemisphere', function(block,radius, northSouth){ Drone.extend( 'hemisphere', function( block, radius, northSouth ) {
var lastRadius = radius; var lastRadius = radius,
var slices = [[radius,0]]; slices = [ [ radius, 0 ] ],
var diameter = radius*2; diameter = radius * 2,
var bm = this._getBlockIdAndMeta(block); bm = this._getBlockIdAndMeta(block),
r2 = radius * radius,
var r2 = radius*radius; i = 0,
for (var i = 0; i <= radius;i++){ newRadius;
var newRadius = Math.round(Math.sqrt(r2 - i*i)); for ( i = 0; i <= radius; i++ ) {
if (newRadius == lastRadius) newRadius = Math.round( Math.sqrt( r2 - i * i ) );
slices[slices.length-1][1]++; if ( newRadius == lastRadius ) {
else slices[ slices.length - 1 ][ 1 ]++;
slices.push([newRadius,1]); } else {
slices.push( [ newRadius, 1 ] );
}
lastRadius = newRadius; lastRadius = newRadius;
} }
this.chkpt('hsphere'); this.chkpt( 'hsphere' );
// //
// mid section // mid section
// //
if (northSouth == "north"){ if ( northSouth == 'north' ) {
this.cylinder(block,radius,slices[0][1],{blockType: bm[0],meta: bm[1]}); this.cylinder( block, radius, slices[0][1], { blockType: bm[0], meta: bm[1] } );
} else { } else {
this.up(radius - slices[0][1]) this.up( radius - slices[0][1] )
.cylinder(block,radius,slices[0][1],{blockType: bm[0],meta: bm[1]}) .cylinder( block, radius, slices[0][1], { blockType: bm[0], meta: bm[1] } )
.down(radius - slices[0][1]); .down( radius - slices[0][1] );
} }
var yOffset = -1; var yOffset = -1;
for (var i = 1; i < slices.length;i++) for ( i = 1; i < slices.length; i++ ) {
{
yOffset += slices[i-1][1]; yOffset += slices[i-1][1];
var sr = slices[i][0]; var sr = slices[i][0];
var sh = slices[i][1]; var sh = slices[i][1];
var v = yOffset, h = radius-sr; var v = yOffset, h = radius-sr;
if (northSouth == "north") { if ( northSouth == 'north' ) {
// northern hemisphere // northern hemisphere
this.up(v).fwd(h).right(h) this.up( v ).fwd( h ).right( h )
.cylinder(block,sr,sh,{blockType: bm[0],meta: bm[1]}) .cylinder( block, sr, sh, { blockType: bm[0], meta: bm[1] } )
.left(h).back(h).down(v); .left( h ).back( h ).down( v );
}else{ } else {
// southern hemisphere // southern hemisphere
v = radius - (yOffset+sh+1); v = radius - ( yOffset + sh + 1 );
this.up(v).fwd(h).right(h) this.up( v ).fwd( h ).right( h )
.cylinder(block,sr,sh,{blockType: bm[0],meta: bm[1]}) .cylinder( block, sr, sh, { blockType: bm[0], meta: bm[1] } )
.left(h).back(h). down(v); .left( h ).back( h ).down( v );
} }
} }
return this.move('hsphere'); return this.move( 'hsphere' );
}); });
/************************************************************************ /************************************************************************
### Drone.hemisphere0() method ### Drone.hemisphere0() method
@ -255,9 +269,9 @@ To create a glass 'north' hemisphere with a radius of 20 blocks...
![hemisphere example](img/hemisphereex2.png) ![hemisphere example](img/hemisphereex2.png)
***/ ***/
Drone.extend('hemisphere0', function(block,radius,northSouth){ Drone.extend( 'hemisphere0', function( block, radius, northSouth ) {
return this.hemisphere(block,radius,northSouth) return this.hemisphere( block, radius, northSouth)
.fwd().right().up(northSouth=="north"?0:1) .fwd().right().up( northSouth == 'north' ? 0 : 1 )
.hemisphere(0,radius-1,northSouth) .hemisphere( 0, radius-1, northSouth )
.back().left().down(northSouth=="north"?0:1); .back().left().down( northSouth == 'north' ? 0 : 1 );
}); });

View file

@ -25,6 +25,6 @@ permission since it relies on the `/js` command to execute.
}; };
***/ ***/
exports.hello = function(player){ exports.hello = function( player ) {
player.sendMessage('Hello ' + player.name); player.sendMessage( 'Hello ' + player.name );
}; };

View file

@ -27,6 +27,6 @@ command does not evaluate javascript code so this command is much more secure.
***/ ***/
command('hello', function (parameters, player) { command( 'hello', function( parameters, player ) {
player.sendMessage('Hello ' + player.name); player.sendMessage( 'Hello ' + player.name );
}); });

View file

@ -30,13 +30,13 @@ message for operators.
}); });
***/ ***/
command('op-hello', function (parameters, player) { command( 'op-hello', function( parameters, player ) {
/* /*
this is how you limit based on player privileges this is how you limit based on player privileges
*/ */
if (!player.op){ if ( !player.op ) {
player.sendMessage('Only operators can do this.'); player.sendMessage( 'Only operators can do this.' );
return; return;
} }
player.sendMessage('Hello ' + player.name); player.sendMessage( 'Hello ' + player.name );
}); });

View file

@ -19,14 +19,14 @@ This example demonstrates adding and using parameters in commands.
This differs from example 3 in that the greeting can be changed from This differs from example 3 in that the greeting can be changed from
a fixed 'Hello ' to anything you like by passing a parameter. a fixed 'Hello ' to anything you like by passing a parameter.
command('hello-params', function (parameters, player) { command( 'hello-params', function ( parameters, player ) {
var salutation = parameters[0] ; var salutation = parameters[0] ;
player.sendMessage( salutation + ' ' + player.name); player.sendMessage( salutation + ' ' + player.name );
}); });
***/ ***/
command('hello-params', function (parameters, player) { command('hello-params', function( parameters, player ) {
/* /*
parameters is an array (or list) of strings. parameters[0] parameters is an array (or list) of strings. parameters[0]
refers to the first element in the list. Arrays in Javascript refers to the first element in the list. Arrays in Javascript
@ -36,5 +36,5 @@ command('hello-params', function (parameters, player) {
which appears after `jsp hello-params `. which appears after `jsp hello-params `.
*/ */
var salutation = parameters[0] ; var salutation = parameters[0] ;
player.sendMessage( salutation + ' ' + player.name); player.sendMessage( salutation + ' ' + player.name );
}); });

View file

@ -29,13 +29,13 @@ this example, we use that module...
Source Code... Source Code...
var greetings = require('./example-1-hello-module'); var greetings = require('./example-1-hello-module');
command('hello-module', function( parameters, player ){ command( 'hello-module', function( parameters, player ) {
greetings.hello(player); greetings.hello( player );
}); });
***/ ***/
var greetings = require('./example-1-hello-module'); var greetings = require('./example-1-hello-module');
command('hello-module', function( parameters, player ){ command( 'hello-module', function( parameters, player ) {
greetings.hello(player); greetings.hello( player );
}); });

View file

@ -32,13 +32,14 @@ Source Code ...
var utils = require('utils'); var utils = require('utils');
var greetings = require('./example-1-hello-module'); var greetings = require('./example-1-hello-module');
command('hello-byname', function( parameters, sender ) { command( 'hello-byname', function( parameters, sender ) {
var playerName = parameters[0]; var playerName = parameters[0];
var recipient = utils.player(playerName); var recipient = utils.player( playerName );
if (recipient) if ( recipient ) {
greetings.hello(recipient); greetings.hello( recipient );
else } else {
sender.sendMessage('Player ' + playerName + ' not found.'); sender.sendMessage( 'Player ' + playerName + ' not found.' );
}
}); });
***/ ***/
@ -46,11 +47,12 @@ Source Code ...
var utils = require('utils'); var utils = require('utils');
var greetings = require('./example-1-hello-module'); var greetings = require('./example-1-hello-module');
command('hello-byname', function( parameters, sender ) { command( 'hello-byname', function( parameters, sender ) {
var playerName = parameters[0]; var playerName = parameters[0];
var recipient = utils.player(playerName); var recipient = utils.player( playerName );
if (recipient) if ( recipient ) {
greetings.hello(recipient); greetings.hello( recipient );
else } else {
sender.sendMessage('Player ' + playerName + ' not found.'); sender.sendMessage( 'Player ' + playerName + ' not found.' );
}
}); });

View file

@ -79,15 +79,15 @@ cleaner and more readable. Similarly where you see a method like
[bksaf]: http://jd.bukkit.org/dev/apidocs/org/bukkit/entity/Player.html#setAllowFlight() [bksaf]: http://jd.bukkit.org/dev/apidocs/org/bukkit/entity/Player.html#setAllowFlight()
[bkapi]: http://jd.bukkit.org/dev/apidocs/ [bkapi]: http://jd.bukkit.org/dev/apidocs/
events.on('player.PlayerJoinEvent', function (listener, event){ events.on( 'player.PlayerJoinEvent', function( listener, event ) {
if (event.player.op) { if ( event.player.op ) {
event.player.sendMessage('Welcome to ' + __plugin); event.player.sendMessage('Welcome to ' + __plugin);
} }
}); });
***/ ***/
events.on('player.PlayerJoinEvent', function (listener, event){ events.on( 'player.PlayerJoinEvent', function( listener, event ) {
if (event.player.op) { if ( event.player.op ) {
event.player.sendMessage('Welcome to ' + __plugin); event.player.sendMessage( 'Welcome to ' + __plugin );
} }
}); });

View file

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

View file

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

View file

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

View file

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

View file

@ -16,20 +16,21 @@ press TAB. Visit
for a list of possible entities (creatures) which can be spawned. for a list of possible entities (creatures) which can be spawned.
***/ ***/
var entities = []; var entities = [],
var Types = org.bukkit.entity.EntityType EntityType = org.bukkit.entity.EntityType;
for (var t in Types){
if (Types[t] && Types[t].ordinal){ for ( var t in EntityType ) {
if ( EntityType[t] && EntityType[t].ordinal ) {
entities.push(t); entities.push(t);
} }
} }
command('spawn', function(parameters, sender){ command( 'spawn', function( parameters, sender ) {
if (!sender.op){ if ( !sender.op ) {
sender.sendMessage('Only operators can perform this command'); sender.sendMessage( 'Only operators can perform this command' );
return; return;
} }
var location = sender.location; var location = sender.location;
var world = location.world; var world = location.world;
var type = ('' + parameters[0]).toUpperCase(); var type = ('' + parameters[0]).toUpperCase();
world.spawnEntity(location, org.bukkit.entity.EntityType[type]); world.spawnEntity( location, EntityType[type] );
},entities); }, entities );

View file

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