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...
/js var fireworks = require('fireworks');
/js fireworks.firework(self.location);
/js fireworks.firework( self.location );
![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...
var http = require('./http/request');
http.request({ url: "http://pixenate.com/pixenate/pxn8.pl",
method: "POST",
params: {script: "[]"}
}, function( responseCode, responseBody){
var jsObj = eval("(" + responseBody + ")");
http.request(
{
url: 'http://pixenate.com/pixenate/pxn8.pl',
method: 'POST',
params: {script: '[]'}
},
function( responseCode, responseBody ) {
var jsObj = eval('(' + responseBody + ')');
});
## sc-mqtt module
@ -870,24 +873,24 @@ present in the CraftBukkit classpath. To use this module, you should
// create a new client
var client = mqtt.client('tcp://localhost:1883', 'uniqueClientId');
var client = mqtt.client( 'tcp://localhost:1883', 'uniqueClientId' );
// connect to the broker
client.connect({ keepAliveInterval: 15 });
client.connect( { keepAliveInterval: 15 } );
// publish a message to the broker
client.publish('minecraft','loaded');
client.publish( 'minecraft', 'loaded' );
// subscribe to messages on 'arduino' topic
client.subscribe('arduino');
client.subscribe( 'arduino' );
// do something when an incoming message arrives...
client.onMessageArrived(function(topic, message){
console.log('Message arrived: topic=' + topic + ', message=' + message);
client.onMessageArrived( function( topic, message ) {
console.log( 'Message arrived: topic=' + topic + ', message=' + message );
});
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 self.sendMessage(boldGoldText);
/js self.sendMessage( boldGoldText );
<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.
- array : The entire array.
* object (optional) : An object which may be used by the callback.
* context (optional) : An object which may be used by the callback.
* delay (optional, numeric) : If a delay is specified (in ticks - 20
ticks = 1 second), then the processing will be scheduled so that
each item will be processed in turn with a delay between the completion of each
@ -1273,8 +1276,8 @@ To warn players when night is approaching...
utils.at( '19:00', function() {
utils.foreach( server.onlinePlayers, function(player){
player.chat('The night is dark and full of terrors!');
utils.foreach( server.onlinePlayers, function( player ) {
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
this...
events.on('block.BlockBreakEvent',function(listener,event){
events.on('block.BlockBreakEvent',function( listener,event) {
var location = event.block.location;
var drone = new Drone(location);
// 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
//
for (i = 0; i< 100; i++){
for ( i = 0; i< 100; i++) {
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.
* 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].
* 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
* 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
the orientation - if orientation is horizontal then this parameter
refers to the height, if vertical then it refers to the length).
* strokeWidth (default: 1) - the width of the stroke (how many
refers to the height, if vertical then it refers to the length ).
* strokeWidth (default: 1 ) - the width of the stroke (how many
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
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',
stack: 1,
fill: false
});
} );
![arc example 1](img/arcex1.png)
@ -1715,7 +1718,7 @@ To create a free-standing sign...
... to create a wall mounted sign...
drone.sign(["Welcome","to","Scriptopia"], 68);
drone.sign(["Welcome","to","Scriptopia"], 68 );
![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 ...
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
should use the tree methods when the drone is directly above the
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
the `up()` method is called first).
the `up( )` method is called first).
![tree example](img/treeex1.png)
@ -1795,7 +1798,7 @@ pasting the copied area elsewhere...
#### Example
drone.copy('somethingCool',10,5,10).right(12).paste('somethingCool');
drone.copy('somethingCool',10,5,10 ).right(12 ).paste('somethingCool' );
### 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
'somethingCool'. The drone moves 12 blocks right then pastes the copy.
drone.copy('somethingCool',10,5,10)
.right(12)
.paste('somethingCool');
drone.copy('somethingCool',10,5,10 )
.right(12 )
.paste('somethingCool' );
### Chaining
@ -1866,9 +1869,9 @@ Use this method to add new methods (which also become chainable global functions
#### Example
// submitted by [edonaldson][edonaldson]
Drone.extend('pyramid', function(block,height){
Drone.extend('pyramid', function( block,height) {
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();
}
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...
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
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...
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
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
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] ;
player.sendMessage( salutation + ' ' + player.name);
player.sendMessage( salutation + ' ' + player.name );
});
## Example Plugin #5 - Re-use - Using your own and others modules.
@ -2253,8 +2256,8 @@ this example, we use that module...
Source Code...
var greetings = require('./example-1-hello-module');
command('hello-module', function( parameters, player ){
greetings.hello(player);
command( 'hello-module', function( parameters, player ) {
greetings.hello( player );
});
## Example Plugin #6 - Re-use - Using 'utils' to get Player objects.
@ -2290,13 +2293,14 @@ Source Code ...
var utils = require('utils');
var greetings = require('./example-1-hello-module');
command('hello-byname', function( parameters, sender ) {
command( 'hello-byname', function( parameters, sender ) {
var playerName = parameters[0];
var recipient = utils.player(playerName);
if (recipient)
greetings.hello(recipient);
else
sender.sendMessage('Player ' + playerName + ' not found.');
var recipient = utils.player( playerName );
if ( recipient ) {
greetings.hello( recipient );
} else {
sender.sendMessage( 'Player ' + playerName + ' not found.' );
}
});
## 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()
[bkapi]: http://jd.bukkit.org/dev/apidocs/
events.on('player.PlayerJoinEvent', function (listener, event){
if (event.player.op) {
events.on( 'player.PlayerJoinEvent', function( listener, event ) {
if ( event.player.op ) {
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
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)...
/js classroom.allowScripting(false,self)
/js classroom.allowScripting( false, self )
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.

View file

@ -2,45 +2,53 @@
/*
command management - allow for non-ops to execute approved javascript code.
*/
var _commands = {};
var _cmdInterceptors = [];
var _commands = {},
_cmdInterceptors = [];
/*
execute a JSP command.
*/
var executeCmd = function(args, player){
if (args.length === 0)
var executeCmd = function( args, player ) {
var name,
cmd,
intercepted,
result = null;
if ( args.length === 0 ) {
throw new Error('Usage: jsp command-name command-parameters');
var name = args[0];
var cmd = _commands[name];
if (typeof cmd === 'undefined'){
}
name = args[0];
cmd = _commands[name];
if ( typeof cmd === 'undefined' ) {
// it's not a global command - pass it on to interceptors
var intercepted = false;
for (var i = 0;i < _cmdInterceptors.length;i++){
if (_cmdInterceptors[i](args,player))
intercepted = false;
for ( var i = 0; i < _cmdInterceptors.length; i++ ) {
if ( _cmdInterceptors[i]( args, player ) )
intercepted = true;
}
if (!intercepted)
console.warn('Command %s is not recognised',name);
if ( !intercepted ) {
console.warn( 'Command %s is not recognised', name );
}
}else{
var result = null;
try {
result = cmd.callback(args.slice(1),player);
}catch (e){
console.error('Error while trying to execute command: ' + JSON.stringify(args));
result = cmd.callback( args.slice(1), player );
} catch ( e ) {
console.error( 'Error while trying to execute command: ' + JSON.stringify( args ) );
throw e;
}
return result;
}
return result;
};
/*
define a new JSP command.
*/
var defineCmd = function(name, func, options, intercepts) {
if (typeof options == 'undefined')
var defineCmd = function( name, func, options, intercepts ) {
if ( typeof options == 'undefined' ) {
options = [];
_commands[name] = {callback: func, options: options};
if (intercepts)
}
_commands[name] = { callback: func, options: options };
if ( intercepts ) {
_cmdInterceptors.push(func);
}
return func;
};
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
***/
var logger = __plugin.logger;
var argsToArray = function(args){
var logger = __plugin.logger,
logMethodName = 'log(java.util.logging.Level,java.lang.String)';
var argsToArray = function( args ) {
var result = [];
for (var i =0;i < args.length; i++)
for ( var i =0; i < args.length; i++ ) {
result.push(args[i]);
}
return result;
}
var log = function(level, restOfArgs){
var args = argsToArray(restOfArgs);
if (args.length > 1){
var msg = java.lang.String.format(args[0],args.slice(1));
logger['log(java.util.logging.Level,java.lang.String)'](level,msg);
}else{
logger['log(java.util.logging.Level,java.lang.String)'](level, args[0]);
var log = function( level, restOfArgs ) {
var args = argsToArray( restOfArgs );
if ( args.length > 1 ) {
var msg = java.lang.String.format( args[0], args.slice(1) );
logger[logMethodName]( level, msg );
} else {
logger[logMethodName]( level, args[0] );
}
};
var Level = java.util.logging.Level;
exports.log = function(){
log(Level.INFO, arguments);
exports.log = function( ) {
log( Level.INFO, arguments );
};
exports.info = function(){
log(Level.INFO, arguments);
}
exports.warn = function(){
log(Level.WARNING, arguments);
exports.info = function( ) {
log( Level.INFO, 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 bkEvtExecutor = org.bukkit.plugin.EventExecutor;
var bkRegListener = org.bukkit.plugin.RegisteredListener;
var bkEvent = org.bukkit.event,
bkEvtExecutor = org.bukkit.plugin.EventExecutor,
bkRegListener = org.bukkit.plugin.RegisteredListener;
exports.on = function(
/* String or java Class */
@ -86,31 +86,33 @@ exports.on = function(
handler,
/* (optional) String (HIGH, HIGHEST, LOW, LOWEST, NORMAL, MONITOR), */
priority ) {
var handlerList,
listener = {},
eventExecutor;
if (typeof priority == "undefined"){
if ( typeof priority == 'undefined' ) {
priority = bkEvent.EventPriority.HIGHEST;
}else{
} else {
priority = bkEvent.EventPriority[priority];
}
if (typeof eventType == "string"){
if ( typeof eventType == 'string' ) {
/*
Nashorn doesn't support bracket notation for accessing packages.
E.g. java.net will work but java['net'] won't.
https://bugs.openjdk.java.net/browse/JDK-8031715
*/
if (typeof Java != 'undefined'){
if ( typeof Java != 'undefined' ) {
// nashorn environment
eventType = Java.type('org.bukkit.event.' + eventType);
eventType = Java.type( 'org.bukkit.event.' + eventType );
} else {
eventType = eval('org.bukkit.event.' + eventType);
eventType = eval( 'org.bukkit.event.' + eventType );
}
}
var handlerList = eventType.getHandlerList();
var listener = {};
var eventExecutor = new bkEvtExecutor(){
execute: function(l,e){
handler(listener.reg,e);
handlerList = eventType.getHandlerList( );
eventExecutor = new bkEvtExecutor( ) {
execute: function( l, e ) {
handler( listener.reg, e );
}
};
/*
@ -121,7 +123,7 @@ exports.on = function(
The workaround is to make the ScriptCraftPlugin java class a Listener.
Should only unregister() registered plugins in ScriptCraft js code.
*/
listener.reg = new bkRegListener( __plugin, eventExecutor, priority, __plugin, true);
handlerList.register(listener.reg);
listener.reg = new bkRegListener( __plugin, eventExecutor, priority, __plugin, true );
handlerList.register( 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.
if (typeof String.prototype.trim == 'undefined'){
String.prototype.trim = function(){
return this.replace(/^\s+|\s+$/g,'');
if ( typeof String.prototype.trim == 'undefined' ) {
String.prototype.trim = function( ) {
return this.replace( /^\s+|\s+$/g, '' );
};
}
$.setTimeout = function( callback, delayInMillis){
$.setTimeout = function( callback, delayInMillis ) {
/*
javascript programmers familiar with setTimeout know that it expects
a delay in milliseconds. However, bukkit's scheduler expects a delay in ticks
(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;
};
$.clearTimeout = function(bukkitTask){
$.clearTimeout = function( bukkitTask ) {
bukkitTask.cancel();
};
$.setInterval = function(callback, intervalInMillis){
$.setInterval = function( callback, intervalInMillis ) {
var delay = intervalInMillis/ 50;
var bukkitTask = server.scheduler.runTaskTimer(__plugin, callback, delay, delay);
var bukkitTask = server.scheduler.runTaskTimer( __plugin, callback, delay, delay );
return bukkitTask;
};
$.clearInterval = function(bukkitTask){
$.clearInterval = function( bukkitTask ) {
bukkitTask.cancel();
};
};

View file

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

View file

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

View file

@ -54,26 +54,26 @@ module specification, the '.js' suffix is optional.
[cjsmodules]: http://wiki.commonjs.org/wiki/Modules/1.1.1.
***/
(function (rootDir, modulePaths, hooks) {
(function ( rootDir, modulePaths, hooks ) {
var File = java.io.File;
var readModuleFromDirectory = function(dir){
var readModuleFromDirectory = function( dir ) {
// look for a package.json file
var pkgJsonFile = new File(dir, './package.json');
if (pkgJsonFile.exists()){
var pkg = scload(pkgJsonFile);
var mainFile = new File(dir, pkg.main);
if (mainFile.exists()){
var pkgJsonFile = new File( dir, './package.json' );
if ( pkgJsonFile.exists() ) {
var pkg = scload( pkgJsonFile );
var mainFile = new File( dir, pkg.main );
if ( mainFile.exists() ) {
return mainFile;
} else {
return null;
}
}else{
} else {
// look for an index.js file
var indexJsFile = new File(dir + './index.js');
if (indexJsFile.exists()){
var indexJsFile = new File( dir + './index.js' );
if ( indexJsFile.exists() ) {
return indexJsFile;
} else {
return null;
@ -81,10 +81,10 @@ module specification, the '.js' suffix is optional.
}
};
var fileExists = function(file) {
if (file.isDirectory()){
return readModuleFromDirectory(file);
}else {
var fileExists = function( file ) {
if ( file.isDirectory() ) {
return readModuleFromDirectory( file );
} else {
return file;
}
};
@ -93,7 +93,6 @@ module specification, the '.js' suffix is optional.
return "" + file.canonicalPath.replaceAll("\\\\","/");
};
var resolveModuleToFile = function(moduleName, parentDir) {
/**********************************************************************
### module name resolution
@ -128,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
***/
var resolveModuleToFile = function ( moduleName, parentDir ) {
var file = new File(moduleName);
if (file.exists()){
if ( file.exists() ) {
return fileExists(file);
}
if (moduleName.match(/^[^\.\/]/)){
if ( moduleName.match( /^[^\.\/]/ ) ) {
// it's a module named like so ... 'events' , 'net/http'
//
var resolvedFile;

View file

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

View file

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

View file

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

View file

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

View file

@ -27,7 +27,7 @@ To call the fireworks.firework() function directly, you must provide a
location. For example...
/js var fireworks = require('fireworks');
/js fireworks.firework(self.location);
/js fireworks.firework( self.location );
![firework example](img/firework.png)
@ -36,15 +36,15 @@ location. For example...
/*
create a firework at the given location
*/
var firework = function(location){
var firework = function( location ) {
var Color = org.bukkit.Color;
var FireworkEffect = org.bukkit.FireworkEffect;
var EntityType = org.bukkit.entity.EntityType;
var randInt = function(n){
return Math.floor(Math.random() * n);
var randInt = function( n ) {
return Math.floor( Math.random() * n );
};
var getColor = function(i){
var getColor = function( i ) {
var colors = [
Color.AQUA, Color.BLACK, Color.BLUE, Color.FUCHSIA, Color.GRAY,
Color.GREEN, Color.LIME, Color.MAROON, Color.NAVY, Color.OLIVE,
@ -59,21 +59,22 @@ var firework = function(location){
FireworkEffect.Type.BURST,
FireworkEffect.Type.CREEPER,
FireworkEffect.Type.STAR];
var type = fwTypes[randInt(5)];
var type = fwTypes[ randInt( 5 ) ];
var r1i = randInt(17);
var r2i = randInt(17);
var c1 = getColor(r1i);
var c2 = getColor(r2i);
var r1i = randInt( 17 );
var r2i = randInt( 17 );
var c1 = getColor( r1i );
var c2 = getColor( r2i );
var effectBuilder = FireworkEffect.builder()
.flicker(Math.round(Math.random())==0)
.withColor(c1)
.withFade(c2).trail(Math.round(Math.random())==0);
effectBuilder['with'](type);
.flicker( Math.round( Math.random() ) == 0 )
.withColor( c1 )
.withFade( c2 )
.trail( Math.round( Math.random() ) == 0 );
effectBuilder['with']( type );
var effect = effectBuilder.build();
fwm.addEffect(effect);
fwm.setPower(randInt(2)+1);
fw.setFireworkMeta(fwm);
fwm.addEffect( effect );
fwm.setPower( randInt( 2 ) + 1 );
fw.setFireworkMeta( fwm );
};
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...
var http = require('./http/request');
http.request({ url: "http://pixenate.com/pixenate/pxn8.pl",
method: "POST",
params: {script: "[]"}
}, function( responseCode, responseBody){
var jsObj = eval("(" + responseBody + ")");
http.request(
{
url: 'http://pixenate.com/pixenate/pxn8.pl',
method: 'POST',
params: {script: '[]'}
},
function( responseCode, responseBody ) {
var jsObj = eval('(' + responseBody + ')');
});
***/
exports.request = function( request, callback)
{
var paramsToString = function(params){
var result = "";
var paramNames = [];
for (var i in params){
paramNames.push(i);
exports.request = function( request, callback ) {
var paramsToString = function( params ) {
var result = '',
paramNames = [],
i;
for ( i in params ) {
paramNames.push( i );
}
for (var i = 0;i < paramNames.length;i++){
result += paramNames[i] + "=" + encodeURI(params[paramNames[i]]);
if (i < paramNames.length-1)
result += "&";
for ( i = 0; i < paramNames.length; i++ ) {
result += paramNames[i] + '=' + encodeURI( params[ paramNames[i] ] );
if ( i < paramNames.length-1 )
result += '&';
}
return result;
};
server.scheduler.runTaskAsynchronously(__plugin,function()
{
server.scheduler.runTaskAsynchronously( __plugin, function() {
var url, paramsAsString, conn, requestMethod;
if (typeof request === "string"){
if (typeof request === 'string'){
url = request;
requestMethod = "GET";
requestMethod = 'GET';
}else{
paramsAsString = paramsToString(request.params);
if (request.method)
requestMethod = request.method
else
requestMethod = "GET";
if (requestMethod == "GET" && request.params){
paramsAsString = paramsToString( request.params );
if ( request.method ) {
requestMethod = request.method;
} else {
requestMethod = 'GET';
}
if ( requestMethod == 'GET' && request.params ) {
// append each parameter to the URL
url = request.url + "?" + paramsAsString;
url = request.url + '?' + paramsAsString;
}
}
conn = new java.net.URL(url).openConnection();
conn = new java.net.URL( url ).openConnection();
conn.requestMethod = requestMethod;
conn.doOutput = true;
conn.instanceFollowRedirects = false;
if (conn.requestMethod == "POST"){
if ( conn.requestMethod == 'POST' ) {
conn.doInput = true;
// put each parameter in the outputstream
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", "" + paramsAsString.length);
conn.setRequestProperty('Content-Type', 'application/x-www-form-urlencoded');
conn.setRequestProperty('charset', 'utf-8');
conn.setRequestProperty('Content-Length', '' + paramsAsString.length);
conn.useCaches =false ;
wr = new java.io.DataOutputStream(conn.getOutputStream ());
wr.writeBytes(paramsAsString);
@ -99,12 +101,12 @@ exports.request = function( request, callback)
var rc = conn.responseCode;
var response;
var stream;
if (rc == 200){
if ( rc == 200 ) {
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(){
callback(rc,response);
server.scheduler.runTask( __plugin, function( ) {
callback( rc, response );
});
});
};

View file

@ -2,44 +2,49 @@
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.
*/
module.exports = function(options){
module.exports = function( options ) {
var temp = {};
var ccScoreboard;
var DisplaySlot = org.bukkit.scoreboard.DisplaySlot;
return {
start: function(){
var objective, slot;
start: function( ) {
var objective,
slot,
ccObj;
ccScoreboard = server.scoreboardManager.getNewScoreboard();
for (objective in options){
var ccObj = ccScoreboard.registerNewObjective(objective,'dummy');
for (slot in options[objective]){
ccObj.displaySlot = DisplaySlot[slot];
ccObj.displayName = options[objective][slot];
for ( objective in options ) {
ccObj = ccScoreboard.registerNewObjective( objective, 'dummy' );
for ( slot in options[ objective ] ) {
ccObj.displaySlot = DisplaySlot[ slot ];
ccObj.displayName = options[ objective ][ slot ];
}
}
},
stop: function(){
var objective, slot;
for (objective in options){
for ( objective in options ) {
ccScoreboard.getObjective(objective).unregister();
for (slot in options[objective]){
ccScoreboard.clearSlot(DisplaySlot[slot]);
for ( slot in options[ objective ] ) {
ccScoreboard.clearSlot( DisplaySlot[ slot ] );
}
}
},
update: function(objective,player,score){
if (player.scoreboard && player.scoreboard != ccScoreboard)
{
update: function( objective, player, score ) {
if ( player.scoreboard && player.scoreboard != ccScoreboard ) {
temp[player.name] = player.scoreboard;
player.scoreboard = ccScoreboard;
}
ccScoreboard.getObjective(objective).getScore(player).score = score;
ccScoreboard
.getObjective( objective )
.getScore( player )
.score = score;
},
restore: function(player){
restore: function( player ) {
// offlineplayers don't have a scoreboard
if (player.scoreboard)
player.scoreboard = temp[player.name];
if ( player.scoreboard ) {
player.scoreboard = temp[ player.name ];
}
}
};
};

View file

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

View file

@ -34,24 +34,24 @@ present in the CraftBukkit classpath. To use this module, you should
// create a new client
var client = mqtt.client('tcp://localhost:1883', 'uniqueClientId');
var client = mqtt.client( 'tcp://localhost:1883', 'uniqueClientId' );
// connect to the broker
client.connect({ keepAliveInterval: 15 });
client.connect( { keepAliveInterval: 15 } );
// publish a message to the broker
client.publish('minecraft','loaded');
client.publish( 'minecraft', 'loaded' );
// subscribe to messages on 'arduino' topic
client.subscribe('arduino');
client.subscribe( 'arduino' );
// do something when an incoming message arrives...
client.onMessageArrived(function(topic, message){
console.log('Message arrived: topic=' + topic + ', message=' + message);
client.onMessageArrived( function( topic, message ) {
console.log( 'Message arrived: topic=' + topic + ', message=' + message );
});
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' +
'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 MqttClient = org.eclipse.paho.client.mqttv3.MqttClient;
var callback = new Callback(
function(err){
console.log('connectionLost: ' + err);
function( err ) {
console.log( 'connectionLost: ' + err );
},
function(topic, message){
console.log('messageArrived ' + topic + '> ' + message);
function( topic, message ) {
console.log( 'messageArrived ' + topic + '> ' + message );
},
function(token){
console.log('deliveryComplete:' + token);
function( token ) {
console.log( 'deliveryComplete:' + token );
}
);
if (!brokerUrl){
if ( !brokerUrl ) {
brokerUrl = 'tcp://localhost:1883';
}
if (!clientId){
if ( !clientId ) {
clientId = 'scriptcraft' + new Date().getTime();
}
var client = new MqttClient(brokerUrl, clientId, null);
client.setCallback(callback);
var client = new MqttClient( brokerUrl, clientId, null );
client.setCallback( callback );
return {
connect: function(options){
if (typeof options === 'undefined'){
connect: function( options ) {
if ( typeof options === 'undefined' ) {
client.connect();
}else{
client.connect(options);
@ -102,17 +101,18 @@ function Client(brokerUrl, clientId){
return client;
},
disconnect: function(quiesceTimeout){
if (typeof quiesceTimeout == 'undefined')
disconnect: function( quiesceTimeout ) {
if ( typeof quiesceTimeout == 'undefined' ) {
client.disconnect();
else
client.disconnect(quiesceTimeout);
} else {
client.disconnect( quiesceTimeout );
}
return client;
},
publish: function(topic, message, qos, retained){
if (typeof message == 'string'){
message = new java.lang.String(message).bytes;
publish: function( topic, message, qos, retained ) {
if ( typeof message == 'string' ) {
message = new java.lang.String( message ).bytes;
}
if (typeof qos == 'undefined'){
qos = 1;
@ -120,41 +120,43 @@ function Client(brokerUrl, clientId){
if (typeof retained == 'undefined'){
retained = false;
}
client.publish(topic, message,qos, retained);
client.publish( topic, message,qos, retained );
return client;
},
subscribe: function(topic){
client.subscribe(topic);
subscribe: function( topic ) {
client.subscribe( topic );
return client;
},
unsubscribe: function(topic){
client.unsubscribe(topic);
unsubscribe: function( topic ) {
client.unsubscribe( topic );
return client;
},
onMessageArrived: function(fn){
callback.setMesgArrived(fn);
onMessageArrived: function( fn ) {
callback.setMesgArrived( fn );
return client;
},
onDeliveryComplete: function(fn){
callback.setDeliveryComplete(fn);
onDeliveryComplete: function( fn ) {
callback.setDeliveryComplete( fn );
return client;
},
onConnectionLost: function(fn){
callback.setConnLost(fn);
onConnectionLost: function( fn ) {
callback.setConnLost( fn );
return client;
}
};
}
exports.client = function(brokerUrl, clientId, options){
if (typeof org.walterhiggins.scriptcraft.ScriptCraftMqttCallback != 'function'){
/*
Return a new MQTT Client
*/
exports.client = function( brokerUrl, clientId, options ) {
if ( typeof org.walterhiggins.scriptcraft.ScriptCraftMqttCallback != 'function' ) {
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,
/* Number */ defaultSelection ){},
store: _store
},true);
},
true);
module.exports = signs;
/*
redraw a menu sign
*/
var _redrawMenuSign = function(p_sign,p_selectedIndex,p_displayOptions)
{
var optLen = p_displayOptions.length;
var _redrawMenuSign = function( p_sign, p_selectedIndex, p_displayOptions ) {
var optLen = p_displayOptions.length,
i,
text;
// the offset is where the menu window begins
var offset = Math.max(0, Math.min(optLen-3, Math.floor(p_selectedIndex/3) * 3));
for (var i = 0;i < 3; i++){
var text = "";
if (offset+i < optLen)
var offset = Math.max( 0, Math.min( optLen-3, Math.floor( p_selectedIndex/3 ) * 3) );
for ( i = 0;i < 3; i++ ) {
text = "";
if ( offset+i < optLen ) {
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 = {};
@ -44,26 +48,22 @@ var _updaters = {};
construct an interactive menu to be subsequently attached to
one or more Signs.
*/
signs.menu = function(
/* String */ label,
/* Array */ options,
/* Function */ callback,
/* Number */ selectedIndex
)
{
signs.menu = function( /* String */ label, /* Array */ options, /* Function */ callback, /* Number */ selectedIndex ) {
if (typeof selectedIndex == "undefined")
if ( typeof selectedIndex == "undefined" ) {
selectedIndex = 0;
}
//
// variables common to all instances of this menu can go here
//
var labelPadding = "---------------";
var optionPadding = " ";
var paddedLabel = (labelPadding+label+labelPadding).substr(((label.length+30)/2)-7,15);
var i;
var paddedLabel = ( labelPadding + label + labelPadding)
.substr( ( ( label.length+30 ) / 2 ) - 7, 15 );
var optLen = options.length;
var displayOptions = [];
for (var i =0;i < options.length;i++){
for ( i = 0; i < options.length; i++ ) {
displayOptions[i] = (" " + options[i] + optionPadding).substring(0,15);
}
/*
@ -72,22 +72,23 @@ signs.menu = function(
signs.menu is for use by Plugin Authors.
The function returned by signs.menu is for use by admins/ops.
*/
var convertToMenuSign = function(/* Sign */ sign, save)
{
if (typeof save == "undefined")
var convertToMenuSign = function(/* Sign */ sign, save) {
var mouseLoc;
if (typeof save == "undefined") {
save = true;
}
/*
@deprecated start
all calls should explicitly provide a [org.bukkit.block.Sign][buksign] parameter.
*/
if (typeof sign == "undefined"){
var mouseLoc = utils.getMousePos();
if (mouseLoc){
if ( typeof sign == "undefined" ) {
mouseLoc = utils.getMousePos();
if ( mouseLoc ) {
sign = mouseLoc.block.state;
if (!(sign && sign.setLine)){
if ( !( sign && sign.setLine ) ) {
throw new Error("You must first provide a sign!");
}
}else{
} else {
throw new Error("You must first provide a sign!");
}
}
@ -98,31 +99,32 @@ signs.menu = function(
// per-sign variables go here
//
var cSelectedIndex = selectedIndex;
sign.setLine(0,paddedLabel.bold());
var _updateSign = function(p_player,p_sign) {
cSelectedIndex = (cSelectedIndex+1) % optLen;
_redrawMenuSign(p_sign,cSelectedIndex,displayOptions);
var signSelectionEvent = {player: p_player,
sign.setLine( 0, paddedLabel.bold() );
var _updateSign = function( p_player, p_sign ) {
cSelectedIndex = ( cSelectedIndex + 1 ) % optLen;
_redrawMenuSign( p_sign, cSelectedIndex, displayOptions );
var signSelectionEvent = {
player: p_player,
sign: p_sign,
text: options[cSelectedIndex],
number:cSelectedIndex};
callback(signSelectionEvent);
text: options[ cSelectedIndex ],
number: cSelectedIndex
};
callback( signSelectionEvent );
};
/*
get a unique ID for this particular sign instance
*/
var signLoc = sign.block.location;
var menuSignSaveData = utils.locationToJSON(signLoc);
var menuSignUID = JSON.stringify(menuSignSaveData);
var menuSignSaveData = utils.locationToJSON( signLoc );
var menuSignUID = JSON.stringify( menuSignSaveData );
/*
keep a reference to the update function for use by the event handler
*/
_updaters[menuSignUID] = _updateSign;
_updaters[ menuSignUID ] = _updateSign;
// initialize the sign
_redrawMenuSign(sign,cSelectedIndex,displayOptions);
_redrawMenuSign( sign, cSelectedIndex, displayOptions );
/*
whenever a sign is placed somewhere in the world
@ -130,13 +132,15 @@ signs.menu = function(
save its location for loading and initialization
when the server starts up again.
*/
if (save){
if (typeof _store.menus == "undefined")
if ( save ) {
if ( typeof _store.menus == "undefined") {
_store.menus = {};
}
var signLocations = _store.menus[label];
if (typeof signLocations == "undefined")
if ( typeof signLocations == "undefined" ) {
signLocations = _store.menus[label] = [];
signLocations.push(menuSignSaveData);
}
signLocations.push( menuSignSaveData );
}
return sign;
};
@ -148,27 +152,26 @@ signs.menu = function(
world with this same label and make dynamic again.
*/
if (_store.menus && _store.menus[label])
{
var signsOfSameLabel = _store.menus[label];
if ( _store.menus && _store.menus[label] ) {
var signsOfSameLabel = _store.menus[ label ];
var defragged = [];
var len = signsOfSameLabel.length;
for (var i = 0; i < len ; i++)
{
for ( i = 0; i < len; i++ ) {
var loc = signsOfSameLabel[i];
var world = org.bukkit.Bukkit.getWorld(loc.world);
if (!world)
if ( !world ) {
continue;
var block = world.getBlockAt(loc.x,loc.y,loc.z);
if (block.state instanceof org.bukkit.block.Sign){
convertToMenuSign(block.state,false);
defragged.push(loc);
}
var block = world.getBlockAt( loc.x, loc.y, loc.z );
if ( block.state instanceof org.bukkit.block.Sign ) {
convertToMenuSign( block.state, false );
defragged.push( loc );
}
}
/*
remove data for signs which no longer exist.
*/
if (defragged.length != len){
if ( defragged.length != len ) {
_store.menus[label] = defragged;
}
}
@ -178,18 +181,20 @@ signs.menu = function(
//
// 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
a sign, then update it.
*/
if (! event.clickedBlock.state instanceof org.bukkit.block.Sign)
if ( ! event.clickedBlock.state instanceof org.bukkit.block.Sign ) {
return;
}
var evtLocStr = utils.locationToString(event.clickedBlock.location);
var signUpdater = _updaters[evtLocStr]
if (signUpdater)
signUpdater(event.player, event.clickedBlock.state);
var signUpdater = _updaters[evtLocStr];
if ( signUpdater ) {
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 menu = require('./menu');
// include all menu exports
for (var i in menu){
for ( var i in menu ) {
exports[i] = menu[i];
}
exports.getTargetedBy = function( livingEntity ){
exports.getTargetedBy = function( livingEntity ) {
var location = utils.getMousePos( livingEntity );
if (!location)
if ( !location ) {
return null;
}
var state = location.block.state;
if (!(state || state.setLine))
if ( ! (state || state.setLine) ) {
return null;
}
return state;
};

View file

@ -37,7 +37,7 @@ Example
-------
/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>
@ -72,8 +72,8 @@ var formattingCodes = {
underline: c.UNDERLINE,
reset: c.RESET
};
for (var method in formattingCodes){
String.prototype[method] = function(c){
return function(){return c+this;};
}(formattingCodes[method]);
for ( var method in formattingCodes ) {
String.prototype[method] = function( c ) {
return function(){ return c + this; };
}( formattingCodes[method] );
}

View file

@ -36,15 +36,15 @@ String, then it tries to find the player with that name.
***/
var _player = function ( playerName ) {
if (typeof playerName == 'undefined'){
if (typeof self == 'undefined'){
if ( typeof playerName == 'undefined' ) {
if ( typeof self == 'undefined' ) {
return null;
} else {
return self;
}
} else {
if (typeof playerName == 'string')
return org.bukkit.Bukkit.getPlayer(playerName);
if ( typeof playerName == 'string' )
return org.bukkit.Bukkit.getPlayer( playerName );
else
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.
***/
var _locationToJSON = function(location){
var _locationToJSON = function( location ) {
return {
world: ''+location.world.name,
x: location.x,
@ -102,8 +102,8 @@ keys in a lookup table.
lookupTable[key] = player.name;
***/
exports.locationToString = function(location){
return JSON.stringify(_locationToJSON(location));
exports.locationToString = function( location ) {
return JSON.stringify( _locationToJSON( location ) );
};
exports.locationToJSON = _locationToJSON;
@ -117,20 +117,22 @@ returned by locationToJSON() and reconstructs and returns a bukkit
Location object.
***/
exports.locationFromJSON = function(json){
if (json.constuctor == Array){
exports.locationFromJSON = function( json ) {
var world;
if ( json.constuctor == Array ) {
// for support of legacy format
var world = org.bukkit.Bukkit.getWorld(json[0]);
return new org.bukkit.Location(world, json[1], json[2] , json[3]);
}else{
var world = org.bukkit.Bukkit.getWorld(json.world);
return new org.bukkit.Location(world, json.x, json.y , json.z, json.yaw, json.pitch);
world = org.bukkit.Bukkit.getWorld( json[0] );
return new org.bukkit.Location( world, json[1], json[2] , json[3] );
} else {
world = org.bukkit.Bukkit.getWorld( json.world );
return new org.bukkit.Location( world, json.x, json.y , json.z, json.yaw, json.pitch );
}
};
exports.player = _player;
exports.getPlayerObject = function(player){
console.warn('utils.getPlayerObject() is deprecated. Use utils.player() instead.');
exports.getPlayerObject = function( player ) {
console.warn( 'utils.getPlayerObject() is deprecated. Use utils.player() instead.' );
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
***/
exports.getPlayerPos = function( player ) {
player = _player(player);
if (player){
if (player instanceof org.bukkit.command.BlockCommandSender)
player = _player( player );
if ( player ) {
if ( player instanceof org.bukkit.command.BlockCommandSender )
return player.block.location;
else
return player.location;
}
else
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);
if (!player)
if ( !player ) {
return null;
}
// player might be CONSOLE or a CommandBlock
if (!player.getTargetBlock)
if ( !player.getTargetBlock ) {
return null;
var targetedBlock = player.getTargetBlock(null,5);
if (targetedBlock == null || targetedBlock.isEmpty()){
}
var targetedBlock = player.getTargetBlock( null, 5 );
if ( targetedBlock == null || targetedBlock.isEmpty() ) {
return null;
}
return targetedBlock.location;
@ -228,7 +231,7 @@ package for scheduling processing of arrays.
- object : Additional (optional) information passed into the foreach method.
- array : The entire array.
* object (optional) : An object which may be used by the callback.
* context (optional) : An object which may be used by the callback.
* delay (optional, numeric) : If a delay is specified (in ticks - 20
ticks = 1 second), then the processing will be scheduled so that
each item will be processed in turn with a delay between the completion of each
@ -286,18 +289,24 @@ without hogging CPU usage...
utils.foreach (a, processItem, null, 10, onDone);
***/
var _foreach = function(array, callback, object, delay, onCompletion) {
if (array instanceof java.util.Collection)
var _foreach = function( array, callback, context, delay, onCompletion ) {
if ( array instanceof java.util.Collection ) {
array = array.toArray();
}
var i = 0;
var len = array.length;
if (delay){
var next = function(){ callback(array[i],i,object,array); i++;};
var hasNext = function(){return i < len;};
_nicely(next,hasNext,onCompletion,delay);
}else{
for (;i < len; i++){
callback(array[i],i,object,array);
if ( delay ) {
var next = function( ) {
callback(array[i], i, context, array);
i++;
};
var hasNext = function( ) {
return i < len;
};
_nicely( next, hasNext, onCompletion, delay );
} else {
for ( ;i < len; i++ ) {
callback( array[i], i, 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.
***/
var _nicely = function(next, hasNext, onDone, delay){
if (hasNext()){
var _nicely = function( next, hasNext, onDone, delay ) {
if ( hasNext() ){
next();
server.scheduler.runTaskLater(__plugin,function(){
_nicely(next,hasNext,onDone,delay);
},delay);
server.scheduler.runTaskLater( __plugin, function() {
_nicely( next, hasNext, onDone, delay );
}, delay );
}else{
if (onDone)
if ( onDone ) {
onDone();
}
}
};
exports.nicely = _nicely;
/************************************************************************
@ -360,34 +370,34 @@ To warn players when night is approaching...
utils.at( '19:00', function() {
utils.foreach( server.onlinePlayers, function(player){
player.chat('The night is dark and full of terrors!');
utils.foreach( server.onlinePlayers, function( player ) {
player.chat( 'The night is dark and full of terrors!' );
});
});
***/
exports.at = function(time24hr, callback, worlds) {
var forever = function(){ return true;};
var timeParts = time24hr.split(':');
var hrs = ((timeParts[0] * 1000) + 18000) % 24000;
exports.at = function( time24hr, callback, worlds ) {
var forever = function(){ return true; };
var timeParts = time24hr.split( ':' );
var hrs = ( (timeParts[0] * 1000) + 18000 ) % 24000;
var mins;
if (timeParts.length > 1)
mins = (timeParts[1] / 60) * 1000;
if ( timeParts.length > 1 ) {
mins = ( timeParts[1] / 60 ) * 1000;
}
var timeMc = hrs + mins;
if (typeof worlds == 'undefined'){
if ( typeof worlds == 'undefined' ) {
worlds = server.worlds;
}
_nicely(function(){
_foreach (worlds, function (world){
_nicely( function() {
_foreach( worlds, function ( world ) {
var time = world.getTime();
var diff = timeMc - time;
if (diff > 0 && diff < 100){
if ( diff > 0 && diff < 100 ) {
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 recurse = function(dir, store){
var files, dirfile = new java.io.File(dir);
var recurse = function( dir, store ) {
var files, dirfile = new java.io.File( dir );
if (typeof filter == 'undefined')
if ( typeof filter == 'undefined' ) {
files = dirfile.list();
else
} else {
files = dirfile.list(filter);
_foreach(files, function (file){
file = new java.io.File(dir + '/' + file);
if (file.isDirectory()){
recurse(file.canonicalPath, store);
}else{
store.push(file.canonicalPath);
}
_foreach( files, function( file ) {
file = new java.io.File( dir + '/' + file );
if ( file.isDirectory() ) {
recurse( file.canonicalPath, store );
} else {
store.push( file.canonicalPath );
}
});
}
recurse(dir,result);
};
recurse( dir, result );
return result;
}
};

View file

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

View file

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

View file

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

View file

@ -1,4 +1,4 @@
var utils = require('utils');
var foreach = require('utils').foreach;
/************************************************************************
## 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
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)...
/js classroom.allowScripting(false,self)
/js classroom.allowScripting( false, self )
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.
***/
var _store = {enableScripting: false};
var classroom = plugin("classroom", {
allowScripting: function (/* boolean: true or false */ canScript, sender) {
if (typeof sender == 'undefined'){
console.log("Attempt to set classroom scripting without credentials");
console.log("classroom.allowScripting(boolean, sender)");
var _store = { enableScripting: false };
var classroom = plugin('classroom', {
allowScripting: function (/* boolean: true or false */ canScript, sender ) {
if ( typeof sender == 'undefined' ) {
console.log( 'Attempt to set classroom scripting without credentials' );
console.log( 'classroom.allowScripting(boolean, sender)' );
return;
}
if (!sender.op){
console.log("Attempt to set classroom scripting without credentials: " + sender.name);
if ( !sender.op ) {
console.log( 'Attempt to set classroom scripting without credentials: ' + sender.name );
return;
}
/*
only operators should be allowed run this function
*/
if (!sender.isOp())
if ( !sender.isOp() ) {
return;
if (canScript){
utils.foreach( server.onlinePlayers, function (player) {
player.addAttachment(__plugin, "scriptcraft.*", true);
}
if ( canScript ) {
foreach( server.onlinePlayers, function( player ) {
player.addAttachment( __plugin, 'scriptcraft.*', true );
});
}else{
utils.foreach( server.onlinePlayers, function(player) {
utils.foreach(player.getEffectivePermissions(), function(perm) {
if ((""+perm.permission).indexOf("scriptcraft.") == 0){
if (perm.attachment)
} else {
foreach( server.onlinePlayers, function( player ) {
foreach( player.getEffectivePermissions(), function( perm ) {
if ( (''+perm.permission).indexOf( 'scriptcraft.' ) == 0 ) {
if ( perm.attachment ) {
perm.attachment.remove();
}
}
});
});
}
@ -81,10 +83,10 @@ var classroom = plugin("classroom", {
exports.classroom = classroom;
events.on('player.PlayerLoginEvent', function(listener, event) {
events.on( 'player.PlayerLoginEvent', function( listener, event ) {
var player = event.player;
if (_store.enableScripting){
player.addAttachment(__plugin, "scriptcraft.*", true);
if ( _store.enableScripting ) {
player.addAttachment( __plugin, 'scriptcraft.*', true );
}
}, 'HIGHEST');

View file

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

View file

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

View file

@ -307,14 +307,22 @@ var bitmaps = {
/*
wph 20130121 compute the width, and x,y coords of pixels ahead of time
*/
for (var c in bitmaps.raw){
var bits = bitmaps.raw[c];
var width = bits.length/5;
var bmInfo = {"width": width,"pixels":[]}
var c,
bits,
width,
bmInfo,
j;
for ( c in bitmaps.raw ) {
bits = bitmaps.raw[c];
width = bits.length/5;
bmInfo = { width: width, pixels:[] };
bitmaps.computed[c] = bmInfo;
for (var j = 0; j < bits.length; j++){
if (bits.charAt(j) != ' '){
bmInfo.pixels.push([j%width,Math.ceil(j/width)]);
for ( j = 0; j < bits.length; j++ ) {
if ( bits.charAt(j) != ' ' ) {
bmInfo.pixels.push( [
j % width,
Math.ceil( j / width )
] );
}
}
}
@ -328,46 +336,72 @@ for (var c in bitmaps.raw){
// bg
// 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');
if (typeof fg == "undefined")
if ( typeof fg == 'undefined' ) {
fg = blocks.wool.black;
}
var bmfg = this._getBlockIdAndMeta(fg);
var bmbg = null;
if (typeof bg != "undefined")
bmbg = this._getBlockIdAndMeta(bg);
var lines = message.split("\n");
var lineCount = lines.length;
for (var h = 0;h < lineCount; h++) {
var line = lines[h];
line = line.toLowerCase().replace(/[^0-9a-z \.\-\+\/\;\'\:\!]/g,"");
this.up(7*(lineCount-(h+1)));
bmfg = this._getBlockIdAndMeta( fg );
bmbg = null;
if ( typeof bg != 'undefined' ) {
bmbg = this._getBlockIdAndMeta( bg );
}
lines = message.split( '\n' );
lineCount = lines.length;
for (var i =0;i < line.length; i++) {
var ch = line.charAt(i)
var bits = bitmaps.computed[ch];
if (typeof bits == "undefined"){
for ( h = 0; h < lineCount; h++) {
line = lines[h];
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[' '];
}
var charWidth = bits.width;
if (typeof bg != "undefined")
this.cuboidX(bmbg[0],bmbg[1],charWidth,7,1);
for (var j = 0;j < bits.pixels.length;j++){
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');
charWidth = bits.width;
if ( typeof bg != 'undefined' ) {
this.cuboidX( bmbg[0], bmbg[1], charWidth, 7, 1 );
}
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
//
Drone.extend('castle', function(side, height)
{
Drone.extend('castle', function( side, height ) {
//
// use sensible default parameter values
// if no parameters are supplied
//
if (typeof side == "undefined")
if ( typeof side == "undefined" )
side = 24;
if (typeof height == "undefined")
if ( typeof height == "undefined" )
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");
//
// 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)
//
for (var corner = 0; corner < 4; corner++)
{
for ( var corner = 0; corner < 4; corner++ ) {
// construct a 'tower' fort
this.fort(towerSide,towerHeight);
// move forward the length of the castle then turn right

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -12,7 +12,7 @@ var Drone = require('../drone').Drone;
* 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');
for(var i = 0; i < width; ++i) {

View file

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

View file

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

View file

@ -3,19 +3,19 @@ var Drone = require('../drone').Drone;
// constructs a mayan temple
//
Drone.extend('temple', function(side) {
if (!side) {
if ( !side ) {
side = 20;
}
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');
while (side > 4) {
var middle = Math.round((side-2)/2);
while ( side > 4 ) {
var middle = Math.round( (side-2) / 2 );
this.chkpt('corner')
.box(stone, side, 1, side)
.right(middle).box(stair).right().box(stair)
.box( stone, side, 1, side )
.right( middle ).box( stair ).right().box( stair )
.move('corner').up().fwd().right();
side = side - 2;
}

View file

@ -1,6 +1,6 @@
var fireworks = require('fireworks');
var Drone = require('./drone').Drone;
Drone.extend('firework',function() {
fireworks.firework(this.getLocation());
Drone.extend( 'firework', function( ) {
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.
***/
Drone.extend('sphere', function(block,radius)
{
var lastRadius = radius;
var slices = [[radius,0]];
var diameter = radius*2;
var bm = this._getBlockIdAndMeta(block);
Drone.extend( 'sphere', function( block, radius ) {
var lastRadius = radius,
slices = [ [ radius , 0 ] ],
diameter = radius * 2,
bm = this._getBlockIdAndMeta( block ),
r2 = radius * radius,
i = 0,
newRadius,
yOffset,
sr,
sh,
v,
h;
var r2 = radius*radius;
for (var i = 0; i <= radius;i++){
var newRadius = Math.round(Math.sqrt(r2 - i*i));
if (newRadius == lastRadius)
slices[slices.length-1][1]++;
else
slices.push([newRadius,1]);
for ( i = 0; i <= radius; i++ ) {
newRadius = Math.round( Math.sqrt( r2 - i * i ) );
if ( newRadius == lastRadius ) {
slices[ slices.length - 1 ][ 1 ]++;
} else {
slices.push( [ newRadius , 1 ] );
}
lastRadius = newRadius;
}
this.chkpt('sphere');
this.chkpt( 'sphere' );
//
// mid section
//
this.up(radius - slices[0][1])
.cylinder(block,radius,(slices[0][1]*2)-1,{blockType: bm[0],meta: bm[1]})
.down(radius-slices[0][1]);
this.up( radius - slices[0][1] )
.cylinder( block, radius, ( slices[0][1]*2 ) - 1, { blockType: bm[0], meta: bm[1] } )
.down( radius - slices[0][1] );
var yOffset = -1;
for (var i = 1; i < slices.length;i++)
{
yOffset = -1;
for ( i = 1; i < slices.length; i++ ) {
yOffset += slices[i-1][1];
var sr = slices[i][0];
var sh = slices[i][1];
var v = radius + yOffset, h = radius-sr;
sr = slices[i][0];
sh = slices[i][1];
v = radius + yOffset;
h = radius - sr;
// northern hemisphere
this.up(v).fwd(h).right(h)
.cylinder(block,sr,sh,{blockType: bm[0],meta: bm[1]})
.left(h).back(h).down(v);
this.up( v )
.fwd( h )
.right( h )
.cylinder( block, sr, sh, { blockType: bm[0], meta: bm[1] } )
.left( h )
.back( h )
.down( v );
// southern hemisphere
v = radius - (yOffset+sh+1);
this.up(v).fwd(h).right(h)
.cylinder(block,sr,sh,{blockType: bm[0],meta: bm[1]})
.left(h).back(h). down(v);
v = radius - ( yOffset + sh + 1 );
this.up( v )
.fwd( h )
.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
@ -88,79 +103,78 @@ server to be very busy for a couple of minutes while doing so.
***/
Drone.extend('sphere0', function(block,radius)
{
/*
this.sphere(block,radius)
.fwd().right().up()
.sphere(0,radius-1)
.back().left().down();
var lastRadius = radius,
slices = [ [ radius, 0 ] ],
diameter = radius * 2,
bm = this._getBlockIdAndMeta( block ),
r2 = radius*radius,
i,
newRadius,
sr,
sh,
v,
h,
len,
yOffset;
*/
var lastRadius = radius;
var slices = [[radius,0]];
var diameter = radius*2;
var bm = this._getBlockIdAndMeta(block);
var r2 = radius*radius;
for (var i = 0; i <= radius;i++){
var newRadius = Math.round(Math.sqrt(r2 - i*i));
if (newRadius == lastRadius)
slices[slices.length-1][1]++;
else
slices.push([newRadius,1]);
for ( i = 0; i <= radius; i++ ) {
newRadius = Math.round( Math.sqrt( r2 - i * i ) );
if ( newRadius == lastRadius ) {
slices[ slices.length - 1 ][ 1 ]++;
} else {
slices.push( [ newRadius, 1 ] );
}
lastRadius = newRadius;
}
this.chkpt('sphere0');
this.chkpt( 'sphere0' );
//
// mid section
//
//.cylinder(block,radius,(slices[0][1]*2)-1,{blockType: bm[0],meta: bm[1]})
this.up(radius - slices[0][1])
.arc({blockType: bm[0],
this.up( radius - slices[0][1] )
.arc({ blockType: bm[0],
meta: bm[1],
radius: radius,
strokeWidth: 2,
stack: (slices[0][1]*2)-1,
fill: false
})
.down(radius-slices[0][1]);
.down( radius - slices[0][1] );
var yOffset = -1;
var len = slices.length;
for (var i = 1; i < len;i++)
{
yOffset = -1;
len = slices.length;
for ( i = 1; i < len; i++ ) {
yOffset += slices[i-1][1];
var sr = slices[i][0];
var sh = slices[i][1];
var v = radius + yOffset, h = radius-sr;
sr = slices[i][0];
sh = slices[i][1];
v = radius + yOffset;
h = radius-sr;
// northern hemisphere
// .cylinder(block,sr,sh,{blockType: bm[0],meta: bm[1]})
this.up(v).fwd(h).right(h)
this.up( v ).fwd( h ).right( h )
.arc({
blockType: bm[0],
meta: bm[1],
radius: sr,
stack: sh,
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
v = radius - (yOffset+sh+1);
//.cylinder(block,sr,sh,{blockType: bm[0],meta: bm[1]})
this.up(v).fwd(h).right(h)
v = radius - ( yOffset + sh + 1 );
this.up( v ).fwd( h ).right( h )
.arc({
blockType: bm[0],
meta: bm[1],
radius: sr,
stack: sh,
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;
@ -185,55 +199,55 @@ To create a wood 'north' hemisphere with a radius of 7 blocks...
![hemisphere example](img/hemisphereex1.png)
***/
Drone.extend('hemisphere', function(block,radius, northSouth){
var lastRadius = radius;
var slices = [[radius,0]];
var diameter = radius*2;
var bm = this._getBlockIdAndMeta(block);
var r2 = radius*radius;
for (var i = 0; i <= radius;i++){
var newRadius = Math.round(Math.sqrt(r2 - i*i));
if (newRadius == lastRadius)
slices[slices.length-1][1]++;
else
slices.push([newRadius,1]);
Drone.extend( 'hemisphere', function( block, radius, northSouth ) {
var lastRadius = radius,
slices = [ [ radius, 0 ] ],
diameter = radius * 2,
bm = this._getBlockIdAndMeta(block),
r2 = radius * radius,
i = 0,
newRadius;
for ( i = 0; i <= radius; i++ ) {
newRadius = Math.round( Math.sqrt( r2 - i * i ) );
if ( newRadius == lastRadius ) {
slices[ slices.length - 1 ][ 1 ]++;
} else {
slices.push( [ newRadius, 1 ] );
}
lastRadius = newRadius;
}
this.chkpt('hsphere');
this.chkpt( 'hsphere' );
//
// mid section
//
if (northSouth == "north"){
this.cylinder(block,radius,slices[0][1],{blockType: bm[0],meta: bm[1]});
if ( northSouth == 'north' ) {
this.cylinder( block, radius, slices[0][1], { blockType: bm[0], meta: bm[1] } );
} else {
this.up(radius - slices[0][1])
.cylinder(block,radius,slices[0][1],{blockType: bm[0],meta: bm[1]})
.down(radius - slices[0][1]);
this.up( radius - slices[0][1] )
.cylinder( block, radius, slices[0][1], { blockType: bm[0], meta: bm[1] } )
.down( radius - slices[0][1] );
}
var yOffset = -1;
for (var i = 1; i < slices.length;i++)
{
for ( i = 1; i < slices.length; i++ ) {
yOffset += slices[i-1][1];
var sr = slices[i][0];
var sh = slices[i][1];
var v = yOffset, h = radius-sr;
if (northSouth == "north") {
if ( northSouth == 'north' ) {
// northern hemisphere
this.up(v).fwd(h).right(h)
.cylinder(block,sr,sh,{blockType: bm[0],meta: bm[1]})
.left(h).back(h).down(v);
}else{
this.up( v ).fwd( h ).right( h )
.cylinder( block, sr, sh, { blockType: bm[0], meta: bm[1] } )
.left( h ).back( h ).down( v );
} else {
// southern hemisphere
v = radius - (yOffset+sh+1);
this.up(v).fwd(h).right(h)
.cylinder(block,sr,sh,{blockType: bm[0],meta: bm[1]})
.left(h).back(h). down(v);
v = radius - ( yOffset + sh + 1 );
this.up( v ).fwd( h ).right( h )
.cylinder( block, sr, sh, { blockType: bm[0], meta: bm[1] } )
.left( h ).back( h ).down( v );
}
}
return this.move('hsphere');
return this.move( 'hsphere' );
});
/************************************************************************
### Drone.hemisphere0() method
@ -255,9 +269,9 @@ To create a glass 'north' hemisphere with a radius of 20 blocks...
![hemisphere example](img/hemisphereex2.png)
***/
Drone.extend('hemisphere0', function(block,radius,northSouth){
return this.hemisphere(block,radius,northSouth)
.fwd().right().up(northSouth=="north"?0:1)
.hemisphere(0,radius-1,northSouth)
.back().left().down(northSouth=="north"?0:1);
Drone.extend( 'hemisphere0', function( block, radius, northSouth ) {
return this.hemisphere( block, radius, northSouth)
.fwd().right().up( northSouth == 'north' ? 0 : 1 )
.hemisphere( 0, radius-1, northSouth )
.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){
player.sendMessage('Hello ' + player.name);
exports.hello = function( player ) {
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) {
player.sendMessage('Hello ' + player.name);
command( 'hello', function( parameters, player ) {
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
*/
if (!player.op){
player.sendMessage('Only operators can do this.');
if ( !player.op ) {
player.sendMessage( 'Only operators can do this.' );
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
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] ;
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]
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 `.
*/
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...
var greetings = require('./example-1-hello-module');
command('hello-module', function( parameters, player ){
greetings.hello(player);
command( 'hello-module', function( parameters, player ) {
greetings.hello( player );
});
***/
var greetings = require('./example-1-hello-module');
command('hello-module', function( parameters, player ){
greetings.hello(player);
command( 'hello-module', function( parameters, player ) {
greetings.hello( player );
});

View file

@ -32,13 +32,14 @@ Source Code ...
var utils = require('utils');
var greetings = require('./example-1-hello-module');
command('hello-byname', function( parameters, sender ) {
command( 'hello-byname', function( parameters, sender ) {
var playerName = parameters[0];
var recipient = utils.player(playerName);
if (recipient)
greetings.hello(recipient);
else
sender.sendMessage('Player ' + playerName + ' not found.');
var recipient = utils.player( playerName );
if ( recipient ) {
greetings.hello( recipient );
} else {
sender.sendMessage( 'Player ' + playerName + ' not found.' );
}
});
***/
@ -46,11 +47,12 @@ Source Code ...
var utils = require('utils');
var greetings = require('./example-1-hello-module');
command('hello-byname', function( parameters, sender ) {
command( 'hello-byname', function( parameters, sender ) {
var playerName = parameters[0];
var recipient = utils.player(playerName);
if (recipient)
greetings.hello(recipient);
else
sender.sendMessage('Player ' + playerName + ' not found.');
var recipient = utils.player( playerName );
if ( recipient ) {
greetings.hello( recipient );
} else {
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()
[bkapi]: http://jd.bukkit.org/dev/apidocs/
events.on('player.PlayerJoinEvent', function (listener, event){
if (event.player.op) {
events.on( 'player.PlayerJoinEvent', function( listener, event ) {
if ( event.player.op ) {
event.player.sendMessage('Welcome to ' + __plugin);
}
});
***/
events.on('player.PlayerJoinEvent', function (listener, event){
if (event.player.op) {
event.player.sendMessage('Welcome to ' + __plugin);
events.on( 'player.PlayerJoinEvent', function( listener, event ) {
if ( event.player.op ) {
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.
***/
var utils = require('utils');
var _store = {
houses: {},
openHouses: {},
invites: {}
};
var utils = require('utils'),
TeleportCause = org.bukkit.event.player.PlayerTeleportEvent.TeleportCause,
_store = {
houses: { },
openHouses: { },
invites: { }
};
/*
*/
var homes = plugin("homes", {
help: function(){
var homes = plugin( 'homes', {
help: function( ) {
return [
/* basic functions */
"/jsp home : Return to your own home",
"/jsp home <player> : Go to player's home",
"/jsp home set : Set your current location as home",
"/jsp home delete : Delete your home location",
'/jsp home : Return to your own home',
'/jsp home <player> : Go to player home',
'/jsp home set : Set your current location as home',
'/jsp home delete : Delete your home location',
/* social */
"/jsp home list : List homes you can visit",
"/jsp home ilist : List players who can visit your home",
"/jsp home invite <player> : Invite <player> to your home",
"/jsp home uninvite <player> : Uninvite <player> to your home",
"/jsp home public : Open your home to all players",
"/jsp home private : Make your home private",
'/jsp home list : List homes you can visit',
'/jsp home ilist : List players who can visit your home',
'/jsp home invite <player> : Invite <player> to your home',
'/jsp home uninvite <player> : Uninvite <player> to your home',
'/jsp home public : Open your home to all players',
'/jsp home private : Make your home private',
/* administration */
"/jsp home listall : Show all houses (ops only)",
"/jsp home clear <player> : Clears player's home location (ops only)"
'/jsp home listall : Show all houses (ops only)',
'/jsp home clear <player> : Clears player home location (ops only)'
];
},
/* ========================================================================
basic functions
======================================================================== */
go: function(guest, host){
if (typeof host == "undefined")
go: function( guest, host ) {
var loc,
homeLoc;
if ( typeof host == 'undefined' ) {
host = guest;
guest = utils.player(guest);
host = utils.player(host);
var loc = _store.houses[host.name];
if (!loc){
guest.sendMessage(host.name + " has no home");
}
guest = utils.player( guest );
host = utils.player( host );
loc = _store.houses[ host.name ];
if ( !loc ) {
guest.sendMessage( host.name + ' has no home' );
return;
}
if (!this._canVisit(guest,host)){
guest.sendMessage("You can't visit " + host.name + "'s home yet");
if ( !this._canVisit( guest, host ) ) {
guest.sendMessage( 'You can not visit ' + host.name + "'s home yet" );
return;
}
var teleportCause = org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
var homeLoc = utils.locationFromJSON(loc);
guest.teleport(homeLoc, teleportCause.PLUGIN);
homeLoc = utils.locationFromJSON( loc );
guest.teleport(homeLoc, TeleportCause.PLUGIN);
},
/*
determine whether a guest is allow visit a host's home
*/
_canVisit: function(guest, host){
if (guest == host)
_canVisit: function( guest, host ) {
var invitations,
i;
if ( guest == host ) {
return true;
if (_store.openHouses[host.name])
}
if ( _store.openHouses[ host.name ] ) {
return true;
var invitations = _store.invites[host.name];
if (invitations)
for (var i = 0;i < invitations.length;i++)
if (invitations[i] == guest.name)
}
invitations = _store.invites[ host.name ];
if ( invitations ) {
for ( i = 0; i < invitations.length; i++ ) {
if ( invitations[i] == guest.name ) {
return true;
}
}
}
return false;
},
set: function(player){
player = utils.player(player);
set: function( player ) {
player = utils.player( player );
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);
delete _store.houses[player.name];
remove: function( player ) {
player = utils.player( player );
delete _store.houses[ player.name ];
},
/* ========================================================================
social functions
@ -142,198 +155,249 @@ var homes = plugin("homes", {
/*
list homes which the player can visit
*/
list: function(player){
var result = [];
for (var ohp in _store.openHouses)
list: function( player ) {
var result = [],
ohp,
host,
guests,
i;
for ( ohp in _store.openHouses ) {
result.push(ohp);
}
player = utils.player(player);
for (var host in _store.invites){
var guests = _store.invites[host];
for (var i = 0;i < guests.length; i++)
if (guests[i] == player.name)
for ( host in _store.invites ) {
guests = _store.invites[host];
for ( i = 0; i < guests.length; i++ ) {
if ( guests[i] == player.name ) {
result.push(host);
}
}
}
return result;
},
/*
list who can visit the player's home
list who can visit the player home
*/
ilist: function(player){
player = utils.player(player);
var result = [];
ilist: function( player ) {
var result = [],
onlinePlayers,
i;
player = utils.player( player );
// if home is public - all players
if (_store.openHouses[player.name]){
var online = org.bukkit.Bukkit.getOnlinePlayers();
for (var i = 0;i < online.length; i++)
if (online[i].name != player.name)
result.push(online[i].name);
}else{
if (_store.invites[player.name])
result = _store.invites[player.name];
else
if ( _store.openHouses[player.name] ) {
onlinePlayers = org.bukkit.Bukkit.getOnlinePlayers();
for ( i = 0; i < onlinePlayers.length; i++ ) {
if ( onlinePlayers[i].name != player.name) {
result.push( onlinePlayers[i].name );
}
}
} else {
if ( _store.invites[player.name] ) {
result = _store.invites[ player.name ];
} else {
result = [];
}
}
return result;
},
/*
Invite a player to the home
*/
invite: function(host, guest){
host = utils.player(host);
guest = utils.player(guest);
invite: function( host, guest ) {
host = utils.player( host );
guest = utils.player( guest );
var invitations = [];
if (_store.invites[host.name])
if ( _store.invites[host.name] ) {
invitations = _store.invites[host.name];
invitations.push(guest.name);
}
invitations.push( guest.name );
_store.invites[host.name] = invitations;
guest.sendMessage(host.name + " has invited you to their home.");
guest.sendMessage("type '/jsp home " + host.name + "' to accept");
guest.sendMessage( host.name + ' has invited you to their home.' );
guest.sendMessage( 'type "/jsp home ' + host.name + '" to accept' );
},
/*
Uninvite someone to the home
*/
uninvite: function(host, guest){
host = utils.player(host);
guest = utils.player(guest);
var invitations = _store.invites[host.name];
if (!invitations)
uninvite: function( host, guest ) {
var invitations,
revisedInvites,
i;
host = utils.player( host );
guest = utils.player( guest );
invitations = _store.invites[ host.name ];
if ( !invitations ) {
return;
var revisedInvites = [];
for (var i =0;i < invitations.length; i++)
if (invitations[i] != guest.name)
revisedInvites.push(invitations[i]);
}
revisedInvites = [];
for ( i = 0; i < invitations.length; i++ ) {
if ( invitations[i] != guest.name ) {
revisedInvites.push( invitations[i] );
}
}
_store.invites[host.name] = revisedInvites;
},
/*
make the player's house public
make the player house public
*/
open: function(player, optionalMsg){
player = utils.player(player);
_store.openHouses[player.name] = true;
if (typeof optionalMsg != "undefined")
__plugin.server.broadcastMessage(optionalMsg);
open: function( player, optionalMsg ) {
player = utils.player( player );
_store.openHouses[ player.name ] = true;
if ( typeof optionalMsg != 'undefined' ) {
__plugin.server.broadcastMessage( optionalMsg );
}
},
/*
make the player's house private
make the player house private
*/
close: function(player){
player = utils.player(player);
delete _store.openHouses[player.name];
close: function( player ) {
player = utils.player( player );
delete _store.openHouses[ player.name ];
},
/* ========================================================================
admin functions
======================================================================== */
listall: function(){
listall: function( ) {
var result = [];
for (var home in _store.houses)
for ( var home in _store.houses ) {
result.push(home);
}
return result;
},
clear: function(player){
player = utils.player(player);
delete _store.houses[player.name];
delete _store.openHouses[player.name];
clear: function( player ) {
player = utils.player( player );
delete _store.houses[ player.name ];
delete _store.openHouses[ player.name ];
},
store: _store
}, true);
}, true );
exports.homes = homes;
/*
define a set of command options that can be used by players
*/
*/
var options = {
'set': function(params, sender){ homes.set(sender); },
'delete': function(params, sender ){ homes.remove(sender);},
'help': function(params, sender){ sender.sendMessage(homes.help());},
'list': function(params, sender){
'set': function( params, sender ) {
homes.set( sender );
},
'delete': function( params, sender ) {
homes.remove( sender );
},
'help': function( params, sender ) {
sender.sendMessage( homes.help() );
},
'list': function( params, sender ) {
var visitable = homes.list();
if (visitable.length == 0){
sender.sendMessage("There are no homes to visit");
if ( visitable.length == 0 ) {
sender.sendMessage( 'There are no homes to visit' );
return;
}else{
} else {
sender.sendMessage([
"You can visit any of these " + visitable.length + " homes"
,visitable.join(", ")
'You can visit any of these ' + visitable.length + ' homes'
,visitable.join(', ')
]);
}
},
'ilist': function(params, sender){
'ilist': function( params, sender ) {
var potentialVisitors = homes.ilist();
if (potentialVisitors.length == 0)
sender.sendMessage("No one can visit your home");
else
if ( potentialVisitors.length == 0 ) {
sender.sendMessage('No one can visit your home');
} else {
sender.sendMessage([
"These " + potentialVisitors.length + "players can visit your home",
potentialVisitors.join(", ")]);
'These ' + potentialVisitors.length + 'players can visit your home',
potentialVisitors.join(', ')]);
}
},
'invite': function(params,sender){
if (params.length == 1){
sender.sendMessage("You must provide a player's name");
'invite': function( params, sender ) {
if ( params.length == 1 ) {
sender.sendMessage( 'You must provide a player name' );
return;
}
var playerName = params[1];
var guest = utils.player(playerName);
if (!guest)
sender.sendMessage(playerName + " is not here");
else
homes.invite(sender,guest);
var guest = utils.player( playerName );
if ( !guest ) {
sender.sendMessage( playerName + ' is not here' );
} else {
homes.invite( sender, guest );
}
},
'uninvite': function(params,sender){
if (params.length == 1){
sender.sendMessage("You must provide a player's name");
'uninvite': function( params, sender ) {
if ( params.length == 1 ) {
sender.sendMessage( 'You must provide a player name' );
return;
}
var playerName = params[1];
var guest = utils.player(playerName);
if (!guest)
sender.sendMessage(playerName + " is not here");
else
homes.uninvite(sender,guest);
var guest = utils.player( playerName );
if ( !guest ) {
sender.sendMessage( playerName + ' is not here' );
} else {
homes.uninvite( sender, guest );
}
},
'public': function(params,sender){
homes.open(sender,params.slice(1).join(' '));
sender.sendMessage("Your home is open to the public");
'public': function( params, sender ) {
homes.open( sender, params.slice( 1 ).join(' ') );
sender.sendMessage( 'Your home is open to the public' );
},
'private': function(params, sender){
homes.close(sender);
sender.sendMessage("Your home is closed to the public");
'private': function( params, sender ) {
homes.close( sender );
sender.sendMessage( 'Your home is closed to the public' );
},
'listall': function(params, sender){
if (!sender.isOp())
sender.sendMessage("Only operators can do this");
else
sender.sendMessage(homes.listall().join(", "));
'listall': function( params, sender ) {
if ( !sender.isOp() ) {
sender.sendMessage( 'Only operators can do this' );
} else {
sender.sendMessage( homes.listall().join(', ') );
}
},
'clear': function(params,sender){
if (!sender.isOp())
sender.sendMessage("Only operators can do this");
else
homes.clear(params[1], sender);
'clear': function( params, sender ) {
if ( !sender.isOp() ) {
sender.sendMessage( 'Only operators can do this' );
} else {
homes.clear( params[1], sender );
}
}
};
var optionList = [];
for (var o in options)
for ( var o in options ) {
optionList.push(o);
}
/*
Expose a set of commands that players can use at the in-game command prompt
*/
command("home", function ( params , sender) {
if (params.length == 0){
homes.go(sender,sender);
*/
command( 'home', function ( params , sender) {
var option,
host;
if ( params.length == 0 ) {
homes.go( sender, sender );
return;
}
var option = options[params[0]];
if (option)
option(params,sender);
else{
var host = utils.player(params[0]);
if (!host)
sender.sendMessage(params[0] + " is not here");
else
homes.go(sender,host);
option = options[ params[0] ];
if ( option ) {
option( params, sender );
} else {
host = utils.player( params[0] );
if ( !host ) {
sender.sendMessage( params[0] + ' is not here' );
} else {
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.
***/
var Prompt = org.bukkit.conversations.Prompt,
ConversationFactory = org.bukkit.conversations.ConversationFactory,
ConversationPrefix = org.bukkit.conversations.ConversationPrefix;
var sb = function(cmd){
org.bukkit.Bukkit.dispatchCommand(server.consoleSender, 'scoreboard ' + cmd)
var sb = function( cmd ) {
org.bukkit.Bukkit.dispatchCommand( server.consoleSender, 'scoreboard ' + cmd ) ;
};
exports.Game_NumberGuess = {
start: function(sender) {
start: function( sender ) {
var guesses = 0;
sb('objectives add NumberGuess dummy Guesses');
sb('players set ' + sender.name + ' NumberGuess ' + guesses);
sb('objectives setdisplay sidebar NumberGuess');
sb( 'objectives add NumberGuess dummy Guesses' );
sb( 'players set ' + sender.name + ' NumberGuess ' + guesses );
sb( 'objectives setdisplay sidebar NumberGuess' );
var Prompt = org.bukkit.conversations.Prompt;
var ConversationFactory = org.bukkit.conversations.ConversationFactory;
var ConversationPrefix = org.bukkit.conversations.ConversationPrefix;
var number = Math.ceil( Math.random() * 10 );
var number = Math.ceil(Math.random() * 10);
var prompt = new Prompt( ) {
var prompt = new Prompt()
{
getPromptText: function(ctx){
var hint = "";
var h = ctx.getSessionData("hint");
if (h){
getPromptText: function( ctx ) {
var hint = '';
var h = ctx.getSessionData( 'hint' );
if ( h ) {
hint = h;
}
return hint + "Think of a number between 1 and 10";
return hint + 'Think of a number between 1 and 10';
},
acceptInput: function(ctx, s)
{
s = s.replace(/^[^0-9]+/,""); // strip leading non-numeric characters (e.g. '/' )
s = parseInt(s);
if (s == number){
setTimeout(function(){
ctx.forWhom.sendRawMessage("You guessed Correct!");
sb('objectives remove NumberGuess');
},100);
acceptInput: function( ctx, s ) {
s = s.replace( /^[^0-9]+/, '' ); // strip leading non-numeric characters (e.g. '/' )
s = parseInt( s );
if ( s == number ) {
setTimeout(function( ) {
ctx.forWhom.sendRawMessage( 'You guessed Correct!' );
sb( 'objectives remove NumberGuess' );
}, 100 );
return null;
}else{
if (s < number)
ctx.setSessionData("hint","too low\n");
if (s > number)
ctx.setSessionData("hint","too high\n");
} else {
if ( s < number ) {
ctx.setSessionData( 'hint', 'too low\n' );
}
if ( s > number ) {
ctx.setSessionData( 'hint', 'too high\n' );
}
guesses++;
sb('players set ' + sender.name + ' NumberGuess ' + guesses);
sb( 'players set ' + sender.name + ' NumberGuess ' + guesses );
return prompt;
}
},
blocksForInput: function(ctx){ return true; }
blocksForInput: function( ctx ) {
return true;
}
};
var cf = new ConversationFactory(__plugin);
var conv = cf.withModality(true)
.withFirstPrompt(prompt)
.withPrefix(new ConversationPrefix(){ getPrefix: function(ctx){ return "[1-10] ";} })
.buildConversation(sender);
conv.begin();
var convPrefix = new ConversationPrefix( ) {
getPrefix: function( ctx ) {
return '[1-10] ';
}
};
new ConversationFactory( __plugin )
.withModality( true )
.withFirstPrompt( prompt )
.withPrefix( convPrefix )
.buildConversation( sender )
.begin( );
}
};

View file

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

View file

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

View file

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

View file

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