From 7457cd58b83bd23dedba2b26f77c1423affbf698 Mon Sep 17 00:00:00 2001 From: walterhiggins Date: Wed, 29 Jan 2014 19:49:15 +0000 Subject: [PATCH] Changed formatting to use idiomatic style. (like glasses-mode in emacs) --- docs/API-Reference.md | 110 +- src/main/js/lib/command.js | 50 +- src/main/js/lib/console.js | 50 +- src/main/js/lib/events.js | 92 +- src/main/js/lib/js-patch.js | 57 +- src/main/js/lib/persistence.js | 73 +- src/main/js/lib/plugin.js | 79 +- src/main/js/lib/require.js | 144 +- src/main/js/lib/scriptcraft.js | 471 +++-- src/main/js/lib/tabcomplete-jsp.js | 68 +- src/main/js/lib/tabcomplete.js | 305 +-- src/main/js/modules/blocks.js | 490 ++--- src/main/js/modules/fireworks/fireworks.js | 77 +- src/main/js/modules/http/request.js | 132 +- src/main/js/modules/minigames/scoreboard.js | 81 +- src/main/js/modules/partial.js | 14 - src/main/js/modules/sc-mqtt.js | 86 +- src/main/js/modules/signs/menu.js | 309 +-- src/main/js/modules/signs/signs.js | 22 +- src/main/js/modules/utils/string-exts.js | 64 +- src/main/js/modules/utils/utils.js | 256 +-- src/main/js/plugins/alias/alias.js | 155 +- src/main/js/plugins/arrows.js | 192 +- src/main/js/plugins/chat/color.js | 100 +- src/main/js/plugins/classroom/classroom.js | 88 +- src/main/js/plugins/commando/commando-test.js | 33 +- src/main/js/plugins/commando/commando.js | 64 +- src/main/js/plugins/drone/blocktype.js | 124 +- src/main/js/plugins/drone/contrib/castle.js | 86 +- .../js/plugins/drone/contrib/chessboard.js | 46 +- src/main/js/plugins/drone/contrib/cottage.js | 104 +- src/main/js/plugins/drone/contrib/fort.js | 123 +- .../js/plugins/drone/contrib/lcd-clock.js | 20 +- src/main/js/plugins/drone/contrib/rainbow.js | 45 +- src/main/js/plugins/drone/contrib/rboxcall.js | 30 +- .../drone/contrib/skyscraper-example.js | 28 +- src/main/js/plugins/drone/contrib/streamer.js | 38 +- src/main/js/plugins/drone/contrib/temple.js | 12 +- src/main/js/plugins/drone/drone-firework.js | 4 +- src/main/js/plugins/drone/drone.js | 1820 +++++++++-------- src/main/js/plugins/drone/sphere.js | 338 +-- .../examples/example-1-hello-module.js | 4 +- .../examples/example-2-hello-command.js | 4 +- .../examples/example-3-hello-ops-only.js | 18 +- .../examples/example-4-hello-parameters.js | 28 +- .../examples/example-5-hello-using-module.js | 8 +- .../examples/example-6-hello-player.js | 30 +- .../examples/example-7-hello-events.js | 16 +- src/main/js/plugins/homes/homes.js | 584 +++--- src/main/js/plugins/minigames/NumberGuess.js | 115 +- .../js/plugins/minigames/SnowballFight.js | 289 +-- src/main/js/plugins/minigames/cow-clicker.js | 256 +-- src/main/js/plugins/spawn.js | 33 +- src/main/resources/boot.js | 145 +- 54 files changed, 4161 insertions(+), 3849 deletions(-) delete mode 100644 src/main/js/modules/partial.js diff --git a/docs/API-Reference.md b/docs/API-Reference.md index 3977782..099909e 100644 --- a/docs/API-Reference.md +++ b/docs/API-Reference.md @@ -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 );

Hello World

@@ -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,9 +1276,9 @@ 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) { - var salutation = parameters[0] ; - player.sendMessage( salutation + ' ' + player.name); + command( 'hello-params', function ( parameters, player ) { + var salutation = parameters[0] ; + 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 ) { - var playerName = parameters[0]; - var recipient = utils.player(playerName); - if (recipient) - greetings.hello(recipient); - else - sender.sendMessage('Player ' + playerName + ' not found.'); + 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.' ); + } }); ## Example Plugin #7 - Listening for events, Greet players when they join the game. @@ -2379,10 +2383,10 @@ 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) { - event.player.sendMessage('Welcome to ' + __plugin); - } + events.on( 'player.PlayerJoinEvent', function( listener, event ) { + if ( event.player.op ) { + event.player.sendMessage('Welcome to ' + __plugin); + } }); ## Arrows 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. diff --git a/src/main/js/lib/command.js b/src/main/js/lib/command.js index 61e0c60..6f2ae12 100644 --- a/src/main/js/lib/command.js +++ b/src/main/js/lib/command.js @@ -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; diff --git a/src/main/js/lib/console.js b/src/main/js/lib/console.js index 91c437b..75a2287 100644 --- a/src/main/js/lib/console.js +++ b/src/main/js/lib/console.js @@ -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 result = []; - for (var i =0;i < args.length; i++) - result.push(args[i]); - return result; +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++ ) { + 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 ); }; diff --git a/src/main/js/lib/events.js b/src/main/js/lib/events.js index 63f8b88..7a0fd44 100644 --- a/src/main/js/lib/events.js +++ b/src/main/js/lib/events.js @@ -75,53 +75,55 @@ 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 */ - eventType, - /* function( registeredListener, event) */ - handler, - /* (optional) String (HIGH, HIGHEST, LOW, LOWEST, NORMAL, MONITOR), */ - priority ) { + /* String or java Class */ + eventType, + /* function( registeredListener, event) */ + handler, + /* (optional) String (HIGH, HIGHEST, LOW, LOWEST, NORMAL, MONITOR), */ + priority ) { + var handlerList, + listener = {}, + eventExecutor; - if (typeof priority == "undefined"){ - priority = bkEvent.EventPriority.HIGHEST; - }else{ - priority = bkEvent.EventPriority[priority]; + if ( typeof priority == 'undefined' ) { + priority = bkEvent.EventPriority.HIGHEST; + } else { + priority = bkEvent.EventPriority[priority]; + } + 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' ) { + // nashorn environment + eventType = Java.type( 'org.bukkit.event.' + eventType ); + } else { + eventType = eval( 'org.bukkit.event.' + eventType ); } - 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'){ - // nashorn environment - eventType = Java.type('org.bukkit.event.' + eventType); - } else { - eventType = eval('org.bukkit.event.' + eventType); - } - } - var handlerList = eventType.getHandlerList(); - var listener = {}; - var eventExecutor = new bkEvtExecutor(){ - execute: function(l,e){ - handler(listener.reg,e); - } - }; - /* - wph 20130222 issue #64 bad interaction with Essentials plugin - if another plugin tries to unregister a Listener (not a Plugin or a RegisteredListener) - then BOOM! the other plugin will throw an error because Rhino can't coerce an - equals() method from an Interface. - 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); - return listener.reg; + } + handlerList = eventType.getHandlerList( ); + eventExecutor = new bkEvtExecutor( ) { + execute: function( l, e ) { + handler( listener.reg, e ); + } + }; + /* + wph 20130222 issue #64 bad interaction with Essentials plugin + if another plugin tries to unregister a Listener (not a Plugin or a RegisteredListener) + then BOOM! the other plugin will throw an error because Rhino can't coerce an + equals() method from an Interface. + 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 ); + return listener.reg; }; diff --git a/src/main/js/lib/js-patch.js b/src/main/js/lib/js-patch.js index 4403bbc..e291b61 100644 --- a/src/main/js/lib/js-patch.js +++ b/src/main/js/lib/js-patch.js @@ -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,''); - }; - } + // 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, '' ); + }; + } - $.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); - return bukkitTask; - }; - $.clearTimeout = function(bukkitTask){ - bukkitTask.cancel(); - }; + $.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 ); + return bukkitTask; + }; + + $.clearTimeout = function( bukkitTask ) { + bukkitTask.cancel(); + }; - $.setInterval = function(callback, intervalInMillis){ - var delay = intervalInMillis/ 50; - var bukkitTask = server.scheduler.runTaskTimer(__plugin, callback, delay, delay); - return bukkitTask; - }; - $.clearInterval = function(bukkitTask){ - bukkitTask.cancel(); - }; + $.setInterval = function( callback, intervalInMillis ) { + var delay = intervalInMillis/ 50; + var bukkitTask = server.scheduler.runTaskTimer( __plugin, callback, delay, delay ); + return bukkitTask; + }; + + $.clearInterval = function( bukkitTask ) { + bukkitTask.cancel(); + }; + }; diff --git a/src/main/js/lib/persistence.js b/src/main/js/lib/persistence.js index cea7147..1b82231 100644 --- a/src/main/js/lib/persistence.js +++ b/src/main/js/lib/persistence.js @@ -1,37 +1,50 @@ +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') - data = {}; - if (typeof write == 'undefined') - write = false; - if (!write){ - dataFromFile = $.scload(_dataDir.canonicalPath + '/' + name + '-store.json'); - if (dataFromFile){ - for (i in dataFromFile){ - data[i] = dataFromFile[i]; - } - } - }else{ - // flush data to file - $.scsave(data, _dataDir.canonicalPath + '/' + name + '-store.json'); + $.persist = function( name, data, write ) { + var i, + dataFromFile; + if ( typeof data == 'undefined' ) { + data = {}; + } + if ( typeof write == 'undefined' ) { + write = false; + } + if ( !write ) { + dataFromFile = _load( name ); + if ( dataFromFile ) { + for ( i in dataFromFile ) { + data[i] = dataFromFile[i]; } - _persistentData[name] = data; - return data; - }; - - $.addUnloadHandler(function(){ - for (var name in _persistentData){ - var data = _persistentData[name]; - $.scsave(data, _dataDir.canonicalPath + '/' + name + '-store.json'); - } - }); + } + } else { + // flush data to file + _save( name, data ); + } + _persistentData[name] = data; + return data; + }; + /* + persist on shutdown + */ + $.addUnloadHandler( function( ) { + var name, + data; + for ( name in _persistentData ) { + data = _persistentData[name]; + _save( name, data ); + } + }); }; diff --git a/src/main/js/lib/plugin.js b/src/main/js/lib/plugin.js index 819461d..448d0a2 100644 --- a/src/main/js/lib/plugin.js +++ b/src/main/js/lib/plugin.js @@ -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)); }; diff --git a/src/main/js/lib/require.js b/src/main/js/lib/require.js index 64e39e4..30d0c79 100644 --- a/src/main/js/lib/require.js +++ b/src/main/js/lib/require.js @@ -54,46 +54,45 @@ 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 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()){ - return mainFile; - } else { - return null; - } - }else{ - // look for an index.js file - var indexJsFile = new File(dir + './index.js'); - if (indexJsFile.exists()){ - return indexJsFile; - } else { - return null; - } - } - }; + // 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() ) { + return mainFile; + } else { + return null; + } + } else { + // look for an index.js file + var indexJsFile = new File( dir + './index.js' ); + if ( indexJsFile.exists() ) { + return indexJsFile; + } else { + return null; + } + } + }; - var fileExists = function(file) { - if (file.isDirectory()){ - return readModuleFromDirectory(file); - }else { - return file; - } - }; + var fileExists = function( file ) { + if ( file.isDirectory() ) { + return readModuleFromDirectory( file ); + } else { + return file; + } + }; - var _canonize = function(file){ - return "" + file.canonicalPath.replaceAll("\\\\","/"); - }; + var _canonize = function(file){ + return "" + file.canonicalPath.replaceAll("\\\\","/"); + }; - var resolveModuleToFile = function(moduleName, parentDir) { /********************************************************************** ### module name resolution @@ -128,48 +127,49 @@ 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 file = new File(moduleName); + var resolveModuleToFile = function ( moduleName, parentDir ) { + var file = new File(moduleName); - if (file.exists()){ - return fileExists(file); + if ( file.exists() ) { + return fileExists(file); + } + if ( moduleName.match( /^[^\.\/]/ ) ) { + // it's a module named like so ... 'events' , 'net/http' + // + var resolvedFile; + for (var i = 0;i < modulePaths.length; i++){ + resolvedFile = new File(modulePaths[i] + moduleName); + if (resolvedFile.exists()){ + return fileExists(resolvedFile); + }else{ + // try appending a .js to the end + resolvedFile = new File(modulePaths[i] + moduleName + '.js'); + if (resolvedFile.exists()) + return resolvedFile; } - if (moduleName.match(/^[^\.\/]/)){ - // it's a module named like so ... 'events' , 'net/http' - // - var resolvedFile; - for (var i = 0;i < modulePaths.length; i++){ - resolvedFile = new File(modulePaths[i] + moduleName); - if (resolvedFile.exists()){ - return fileExists(resolvedFile); - }else{ - // try appending a .js to the end - resolvedFile = new File(modulePaths[i] + moduleName + '.js'); - if (resolvedFile.exists()) - return resolvedFile; - } - } - } else { - // it's of the form ./path - file = new File(parentDir, moduleName); - if (file.exists()){ - return fileExists(file); - }else { + } + } else { + // it's of the form ./path + file = new File(parentDir, moduleName); + if (file.exists()){ + return fileExists(file); + }else { - // try appending a .js to the end - var pathWithJSExt = file.canonicalPath + '.js'; - file = new File( parentDir, pathWithJSExt); - if (file.exists()) - return file; - else{ - file = new File(pathWithJSExt); - if (file.exists()) - return file; - } - - } + // try appending a .js to the end + var pathWithJSExt = file.canonicalPath + '.js'; + file = new File( parentDir, pathWithJSExt); + if (file.exists()) + return file; + else{ + file = new File(pathWithJSExt); + if (file.exists()) + return file; } - return null; - }; + + } + } + return null; + }; /* wph 20131215 Experimental */ diff --git a/src/main/js/lib/scriptcraft.js b/src/main/js/lib/scriptcraft.js index a8d393f..38ca67b 100644 --- a/src/main/js/lib/scriptcraft.js +++ b/src/main/js/lib/scriptcraft.js @@ -413,238 +413,257 @@ 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 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; + var _canonize = function( file ) { + return '' + file.getCanonicalPath().replaceAll( '\\\\', '/' ); + }; + // 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); - return; - } - var f = (filename instanceof File) ? filename : new File(filename); - var 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); - }; + /* + Save a javascript object to a file (saves using JSON notation) + */ + 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; } - - /* - Load the contents of the file and evaluate as javascript - */ - var _load = function(filename,warnOnFileNotFound) + 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 ); + }; + } + + /* + Load the contents of the file and evaluate as javascript + */ + var _load = function( filename, warnOnFileNotFound ) + { + var result = null, + file = filename, + r, + parent, + reader, + br, + code, + wrappedCode; + + if ( !( filename instanceof File ) ) { + file = new File(filename); + } + var canonizedFilename = _canonize( file ); + + 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 ); + } + finally { + try { + reader.close(); + } catch ( re ) { + // fail silently on reader close error + } + } + } 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 }; + } + global.config = config; + global.__plugin = __plugin; + /* + wph 20131229 Issue #103 JSON is not bundled with javax.scripting / Rhino on Mac. + */ + (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 _runUnloadHandlers = function() { + for ( var i = 0; i < unloadHandlers.length; i++ ) { + unloadHandlers[i]( ); + } + }; + global.addUnloadHandler = _addUnloadHandler; + + + global.refresh = function( ) { + __plugin.pluginLoader.disablePlugin( __plugin ); + __plugin.pluginLoader.enablePlugin( __plugin ); + }; + + var _echo = function ( msg ) { + if ( typeof self == 'undefined' ) { + return; + } + self.sendMessage( msg ); + }; + + global.echo = _echo; + global.alert = _echo; + global.scload = _load; + global.scsave = _save; + + var configRequire = _load( jsPluginsRootDirName + '/lib/require.js', true ); + /* + setup paths to search for 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) ); + } + var requireHooks = { + loading: function( path ) { + if ( config.verbose ) { + logger.info( 'loading ' + path ); + } + }, + loaded: function( path ) { + if ( config.verbose ) { + logger.info( 'loaded ' + path ); + } + } + }; + global.require = configRequire( jsPluginsRootDirName, modulePaths, requireHooks ); + + require('js-patch')( global ); + global.console = require('console'); + /* + setup persistence + */ + require('persistence')( jsPluginsRootDir, global ); + + var cmdModule = require('command'); + global.command = cmdModule.command; + var plugins = require('plugin'); + global.__onTabComplete = require('tabcomplete'); + global.plugin = plugins.plugin; + + var events = require('events'); + events.on( 'server.PluginDisableEvent', function( l, e ) { + // save config + _save( global.config, new File( jsPluginsRootDir, 'data/global-config.json' ) ); + + _runUnloadHandlers(); + org.bukkit.event.HandlerList['unregisterAll(org.bukkit.plugin.Plugin)'](__plugin); + }); + // wph 20131226 - make events global as it is used by many plugins/modules + global.events = events; + + + global.__onCommand = function( sender, cmd, label, args) { + var jsArgs = []; + var i = 0; + for ( ; i < args.length ; i++ ) { + jsArgs.push( '' + args[i] ); + } + + var result = false; + var cmdName = ( '' + cmd.name ).toLowerCase(); + if (cmdName == 'js') { - var result = null - ,file = filename - ,r = undefined; - - if (!(filename instanceof File)) - file = new File(filename); - - var canonizedFilename = _canonize(file); - - if (file.exists()) { - var parent = file.getParentFile(); - var reader = new FileReader(file); - var br = new BufferedReader(reader); - var code = ""; - var wrappedCode; - 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 ); - } - finally { - try { - reader.close(); - }catch (re){ - // fail silently on reader close error - } - } - }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}; - 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'))); - - /* - Unload Handlers - */ - var unloadHandlers = []; - var _addUnloadHandler = function(f) { - unloadHandlers.push(f); - }; - var _runUnloadHandlers = function() { - for (var i = 0; i < unloadHandlers.length; i++) { - unloadHandlers[i](); - } - }; - - global.refresh = function(){ - __plugin.pluginLoader.disablePlugin(__plugin); - __plugin.pluginLoader.enablePlugin(__plugin); - }; - - var _echo = function (msg) { - if (typeof self == "undefined"){ - return; - } - self.sendMessage(msg); - }; - - global.echo = _echo; - global.alert = _echo; - global.scload = _load; - global.scsave = _save; - - global.addUnloadHandler = _addUnloadHandler; - - var configRequire = _load(jsPluginsRootDirName + '/lib/require.js',true); - /* - setup paths to search for 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)); + result = true; + var fnBody = jsArgs.join(' '); + global.self = sender; + global.__engine = __engine; + try { + var jsResult = __engine.eval(fnBody); + if ( jsResult ) { + sender.sendMessage(jsResult); + } + } catch ( e ) { + logger.severe( 'Error while trying to evaluate javascript: ' + fnBody + ', Error: '+ e ); + throw e; + } finally { + delete global.self; + delete global.__engine; + } } - var requireHooks = { - loading: function(path){ - if (config.verbose) - logger.info('loading ' + path); - }, - loaded: function(path){ - if (config.verbose) - logger.info('loaded ' + path); - } - }; - global.require = configRequire(jsPluginsRootDirName, modulePaths,requireHooks ); - - require('js-patch')(global); - global.console = require('console'); - /* - setup persistence - */ - require('persistence')(jsPluginsRootDir,global); - - var cmdModule = require('command'); - global.command = cmdModule.command; - var plugins = require('plugin'); - global.__onTabComplete = require('tabcomplete'); - global.plugin = plugins.plugin; - - var events = require('events'); - events.on('server.PluginDisableEvent',function(l,e){ - // save config - _save(global.config, new File(jsPluginsRootDir, 'data/global-config.json' )); - - _runUnloadHandlers(); - org.bukkit.event.HandlerList['unregisterAll(org.bukkit.plugin.Plugin)'](__plugin); - }); - // wph 20131226 - make events global as it is used by many plugins/modules - global.events = events; - - - global.__onCommand = function( sender, cmd, label, args) { - var jsArgs = []; - var i = 0; - for (;i < args.length; i++) { - jsArgs.push('' + args[i]); - } - - var result = false; - var cmdName = ('' + cmd.name).toLowerCase(); - if (cmdName == 'js') - { - result = true; - var fnBody = jsArgs.join(' '); - global.self = sender; - global.__engine = __engine; - try { - var jsResult = __engine.eval(fnBody); - if (jsResult) - sender.sendMessage(jsResult); - }catch (e){ - logger.severe("Error while trying to evaluate javascript: " + fnBody + ", Error: "+ e); - throw e; - }finally{ - delete global.self; - delete global.__engine; - } - } - if (cmdName == 'jsp'){ - cmdModule.exec(jsArgs, sender); - result = true; - } - return result; - }; - - 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()){ - legacyExists = true; - console.warn('Legacy ScriptCraft directory %s was found. This directory is no longer used.', - legacyDirs[i].canonicalPath); - } + if ( cmdName == 'jsp' ) { + cmdModule.exec( jsArgs, sender ); + result = true; } - if (legacyExists){ - console.info('Please note that the working directory for %s is %s', - __plugin, jsPluginsRootDir.canonicalPath); + return result; + }; + + plugins.autoload( jsPluginsRootDir, logger ); + /* + wph 20140102 - warn if legacy 'craftbukkit/js-plugins' or 'craftbukkit/scriptcraft' directories are present + */ + (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 ); + } + })(); + } diff --git a/src/main/js/lib/tabcomplete-jsp.js b/src/main/js/lib/tabcomplete-jsp.js index 29490c2..3ed61cb 100644 --- a/src/main/js/lib/tabcomplete-jsp.js +++ b/src/main/js/lib/tabcomplete-jsp.js @@ -3,39 +3,45 @@ 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{ - // 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]); - } - } - } - }else{ - if (cmdArgs.length == 0){ - for (var 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); - } - } +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 ( i = 0; i < len; i++ ) { + if ( opts[i].indexOf( cmdArgs[1] ) == 0 ) { + result.add( opts[i] ); } + } } - return result; + } else { + if ( cmdArgs.length == 0 ) { + for ( i in _commands ) { + result.add( i ); + } + } else { + // partial e.g. /jsp ho + // should tabcomplete to home + // + for ( i in _commands ) { + if ( i.indexOf( cmdInput ) == 0 ) { + result.add( i ); + } + } + } + } + return result; }; module.exports = __onTabCompleteJSP; diff --git a/src/main/js/lib/tabcomplete.js b/src/main/js/lib/tabcomplete.js index 04aac7b..a1114f0 100644 --- a/src/main/js/lib/tabcomplete.js +++ b/src/main/js/lib/tabcomplete.js @@ -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) @@ -15,165 +15,180 @@ var _isJavaObject = function(o){ return result; }; var _javaLangObjectMethods = [ - 'equals' - ,'getClass' - ,'class' - ,'getClass' - ,'hashCode' - ,'notify' - ,'notifyAll' - ,'toString' - ,'wait' - ,'clone' - ,'finalize' + 'equals' + ,'getClass' + ,'class' + ,'getClass' + ,'hashCode' + ,'notify' + ,'notifyAll' + ,'toString' + ,'wait' + ,'clone' + ,'finalize' ]; - -var _getProperties = function(o) -{ - var result = []; - if (_isJavaObject(o)) - { - propertyLoop: - for (var i in o) - { - // - // don't include standard Object methods - // - var isObjectMethod = false; - for (var j = 0;j < _javaLangObjectMethods.length; j++) - if (_javaLangObjectMethods[j] == i) - continue propertyLoop; - var typeofProperty = null; - try { - typeofProperty = typeof o[i]; - }catch( e ){ - if (e.message == 'java.lang.IllegalStateException: Entity not leashed'){ - // wph 20131020 fail silently for Entity leashing in craftbukkit - }else{ - throw e; - } - } - if (typeofProperty == 'function' ) - result.push(i+'()'); - else - result.push(i); - } - }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); - } + +var _getProperties = function( o ) { + var result = [], + i, + j, + isObjectMethod, + typeofProperty; + if ( _isJavaObject( o ) ) { + propertyLoop: + for ( i in o ) { + // + // don't include standard Object methods + // + isObjectMethod = false; + for ( j = 0; j < _javaLangObjectMethods.length; j++ ) { + if ( _javaLangObjectMethods[j] == i ) { + continue propertyLoop; + } + } + typeofProperty = null; + try { + typeofProperty = typeof o[i]; + } catch( e ) { + if ( e.message == 'java.lang.IllegalStateException: Entity not leashed' ) { + // wph 20131020 fail silently for Entity leashing in craftbukkit + } else { + throw e; } + } + if ( typeofProperty == 'function' ) { + result.push( i+'()' ); + } else { + result.push( i ); + } } - return result.sort(); + } else { + if ( o.constructor == Array ) { + return result; + } + 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') - return tabCompleteJSP( result, cmdSender, pluginCmd, cmdAlias, cmdArgs ); + cmdArgs = Array.prototype.slice.call( cmdArgs, 0 ); - global.self = cmdSender; // bring in self just for autocomplete + 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(' '); - - statement = statement.replace(/^\s+/,'').replace(/\s+$/,''); - - - if (statement.length == 0) - propsOfLastArg = _globalSymbols; - else{ - var statementSyms = statement.split(/[^\$a-zA-Z0-9_\.]/); - var lastSymbol = statementSyms[statementSyms.length-1]; - //print('DEBUG: lastSymbol=[' + lastSymbol + ']'); + lastArg = cmdArgs.length?cmdArgs[cmdArgs.length-1]+'':null; + propsOfLastArg = []; + statement = cmdArgs.join(' '); + + statement = statement.replace(/^\s+/,'').replace(/\s+$/,''); + + if ( statement.length == 0 ) { + propsOfLastArg = _globalSymbols; + } 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. + // + 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' ) { + break; + } + lastGoodSymbol = symbol; + } + //print('debug:name['+name+']lastSymbol['+lastSymbol+']symbol['+symbol+']'); + if ( typeof symbol == 'undefined' ) { // - // try to complete the object ala java IDEs. + // look up partial matches against last good symbol // - 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++){ - name = parts[i]; - symbol = symbol[name]; - if (typeof symbol == 'undefined') - break; - lastGoodSymbol = symbol; + objectProps = _getProperties( lastGoodSymbol ); + if ( name == '' ) { + // if the last symbol looks like this.. + // ScriptCraft. + // + + for ( i =0; i < objectProps.length; i++ ) { + candidate = lastSymbol + objectProps[i]; + re = new RegExp( lastSymbol + '$', 'g' ); + propsOfLastArg.push( lastArg.replace( re, candidate ) ); + } + + } else { + // it looks like this.. + // ScriptCraft.co + // + //print('debug:case Y: ScriptCraft.co'); + + 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]; + re = new RegExp( lastSymbol + '$', 'g' ); + propsOfLastArg.push( lastArg.replace( re, candidate ) ); } - //print('debug:name['+name+']lastSymbol['+lastSymbol+']symbol['+symbol+']'); - if (typeof symbol == 'undefined'){ - // - // look up partial matches against last good symbol - // - var 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)); - } - - }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)); - 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)); - } - } - - } - }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{ - //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 { + objectProps = _getProperties( symbol ); + for ( i = 0; i < objectProps.length; i++ ) { + re = new RegExp( lastSymbol+ '$', 'g' ); + propsOfLastArg.push( lastArg.replace( re, lastSymbol + '.' + objectProps[i] ) ); + } + } + } 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 + delete global.self; // delete self when no longer needed for autocomplete }; module.exports = onTabCompleteJS; diff --git a/src/main/js/modules/blocks.js b/src/main/js/modules/blocks.js index b16d358..ae4fcd8 100644 --- a/src/main/js/modules/blocks.js +++ b/src/main/js/modules/blocks.js @@ -21,261 +21,261 @@ The blocks module is globally exported by the Drone module. ***/ var blocks = { - air: 0, - stone: 1, - grass: 2, - dirt: 3, - cobblestone: 4, - oak: 5, - spruce: '5:1', - birch: '5:2', - jungle: '5:3', - sapling: { - oak: 6, - spruce: '6:1', - birch: '6:2', - jungle: '6:3' - }, - bedrock: 7, - water: 8, - water_still: 9, - lava: 10, - lava_still: 11, - sand: 12, - gravel: 13, - gold_ore: 14, - iron_ore: 15, - coal_ore: 16, - wood: 17, - leaves: 18, - sponge: 19, - glass: 20, - lapis_lazuli_ore: 21, - lapis_lazuli_block: 22, - dispenser: 23, - sandstone: 24, - note: 25, - bed: 26, - powered_rail: 27, - detector_rail: 28, - sticky_piston: 29, - cobweb: 30, - grass_tall: 31, - dead_bush: 32, - piston: 33, - piston_extn: 34, - wool: { - white: 35 // All other colors added below - }, - dandelion: 37, - flower_yellow: 37, - rose: 38, - flower_red: 38, - mushroom_brown: 39, - mushroom_red: 40, - gold: 41, - iron: 42, - tnt: 46, - bookshelf: 47, - moss_stone: 48, - obsidian: 49, - torch: 50, - fire: 51, - monster_spawner: 52, - stairs: { - oak: 53, - cobblestone: 67, - brick: 108, - stone: 109, - nether: 114, - sandstone: 128, - spruce: 134, - birch: 135, - jungle: 136, - quartz: 156 - }, - chest: 54, - redstone_wire: 55, - diamond_ore: 56, - diamond: 57, - crafting_table: 58, - wheat_seeds: 59, - farmland: 60, - furnace: 61, - furnace_burning: 62, - sign_post: 63, - door_wood: 64, - ladder: 65, - rail: 66, - sign: 68, - lever: 69, - pressure_plate_stone: 70, - door_iron: 71, - pressure_plate_wood: 72, - redstone_ore: 73, - redstone_ore_glowing: 74, - torch_redstone: 75, - torch_redstone_active: 76, - stone_button: 77, - ice: 79, - snow: 80, - cactus: 81, - clay: 82, - sugar_cane: 83, - jukebox: 84, - fence: 85, - pumpkin: 86, - netherrack: 87, - soulsand: 88, - glowstone: 89, - netherportal: 90, - jackolantern: 91, - cake: 92, - redstone_repeater: 93, - redeston_repeater_active: 94, - chest_locked: 95, - trapdoor: 96, - monster_egg: 97, - brick: { - stone: 98, - mossy: '98:1', - cracked: '98:2', - chiseled: '98:3', - red: 45 - }, - mushroom_brown_huge: 99, - mushroom_red_huge: 100, - iron_bars: 101, - glass_pane: 102, - melon: 103, - pumpkin_stem: 104, - melon_stem: 105, - vines: 106, - fence_gate: 107, - mycelium: 110, - lily_pad: 111, - nether: 112, - nether_fence: 113, - netherwart: 115, - table_enchantment: 116, - brewing_stand: 117, - cauldron: 118, - endportal: 119, - endportal_frame: 120, - endstone: 121, - dragon_egg: 122, - redstone_lamp: 123, - redstone_lamp_active: 124, - slab: { - snow: 78, - stone: 44, - sandstone: '44:1', - wooden: '44:2', - cobblestone: '44:3', - brick: '44:4', - stonebrick: '44:5', - netherbrick:'44:6', - quartz: '44:7', - oak: 126, - spruce: '126:1', - birch: '126:2', - jungle: '126:3', - upper: { - stone: '44:8', - sandstone: '44:9', - wooden: '44:10', - cobblestone: '44:11', - brick: '44:12', - stonebrick: '44:13', - netherbrick:'44:14', - quartz: '44:15', - oak: '126:8', - spruce: '126:9', - birch: '126:10', - jungle: '126:11', - } - }, - cocoa: 127, - emerald_ore: 129, - enderchest: 130, - tripwire_hook: 131, - tripwire: 132, - emerald: 133, - command: 137, - beacon: 138, - cobblestone_wall: 139, - flowerpot: 140, - carrots: 141, - potatoes: 142, - button_wood: 143, - mobhead: 144, - anvil: 145, - chest_trapped: 146, - pressure_plate_weighted_light: 147, - pressure_plate_weighted_heavy: 148, - redstone_comparator: 149, - redstone_comparator_active: 150, - daylight_sensor: 151, - redstone: 152, - netherquartzore: 153, - hopper: 154, - quartz: 155, - rail_activator: 157, - dropper: 158, - stained_clay: { - white: 159 // All other colors added below - }, - hay: 170, - carpet: { - white: 171 // All other colors added below - }, - hardened_clay: 172, - coal_block: 173 + air: 0, + stone: 1, + grass: 2, + dirt: 3, + cobblestone: 4, + oak: 5, + spruce: '5:1', + birch: '5:2', + jungle: '5:3', + sapling: { + oak: 6, + spruce: '6:1', + birch: '6:2', + jungle: '6:3' + }, + bedrock: 7, + water: 8, + water_still: 9, + lava: 10, + lava_still: 11, + sand: 12, + gravel: 13, + gold_ore: 14, + iron_ore: 15, + coal_ore: 16, + wood: 17, + leaves: 18, + sponge: 19, + glass: 20, + lapis_lazuli_ore: 21, + lapis_lazuli_block: 22, + dispenser: 23, + sandstone: 24, + note: 25, + bed: 26, + powered_rail: 27, + detector_rail: 28, + sticky_piston: 29, + cobweb: 30, + grass_tall: 31, + dead_bush: 32, + piston: 33, + piston_extn: 34, + wool: { + white: 35 // All other colors added below + }, + dandelion: 37, + flower_yellow: 37, + rose: 38, + flower_red: 38, + mushroom_brown: 39, + mushroom_red: 40, + gold: 41, + iron: 42, + tnt: 46, + bookshelf: 47, + moss_stone: 48, + obsidian: 49, + torch: 50, + fire: 51, + monster_spawner: 52, + stairs: { + oak: 53, + cobblestone: 67, + brick: 108, + stone: 109, + nether: 114, + sandstone: 128, + spruce: 134, + birch: 135, + jungle: 136, + quartz: 156 + }, + chest: 54, + redstone_wire: 55, + diamond_ore: 56, + diamond: 57, + crafting_table: 58, + wheat_seeds: 59, + farmland: 60, + furnace: 61, + furnace_burning: 62, + sign_post: 63, + door_wood: 64, + ladder: 65, + rail: 66, + sign: 68, + lever: 69, + pressure_plate_stone: 70, + door_iron: 71, + pressure_plate_wood: 72, + redstone_ore: 73, + redstone_ore_glowing: 74, + torch_redstone: 75, + torch_redstone_active: 76, + stone_button: 77, + ice: 79, + snow: 80, + cactus: 81, + clay: 82, + sugar_cane: 83, + jukebox: 84, + fence: 85, + pumpkin: 86, + netherrack: 87, + soulsand: 88, + glowstone: 89, + netherportal: 90, + jackolantern: 91, + cake: 92, + redstone_repeater: 93, + redeston_repeater_active: 94, + chest_locked: 95, + trapdoor: 96, + monster_egg: 97, + brick: { + stone: 98, + mossy: '98:1', + cracked: '98:2', + chiseled: '98:3', + red: 45 + }, + mushroom_brown_huge: 99, + mushroom_red_huge: 100, + iron_bars: 101, + glass_pane: 102, + melon: 103, + pumpkin_stem: 104, + melon_stem: 105, + vines: 106, + fence_gate: 107, + mycelium: 110, + lily_pad: 111, + nether: 112, + nether_fence: 113, + netherwart: 115, + table_enchantment: 116, + brewing_stand: 117, + cauldron: 118, + endportal: 119, + endportal_frame: 120, + endstone: 121, + dragon_egg: 122, + redstone_lamp: 123, + redstone_lamp_active: 124, + slab: { + snow: 78, + stone: 44, + sandstone: '44:1', + wooden: '44:2', + cobblestone: '44:3', + brick: '44:4', + stonebrick: '44:5', + netherbrick:'44:6', + quartz: '44:7', + oak: 126, + spruce: '126:1', + birch: '126:2', + jungle: '126:3', + upper: { + stone: '44:8', + sandstone: '44:9', + wooden: '44:10', + cobblestone: '44:11', + brick: '44:12', + stonebrick: '44:13', + netherbrick:'44:14', + quartz: '44:15', + oak: '126:8', + spruce: '126:9', + birch: '126:10', + jungle: '126:11' + } + }, + cocoa: 127, + emerald_ore: 129, + enderchest: 130, + tripwire_hook: 131, + tripwire: 132, + emerald: 133, + command: 137, + beacon: 138, + cobblestone_wall: 139, + flowerpot: 140, + carrots: 141, + potatoes: 142, + button_wood: 143, + mobhead: 144, + anvil: 145, + chest_trapped: 146, + pressure_plate_weighted_light: 147, + pressure_plate_weighted_heavy: 148, + redstone_comparator: 149, + redstone_comparator_active: 150, + daylight_sensor: 151, + redstone: 152, + netherquartzore: 153, + hopper: 154, + quartz: 155, + rail_activator: 157, + dropper: 158, + stained_clay: { + white: 159 // All other colors added below + }, + hay: 170, + carpet: { + white: 171 // All other colors added below + }, + hardened_clay: 172, + coal_block: 173 }; // Add all available colors to colorized block collections var colors = { - orange: ':1', - magenta: ':2', - lightblue: ':3', - yellow: ':4', - lime: ':5', - pink: ':6', - gray: ':7', - lightgray: ':8', - cyan: ':9', - purple: ':10', - blue: ':11', - brown: ':12', - green: ':13', - red: ':14', - black: ':15' + orange: ':1', + magenta: ':2', + lightblue: ':3', + yellow: ':4', + lime: ':5', + pink: ':6', + gray: ':7', + lightgray: ':8', + cyan: ':9', + purple: ':10', + blue: ':11', + brown: ':12', + green: ':13', + 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], - data_value = blocks[block].white; - - for (var color in colors) { - blocks[block][color] = data_value + colors[color]; - } + var block = colorized_blocks[i], + data_value = blocks[block].white; + + for (var color in colors) { + blocks[block][color] = data_value + colors[color]; + } }; /* - rainbow colors - a convenience - 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.wool.orange, - blocks.wool.yellow, - blocks.wool.lime, - blocks.wool.lightblue, - blocks.wool.blue, - blocks.wool.purple]; - + rainbow colors - a convenience + 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.wool.orange, + blocks.wool.yellow, + blocks.wool.lime, + blocks.wool.lightblue, + blocks.wool.blue, + blocks.wool.purple]; module.exports = blocks; diff --git a/src/main/js/modules/fireworks/fireworks.js b/src/main/js/modules/fireworks/fireworks.js index 6e59003..bcaffe3 100644 --- a/src/main/js/modules/fireworks/fireworks.js +++ b/src/main/js/modules/fireworks/fireworks.js @@ -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,44 +36,45 @@ location. For example... /* create a firework at the given location */ -var firework = function(location){ - var Color = org.bukkit.Color; - var FireworkEffect = org.bukkit.FireworkEffect; - var EntityType = org.bukkit.entity.EntityType; +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 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, - Color.ORANGE, Color.PURPLE, Color.RED, Color.SILVER, Color.TEAL, - Color.WHITE, Color.YELLOW]; - return colors[i]; - }; - var fw = location.world.spawnEntity(location, EntityType.FIREWORK); - var fwm = fw.getFireworkMeta(); - var fwTypes = [FireworkEffect.Type.BALL, - FireworkEffect.Type.BALL_LARGE, - FireworkEffect.Type.BURST, - FireworkEffect.Type.CREEPER, - FireworkEffect.Type.STAR]; - var type = fwTypes[randInt(5)]; - - 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); - var effect = effectBuilder.build(); - fwm.addEffect(effect); - fwm.setPower(randInt(2)+1); - fw.setFireworkMeta(fwm); + var randInt = function( n ) { + return Math.floor( Math.random() * n ); + }; + 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, + Color.ORANGE, Color.PURPLE, Color.RED, Color.SILVER, Color.TEAL, + Color.WHITE, Color.YELLOW]; + return colors[i]; + }; + var fw = location.world.spawnEntity(location, EntityType.FIREWORK); + var fwm = fw.getFireworkMeta(); + var fwTypes = [FireworkEffect.Type.BALL, + FireworkEffect.Type.BALL_LARGE, + FireworkEffect.Type.BURST, + FireworkEffect.Type.CREEPER, + FireworkEffect.Type.STAR]; + var type = fwTypes[ randInt( 5 ) ]; + + 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 ); + var effect = effectBuilder.build(); + fwm.addEffect( effect ); + fwm.setPower( randInt( 2 ) + 1 ); + fw.setFireworkMeta( fwm ); }; exports.firework = firework; diff --git a/src/main/js/modules/http/request.js b/src/main/js/modules/http/request.js index 00d2965..713d69b 100644 --- a/src/main/js/modules/http/request.js +++ b/src/main/js/modules/http/request.js @@ -37,74 +37,76 @@ 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); - } - for (var 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() - { - var url, paramsAsString, conn, requestMethod; - if (typeof request === "string"){ - url = request; - requestMethod = "GET"; - }else{ - paramsAsString = paramsToString(request.params); - if (request.method) - requestMethod = request.method - else - requestMethod = "GET"; +exports.request = function( request, callback ) { + var paramsToString = function( params ) { + var result = '', + paramNames = [], + i; + for ( i in params ) { + paramNames.push( i ); + } + 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() { + var url, paramsAsString, conn, requestMethod; + if (typeof request === 'string'){ + url = request; + requestMethod = 'GET'; + }else{ + 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; + } + } + conn = new java.net.URL( url ).openConnection(); + conn.requestMethod = requestMethod; + conn.doOutput = true; + conn.instanceFollowRedirects = false; - if (requestMethod == "GET" && request.params){ - // append each parameter to the URL - url = request.url + "?" + paramsAsString; - } - } - conn = new java.net.URL(url).openConnection(); - conn.requestMethod = requestMethod; - conn.doOutput = true; - conn.instanceFollowRedirects = false; - - 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.useCaches =false ; - wr = new java.io.DataOutputStream(conn.getOutputStream ()); - wr.writeBytes(paramsAsString); - wr.flush(); - wr.close(); - } - var rc = conn.responseCode; - var response; - var stream; - if (rc == 200){ - stream = conn.getInputStream(); - response = new java.util.Scanner(stream).useDelimiter("\\A").next(); - } - server.scheduler.runTask(__plugin,function(){ - callback(rc,response); - }); + 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.useCaches =false ; + wr = new java.io.DataOutputStream(conn.getOutputStream ()); + wr.writeBytes(paramsAsString); + wr.flush(); + wr.close(); + } + var rc = conn.responseCode; + var response; + var stream; + if ( rc == 200 ) { + stream = conn.getInputStream(); + response = new java.util.Scanner( stream ).useDelimiter("\\A").next(); + } + server.scheduler.runTask( __plugin, function( ) { + callback( rc, response ); }); + }); }; diff --git a/src/main/js/modules/minigames/scoreboard.js b/src/main/js/modules/minigames/scoreboard.js index 20d8628..c526203 100644 --- a/src/main/js/modules/minigames/scoreboard.js +++ b/src/main/js/modules/minigames/scoreboard.js @@ -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){ - var temp = {}; - var ccScoreboard; - var DisplaySlot = org.bukkit.scoreboard.DisplaySlot; +module.exports = function( options ) { + var temp = {}; + var ccScoreboard; + var DisplaySlot = org.bukkit.scoreboard.DisplaySlot; - return { - start: function(){ - var objective, slot; - 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]; - } - } - }, - stop: function(){ - var objective, slot; - for (objective in options){ - ccScoreboard.getObjective(objective).unregister(); - for (slot in options[objective]){ - ccScoreboard.clearSlot(DisplaySlot[slot]); - } - } - }, - 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; - }, - restore: function(player){ - // offlineplayers don't have a scoreboard - if (player.scoreboard) - player.scoreboard = temp[player.name]; + return { + start: function( ) { + var objective, + slot, + ccObj; + ccScoreboard = server.scoreboardManager.getNewScoreboard(); + 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 ) { + ccScoreboard.getObjective(objective).unregister(); + for ( slot in options[ objective ] ) { + ccScoreboard.clearSlot( DisplaySlot[ slot ] ); + } + } + }, + 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; + }, + restore: function( player ) { + // offlineplayers don't have a scoreboard + if ( player.scoreboard ) { + player.scoreboard = temp[ player.name ]; + } + } + }; }; diff --git a/src/main/js/modules/partial.js b/src/main/js/modules/partial.js deleted file mode 100644 index f9c40f7..0000000 --- a/src/main/js/modules/partial.js +++ /dev/null @@ -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); - }; -} diff --git a/src/main/js/modules/sc-mqtt.js b/src/main/js/modules/sc-mqtt.js index 80b35ab..2846b49 100644 --- a/src/main/js/modules/sc-mqtt.js +++ b/src/main/js/modules/sc-mqtt.js @@ -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 ); }; diff --git a/src/main/js/modules/signs/menu.js b/src/main/js/modules/signs/menu.js index 32aba39..16c011f 100644 --- a/src/main/js/modules/signs/menu.js +++ b/src/main/js/modules/signs/menu.js @@ -8,35 +8,39 @@ var _store = {}; */ var signs = plugin("signs", { /* - construct an interactive menu which can then be attached to a Sign. - */ + construct an interactive menu which can then be attached to a Sign. + */ menu: function( - /* String */ label, - /* Array */ options, - /* Function */ onInteract, - /* Number */ defaultSelection ){}, + /* String */ label, + /* Array */ options, + /* 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; - // 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) - text = p_displayOptions[offset+i]; - if (offset+i == p_selectedIndex) - text = ("" + text).replace(/^ /,">"); - p_sign.setLine(i+1,text); +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 ( i = 0;i < 3; i++ ) { + text = ""; + if ( offset+i < optLen ) { + text = p_displayOptions[offset+i]; } - 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,152 +48,153 @@ 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 -) -{ - - 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 optLen = options.length; - var displayOptions = []; - for (var i =0;i < options.length;i++){ - displayOptions[i] = (" " + options[i] + optionPadding).substring(0,15); +signs.menu = function( /* String */ label, /* Array */ options, /* Function */ callback, /* Number */ selectedIndex ) { + + if ( typeof selectedIndex == "undefined" ) { + selectedIndex = 0; + } + // + // variables common to all instances of this menu can go here + // + var labelPadding = "---------------"; + var optionPadding = " "; + var i; + var paddedLabel = ( labelPadding + label + labelPadding) + .substr( ( ( label.length+30 ) / 2 ) - 7, 15 ); + var optLen = options.length; + var displayOptions = []; + for ( i = 0; i < options.length; i++ ) { + displayOptions[i] = (" " + options[i] + optionPadding).substring(0,15); + } + /* + this function is returned by signs.menu and when it is invoked it will + attach menu behaviour to an existing sign in the world. + 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) { + var mouseLoc; + if (typeof save == "undefined") { + save = true; } /* - this function is returned by signs.menu and when it is invoked it will - attach menu behaviour to an existing sign in the world. - 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") - 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){ - sign = mouseLoc.block.state; - if (!(sign && sign.setLine)){ - throw new Error("You must first provide a sign!"); - } - }else{ - throw new Error("You must first provide a sign!"); - } + @deprecated start + all calls should explicitly provide a [org.bukkit.block.Sign][buksign] parameter. + */ + if ( typeof sign == "undefined" ) { + mouseLoc = utils.getMousePos(); + if ( mouseLoc ) { + sign = mouseLoc.block.state; + if ( !( sign && sign.setLine ) ) { + throw new Error("You must first provide a sign!"); } - /* - @deprecated end - */ - // - // 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: p_sign, - 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); - /* - keep a reference to the update function for use by the event handler - */ - _updaters[menuSignUID] = _updateSign; - - // initialize the sign - _redrawMenuSign(sign,cSelectedIndex,displayOptions); - - /* - whenever a sign is placed somewhere in the world - (which is what this function does) - save its location for loading and initialization - when the server starts up again. - */ - if (save){ - if (typeof _store.menus == "undefined") - _store.menus = {}; - var signLocations = _store.menus[label]; - if (typeof signLocations == "undefined") - signLocations = _store.menus[label] = []; - signLocations.push(menuSignSaveData); - } - return sign; + } else { + throw new Error("You must first provide a sign!"); + } + } + /* + @deprecated end + */ + // + // 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: p_sign, + 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 ); /* - a new sign definition - need to store (in-memory only) - its behaviour and bring back to life other signs of the - same type in the world. Look for other static signs in the - world with this same label and make dynamic again. - */ + keep a reference to the update function for use by the event handler + */ + _updaters[ menuSignUID ] = _updateSign; - if (_store.menus && _store.menus[label]) - { - var signsOfSameLabel = _store.menus[label]; - var defragged = []; - var len = signsOfSameLabel.length; - for (var i = 0; i < len ; i++) - { - var loc = signsOfSameLabel[i]; - var world = org.bukkit.Bukkit.getWorld(loc.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); - } - } - /* - remove data for signs which no longer exist. - */ - if (defragged.length != len){ - _store.menus[label] = defragged; - } + // initialize the sign + _redrawMenuSign( sign, cSelectedIndex, displayOptions ); + + /* + whenever a sign is placed somewhere in the world + (which is what this function does) + save its location for loading and initialization + when the server starts up again. + */ + if ( save ) { + if ( typeof _store.menus == "undefined") { + _store.menus = {}; + } + var signLocations = _store.menus[label]; + if ( typeof signLocations == "undefined" ) { + signLocations = _store.menus[label] = []; + } + signLocations.push( menuSignSaveData ); } - return convertToMenuSign; + return sign; + }; + + /* + a new sign definition - need to store (in-memory only) + its behaviour and bring back to life other signs of the + same type in the world. Look for other static signs in the + world with this same label and make dynamic again. + */ + + if ( _store.menus && _store.menus[label] ) { + var signsOfSameLabel = _store.menus[ label ]; + var defragged = []; + var len = signsOfSameLabel.length; + for ( i = 0; i < len; i++ ) { + var loc = signsOfSameLabel[i]; + var world = org.bukkit.Bukkit.getWorld(loc.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 ); + } + } + /* + remove data for signs which no longer exist. + */ + if ( defragged.length != len ) { + _store.menus[label] = defragged; + } + } + return convertToMenuSign; }; // // update it every time player interacts with it. // -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. - */ +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) - return; - var evtLocStr = utils.locationToString(event.clickedBlock.location); - var signUpdater = _updaters[evtLocStr] - if (signUpdater) - signUpdater(event.player, event.clickedBlock.state); + 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 ); + } }); diff --git a/src/main/js/modules/signs/signs.js b/src/main/js/modules/signs/signs.js index 686a6b1..7c5c8a6 100644 --- a/src/main/js/modules/signs/signs.js +++ b/src/main/js/modules/signs/signs.js @@ -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){ - exports[i] = menu[i]; +for ( var i in menu ) { + exports[i] = menu[i]; } -exports.getTargetedBy = function( livingEntity ){ - var location = utils.getMousePos( livingEntity ); - if (!location) - return null; - var state = location.block.state; - if (!(state || state.setLine)) - return null; - return state; +exports.getTargetedBy = function( livingEntity ) { + var location = utils.getMousePos( livingEntity ); + if ( !location ) { + return null; + } + var state = location.block.state; + if ( ! (state || state.setLine) ) { + return null; + } + return state; }; diff --git a/src/main/js/modules/utils/string-exts.js b/src/main/js/modules/utils/string-exts.js index bb33e23..8167636 100644 --- a/src/main/js/modules/utils/string-exts.js +++ b/src/main/js/modules/utils/string-exts.js @@ -37,43 +37,43 @@ Example ------- /js var boldGoldText = "Hello World".bold().gold(); - /js self.sendMessage(boldGoldText); + /js self.sendMessage( boldGoldText );

Hello World

***/ var c = org.bukkit.ChatColor; var formattingCodes = { - aqua: c.AQUA, - black: c.BLACK, - blue: c.BLUE, - bold: c.BOLD, - brightgreen: c.GREEN, - darkaqua: c.DARK_AQUA, - darkblue: c.DARK_BLUE, - darkgray: c.DARK_GRAY, - darkgreen: c.DARK_GREEN, - purple: c.LIGHT_PURPLE, - darkpurple: c.DARK_PURPLE, - darkred: c.DARK_RED, - gold: c.GOLD, - gray: c.GRAY, - green: c.GREEN, - italic: c.ITALIC, - lightpurple: c.LIGHT_PURPLE, - indigo: c.BLUE, - red: c.RED, - pink: c.LIGHT_PURPLE, - yellow: c.YELLOW, - white: c.WHITE, - strike: c.STRIKETHROUGH, - random: c.MAGIC, - magic: c.MAGIC, - underline: c.UNDERLINE, - reset: c.RESET + aqua: c.AQUA, + black: c.BLACK, + blue: c.BLUE, + bold: c.BOLD, + brightgreen: c.GREEN, + darkaqua: c.DARK_AQUA, + darkblue: c.DARK_BLUE, + darkgray: c.DARK_GRAY, + darkgreen: c.DARK_GREEN, + purple: c.LIGHT_PURPLE, + darkpurple: c.DARK_PURPLE, + darkred: c.DARK_RED, + gold: c.GOLD, + gray: c.GRAY, + green: c.GREEN, + italic: c.ITALIC, + lightpurple: c.LIGHT_PURPLE, + indigo: c.BLUE, + red: c.RED, + pink: c.LIGHT_PURPLE, + yellow: c.YELLOW, + white: c.WHITE, + strike: c.STRIKETHROUGH, + random: c.MAGIC, + magic: c.MAGIC, + 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] ); } diff --git a/src/main/js/modules/utils/utils.js b/src/main/js/modules/utils/utils.js index 9ed6730..6c438bc 100644 --- a/src/main/js/modules/utils/utils.js +++ b/src/main/js/modules/utils/utils.js @@ -36,18 +36,18 @@ String, then it tries to find the player with that name. ***/ var _player = function ( playerName ) { - if (typeof playerName == 'undefined'){ - if (typeof self == 'undefined'){ - return null; - } else { - return self; - } - } else { - if (typeof playerName == 'string') - return org.bukkit.Bukkit.getPlayer(playerName); - else - return playerName; // assumes it's a player object + if ( typeof playerName == 'undefined' ) { + if ( typeof self == 'undefined' ) { + return null; + } else { + return self; } + } else { + if ( typeof playerName == 'string' ) + return org.bukkit.Bukkit.getPlayer( playerName ); + else + return playerName; // assumes it's a player object + } }; /************************************************************************* ### utils.locationToJSON() function @@ -73,15 +73,15 @@ 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){ - return { - world: ''+location.world.name, - x: location.x, - y: location.y, - z: location.z, - yaw: location.yaw, - pitch: location.pitch - }; +var _locationToJSON = function( location ) { + return { + world: ''+location.world.name, + x: location.x, + y: location.y, + z: location.z, + yaw: location.yaw, + pitch: location.pitch + }; }; /************************************************************************* ### utils.locationToString() function @@ -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,21 +117,23 @@ returned by locationToJSON() and reconstructs and returns a bukkit Location object. ***/ -exports.locationFromJSON = function(json){ - 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); - } +exports.locationFromJSON = function( json ) { + var world; + if ( json.constuctor == Array ) { + // for support of legacy format + 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.'); - return _player(player); + +exports.getPlayerObject = function( player ) { + console.warn( 'utils.getPlayerObject() is deprecated. Use utils.player() instead.' ); + return _player(player); }; /************************************************************************* ### utils.getPlayerPos() function @@ -153,15 +155,14 @@ 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) - return player.block.location; - else - return player.location; - } + player = _player( player ); + if ( player ) { + if ( player instanceof org.bukkit.command.BlockCommandSender ) + return player.block.location; else - return null; + return player.location; + } + return null; }; /************************************************************************ ### utils.getMousePos() function @@ -186,19 +187,21 @@ The following code will strike lightning at the location the player is looking a } ***/ -exports.getMousePos = function (player) { - - player = _player(player); - if (!player) - return null; - // player might be CONSOLE or a CommandBlock - if (!player.getTargetBlock) - return null; - var targetedBlock = player.getTargetBlock(null,5); - if (targetedBlock == null || targetedBlock.isEmpty()){ - return null; - } - return targetedBlock.location; +exports.getMousePos = function( player ) { + + player = _player(player); + if ( !player ) { + return null; + } + // player might be CONSOLE or a CommandBlock + if ( !player.getTargetBlock ) { + return null; + } + var targetedBlock = player.getTargetBlock( null, 5 ); + if ( targetedBlock == null || targetedBlock.isEmpty() ) { + return null; + } + return targetedBlock.location; }; /************************************************************************ ### utils.foreach() function @@ -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,20 +289,26 @@ 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) - 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); - } +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, 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 ); } + } }; exports.foreach = _foreach; /************************************************************************ @@ -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()){ - next(); - server.scheduler.runTaskLater(__plugin,function(){ - _nicely(next,hasNext,onDone,delay); - },delay); - }else{ - if (onDone) - onDone(); +var _nicely = function( next, hasNext, onDone, delay ) { + if ( hasNext() ){ + next(); + server.scheduler.runTaskLater( __plugin, function() { + _nicely( next, hasNext, onDone, delay ); + }, delay ); + }else{ + 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; - var mins; - if (timeParts.length > 1) - mins = (timeParts[1] / 60) * 1000; - - var timeMc = hrs + mins; - if (typeof worlds == 'undefined'){ - worlds = server.worlds; - } - _nicely(function(){ - _foreach (worlds, function (world){ - var time = world.getTime(); - var diff = timeMc - time; - if (diff > 0 && diff < 100){ - callback(); - } - }); - },forever, null, 100); +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; + } + var timeMc = hrs + mins; + if ( typeof worlds == 'undefined' ) { + worlds = server.worlds; + } + _nicely( function() { + _foreach( worlds, function ( world ) { + var time = world.getTime(); + var diff = timeMc - time; + if ( diff > 0 && diff < 100 ) { + callback(); + } + }); + }, forever, null, 100 ); }; /************************************************************************ @@ -411,25 +421,25 @@ a given directory and recursiving trawling all sub-directories. }); ***/ -exports.find = function( dir , filter){ - var result = []; - var recurse = function(dir, store){ - var files, dirfile = new java.io.File(dir); - - if (typeof filter == 'undefined') - files = dirfile.list(); - 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); - } - }); +exports.find = function( dir , filter ) { + var result = []; + var recurse = function( dir, store ) { + var files, dirfile = new java.io.File( dir ); + + if ( typeof filter == 'undefined' ) { + files = dirfile.list(); + } else { + files = dirfile.list(filter); } - recurse(dir,result); - return result; -} + _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 ); + return result; +}; diff --git a/src/main/js/plugins/alias/alias.js b/src/main/js/plugins/alias/alias.js index e8be545..35f58e3 100644 --- a/src/main/js/plugins/alias/alias.js +++ b/src/main/js/plugins/alias/alias.js @@ -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'; + } }); diff --git a/src/main/js/plugins/arrows.js b/src/main/js/plugins/arrows.js index dcac397..07cc12e 100644 --- a/src/main/js/plugins/arrows.js +++ b/src/main/js/plugins/arrows.js @@ -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 - console.warn('arrows.' + n + ' No player ' + player); - }; - })(_types[type]); + +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); + } + }; + } )( 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; + 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 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!'); - } - return convertToArrowSign(sign,true); +/* + 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 ); }; /* - 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]; + event handler called when a projectile hits something + */ +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){ - case 1: - projectile.remove(); - world.createExplosion(projectile.location,arrows.explosiveYield); - break; - case 2: - projectile.remove(); - var teleportCause =org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; - shooter.teleport(projectile.location, - teleportCause.PLUGIN); - break; - case 3: - projectile.remove(); - world.generateTree(projectile.location, org.bukkit.TreeType.BIG_TREE); - break; - case 4: - projectile.remove(); - world.strikeLightning(projectile.location); - break; - case 5: - projectile.remove(); - var launch = function(){ - fireworks.firework(projectile.location); - if (--fireworkCount) - setTimeout(launch,2000); - }; - launch(); - break; - } + 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, EXPLOSIVE_YIELD ); + break; + case 2: + projectile.remove(); + shooter.teleport( projectile.location, TeleportCause.PLUGIN ); + break; + case 3: + projectile.remove(); + world.generateTree( projectile.location, org.bukkit.TreeType.BIG_TREE ); + break; + case 4: + projectile.remove(); + world.strikeLightning( projectile.location ); + break; + case 5: + projectile.remove(); + launch(); + break; } + } }; -events.on('entity.ProjectileHitEvent',_onArrowHit); +events.on( 'entity.ProjectileHitEvent', _onArrowHit ); diff --git a/src/main/js/plugins/chat/color.js b/src/main/js/plugins/chat/color.js index 5d7ea64..a6666d0 100644 --- a/src/main/js/plugins/chat/color.js +++ b/src/main/js/plugins/chat/color.js @@ -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", { - /* - set the color of text for a given player - */ - setColor: function(player, color){ - _store.players[player.name] = color; - }, +exports.chat = plugin( 'chat', { + /* + set the color of text for a given player + */ + setColor: function( player, color ) { + _store.players[ player.name ] = color; + }, - store: _store + 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){ - var player = e.player; - var playerChatColor = _store.players[player.name]; - if (playerChatColor){ - e.message = "§" + colorCodes[playerChatColor] + e.message; - } +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 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(", ")); -}; -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"); - listColors(); - } -},colors); + +var listColors = function( params, sender ) { + var colorNamesInColor = []; + 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 ) { + var color = params[0]; + if ( colorCodes[color] ) { + chat.setColor( sender, color ); + } else { + sender.sendMessage( color + ' is not a valid color' ); + listColors(); + } +}, colors ); diff --git a/src/main/js/plugins/classroom/classroom.js b/src/main/js/plugins/classroom/classroom.js index d674f96..a91257a 100644 --- a/src/main/js/plugins/classroom/classroom.js +++ b/src/main/js/plugins/classroom/classroom.js @@ -1,4 +1,4 @@ -var utils = require('utils'); +var foreach = require('utils').foreach; /************************************************************************ ## Classroom Plugin @@ -32,59 +32,61 @@ 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)"); - return; - } - 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()) - return; - if (canScript){ - utils.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) - perm.attachment.remove(); - } - }); - }); - } - _store.enableScripting = canScript; - }, - store: _store +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 ); + return; + } + + /* + only operators should be allowed run this function + */ + if ( !sender.isOp() ) { + return; + } + if ( canScript ) { + foreach( server.onlinePlayers, function( player ) { + player.addAttachment( __plugin, 'scriptcraft.*', true ); + }); + } else { + foreach( server.onlinePlayers, function( player ) { + foreach( player.getEffectivePermissions(), function( perm ) { + if ( (''+perm.permission).indexOf( 'scriptcraft.' ) == 0 ) { + if ( perm.attachment ) { + perm.attachment.remove(); + } + } + }); + }); + } + _store.enableScripting = canScript; + }, + store: _store }, true); exports.classroom = classroom; -events.on('player.PlayerLoginEvent', function(listener, event) { - var player = event.player; - if (_store.enableScripting){ - player.addAttachment(__plugin, "scriptcraft.*", true); - } +events.on( 'player.PlayerLoginEvent', function( listener, event ) { + var player = event.player; + if ( _store.enableScripting ) { + player.addAttachment( __plugin, 'scriptcraft.*', true ); + } }, 'HIGHEST'); diff --git a/src/main/js/plugins/commando/commando-test.js b/src/main/js/plugins/commando/commando-test.js index 56900b4..5457e11 100644 --- a/src/main/js/plugins/commando/commando-test.js +++ b/src/main/js/plugins/commando/commando-test.js @@ -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)); +var commando = require('./commando').commando, + times = ['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; + } } - if (sender.location) - sender.location.world.setTime(times[params[0]]); - else - sender.sendMessage('This command only works in-world'); + } else { + sender.sendMessage('This command only works in-world'); + } -},['Dawn','Midday','Dusk','Midnight']); +},times); diff --git a/src/main/js/plugins/commando/commando.js b/src/main/js/plugins/commando/commando.js index 6f2694a..55fa910 100644 --- a/src/main/js/plugins/commando/commando.js +++ b/src/main/js/plugins/commando/commando.js @@ -78,37 +78,41 @@ 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); - commands[name] = result; - return result; +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){ - var msg = '' + e.message; - 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) - 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; +events.on( 'player.PlayerCommandPreprocessEvent', function( l, e ) { + var msg = '' + e.message; + 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 ) { + 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; + } }); diff --git a/src/main/js/plugins/drone/blocktype.js b/src/main/js/plugins/drone/blocktype.js index 2265763..0067d55 100644 --- a/src/main/js/plugins/drone/blocktype.js +++ b/src/main/js/plugins/drone/blocktype.js @@ -307,16 +307,24 @@ 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":[]} - 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)]); - } +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 ( 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 ) { - this.chkpt('blocktext'); + var bmfg, + bmbg, + lines, + lineCount, + h, + line, + i, + x, + y, + ch, + bits, + charWidth, + j; - if (typeof fg == "undefined") - fg = blocks.wool.black; + this.chkpt('blocktext'); - 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))); - - for (var i =0;i < line.length; i++) { - var ch = line.charAt(i) - var 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'); - } + if ( typeof fg == 'undefined' ) { + fg = blocks.wool.black; + } + + bmfg = this._getBlockIdAndMeta( fg ); + bmbg = null; + if ( typeof bg != 'undefined' ) { + bmbg = this._getBlockIdAndMeta( bg ); + } + lines = message.split( '\n' ); + lineCount = lines.length; + + for ( h = 0; h < lineCount; h++) { + + line = lines[h]; + line = line.toLowerCase().replace( /[^0-9a-z \.\-\+\/\;\'\:\!]/g, '' ); + this.up( 7 * ( lineCount - ( h + 1 ) ) ); - return this.move('blocktext'); + for ( i =0; i < line.length; i++) { + + ch = line.charAt( i ); + bits = bitmaps.computed[ ch ]; + + if ( typeof bits == 'undefined' ) { + bits = bitmaps.computed[' ']; + } + charWidth = bits.width; + + if ( typeof bg != 'undefined' ) { + this.cuboidX( bmbg[0], bmbg[1], charWidth, 7, 1 ); + } + + 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' ); }); diff --git a/src/main/js/plugins/drone/contrib/castle.js b/src/main/js/plugins/drone/contrib/castle.js index f7e4d15..c8ac9fc 100644 --- a/src/main/js/plugins/drone/contrib/castle.js +++ b/src/main/js/plugins/drone/contrib/castle.js @@ -3,49 +3,47 @@ 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) -{ - // - // use sensible default parameter values - // if no parameters are supplied - // - if (typeof side == "undefined") - side = 24; - if (typeof height == "undefined") - height = 10; - 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' - // - this.chkpt('castle'); - // - // how big the towers at each corner will be... - // - var towerSide = 10; - var towerHeight = height+4; +Drone.extend('castle', function( side, height ) { + // + // use sensible default parameter values + // if no parameters are supplied + // + if ( typeof side == "undefined" ) + side = 24; + if ( typeof height == "undefined" ) + height = 10; + 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' + // + this.chkpt('castle'); + // + // how big the towers at each corner will be... + // + var towerSide = 10; + var towerHeight = height+4; - // - // the main castle building will be front and right of the first tower - // - this.fwd(towerSide/2).right(towerSide/2); - // - // the castle is really just a big fort with 4 smaller 'tower' forts at each corner - // - this.fort(side,height); - // - // move back to start position - // - this.move('castle'); - // - // now place 4 towers at each corner (each tower is another fort) - // - 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 - this.fwd(side+towerSide-1).turn(); - } - return this.move('castle'); + // + // the main castle building will be front and right of the first tower + // + this.fwd(towerSide/2).right(towerSide/2); + // + // the castle is really just a big fort with 4 smaller 'tower' forts at each corner + // + this.fort(side,height); + // + // move back to start position + // + this.move('castle'); + // + // now place 4 towers at each corner (each tower is another fort) + // + 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 + this.fwd(side+towerSide-1).turn(); + } + return this.move('castle'); }); diff --git a/src/main/js/plugins/drone/contrib/chessboard.js b/src/main/js/plugins/drone/contrib/chessboard.js index f0c046b..6f773e4 100644 --- a/src/main/js/plugins/drone/contrib/chessboard.js +++ b/src/main/js/plugins/drone/contrib/chessboard.js @@ -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.box(block); - this.right(); - } - this.move('chessboard-start').fwd(i+1); - } - return this.move('chessboard-start'); + 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; + } + 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'); }); diff --git a/src/main/js/plugins/drone/contrib/cottage.js b/src/main/js/plugins/drone/contrib/cottage.js index 8aeb256..8301d2c 100644 --- a/src/main/js/plugins/drone/contrib/cottage.js +++ b/src/main/js/plugins/drone/contrib/cottage.js @@ -11,69 +11,67 @@ var Drone = require('../drone').Drone; // /js drone.cottage(); // -Drone.extend('cottage',function () -{ - this.chkpt('cottage') - .box0(48,7,2,6) // 4 walls - .right(3).door() // door front and center - .up(1).left(2).box(102) // windows to left and right - .right(4).box(102) - .left(5).up().prism0(53,7,6); +Drone.extend('cottage',function ( ) { + this.chkpt('cottage') + .box0(48,7,2,6) // 4 walls + .right(3).door() // door front and center + .up(1).left(2).box(102) // windows to left and right + .right(4).box(102) + .left(5).up().prism0(53,7,6); // // put up a sign near door. // - this.down().right(4).sign(["Home","Sweet","Home"],68); + this.down().right(4) + .sign(['Home','Sweet','Home'],68); - return this.move('cottage'); + return this.move('cottage'); }); // // 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"){ - numberCottages = 6; - } - var i=0, distanceBetweenTrees = 11; - // - // step 1 build the road. - // - var cottagesPerSide = Math.floor(numberCottages/2); +Drone.extend('cottage_road', function( numberCottages ) { + if (typeof numberCottages == 'undefined'){ + numberCottages = 6; + } + var i=0, distanceBetweenTrees = 11; + // + // step 1 build the road. + // + var cottagesPerSide = Math.floor(numberCottages/2); + this + .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 + + // + // step 2 line the road with trees + // + for ( ; i < cottagesPerSide+1;i++ ) { this - .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 + .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 - // - // step 2 line the road with trees - // - 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 function builds a path leading to a cottage. - 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); - // build cottage on left - pathAndCottage(this.turn(3)).move("r"+i); - // build cottage on right - pathAndCottage(this.turn()).move("r"+i); - } - // return drone to where it was at start of function - return this.move("cottage_road"); + // this function builds a path leading to a cottage. + 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); + // build cottage on left + pathAndCottage( this.turn(3) ).move( 'r' + i ); + // build cottage on right + pathAndCottage(this.turn()).move( 'r' + i ); + } + // return drone to where it was at start of function + return this.move('cottage_road'); }); diff --git a/src/main/js/plugins/drone/contrib/fort.js b/src/main/js/plugins/drone/contrib/fort.js index 90686c7..d0921ad 100644 --- a/src/main/js/plugins/drone/contrib/fort.js +++ b/src/main/js/plugins/drone/contrib/fort.js @@ -3,66 +3,69 @@ var Drone = require('../drone').Drone; // // constructs a medieval fort // -Drone.extend('fort', function(side, height) -{ - if (typeof side == "undefined") - side = 18; - if (typeof height == "undefined") - height = 6; - // make sure side is even - if (side%2) - side++; - 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. - // - this.chkpt('fort').box0(brick,side,height-1,side); - // - // build battlements - // - this.up(height-1); - 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{ - this.boxa(turret,1,1,side-2).fwd(side-2).turn(); - }catch(e){ - console.log("ERROR: " + e.toString()); - } +Drone.extend('fort', function( side, height ) { + if ( typeof side == 'undefined' ) { + side = 18; + } + if ( typeof height == 'undefined' ) { + height = 6; + } + // make sure side is even + if ( side % 2 ) { + side++; + } + 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. + // + this.chkpt('fort').box0(brick,side,height-1,side); + // + // build battlements + // + this.up(height-1); + 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 { + this.boxa(turret,1,1,side-2).fwd(side-2).turn(); + } catch( e ) { + console.log('ERROR: ' + e.toString()); } - // - // build battlement's floor - // - this.move('fort'); - this.up(height-2).fwd().right().box('126:0',side-2,1,side-2); - var battlementWidth = 3; - if (side <= 12) - battlementWidth = 2; - - this.fwd(battlementWidth).right(battlementWidth) - .box(0,side-((1+battlementWidth)*2),1,side-((1+battlementWidth)*2)); - // - // add door - // - var torch = '50:' + Drone.PLAYER_TORCH_FACING[this.dir]; - this.move('fort').right((side/2)-1).door2() // double doors - .back().left().up() - .box(torch) // left torch - .right(3) - .box(torch); // right torch - // - // add ladder up to battlements - // - var ladder = '65:' + Drone.PLAYER_SIGN_FACING[(this.dir+2)%4]; - this.move('fort').right((side/2)-3).fwd(1) // move inside fort - .box(ladder, 1,height-1,1); - return this.move('fort'); - + } + // + // build battlement's floor + // + this.move('fort'); + this.up(height-2).fwd().right().box('126:0',side-2,1,side-2); + var battlementWidth = 3; + if ( side <= 12 ) { + battlementWidth = 2; + } + this.fwd(battlementWidth).right(battlementWidth) + .box(0,side-((1+battlementWidth)*2),1,side-((1+battlementWidth)*2)); + // + // add door + // + var torch = '50:' + Drone.PLAYER_TORCH_FACING[this.dir]; + this.move('fort').right((side/2)-1).door2() // double doors + .back().left().up() + .box(torch) // left torch + .right(3) + .box(torch); // right torch + // + // add ladder up to battlements + // + var ladder = '65:' + Drone.PLAYER_SIGN_FACING[(this.dir+2)%4]; + this.move('fort').right((side/2)-3).fwd(1) // move inside fort + .box(ladder, 1,height-1,1); + return this.move('fort'); + }); diff --git a/src/main/js/plugins/drone/contrib/lcd-clock.js b/src/main/js/plugins/drone/contrib/lcd-clock.js index 48cf7f2..b6fc492 100644 --- a/src/main/js/plugins/drone/contrib/lcd-clock.js +++ b/src/main/js/plugins/drone/contrib/lcd-clock.js @@ -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; diff --git a/src/main/js/plugins/drone/contrib/rainbow.js b/src/main/js/plugins/drone/contrib/rainbow.js index 31d33b5..2575a62 100644 --- a/src/main/js/plugins/drone/contrib/rainbow.js +++ b/src/main/js/plugins/drone/contrib/rainbow.js @@ -19,24 +19,29 @@ Creates a Rainbow. ***/ Drone.extend('rainbow', function(radius){ - 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.push(blocks.air); - for (var i = 0;i < colors.length; i++) { - var bm = this._getBlockIdAndMeta(colors[i]); - this.arc({ - blockType: bm[0], - meta: bm[1], - radius: radius-i, - strokeWidth: 2, - quadrants: {topright: true, - topleft: true}, - orientation: 'vertical'}).right().up(); - } - return this.move('rainbow'); + 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) + colors = blocks.rainbow.slice(0); + colors.push(blocks.air); + for ( i = 0; i < colors.length; i++ ) { + bm = this._getBlockIdAndMeta( colors[i] ); + this.arc({ + blockType: bm[0], + meta: bm[1], + radius: radius-i, + strokeWidth: 2, + quadrants: {topright: true, + topleft: true}, + orientation: 'vertical'}).right().up(); + } + return this.move('rainbow'); }); diff --git a/src/main/js/plugins/drone/contrib/rboxcall.js b/src/main/js/plugins/drone/contrib/rboxcall.js index bc709bb..222f101 100644 --- a/src/main/js/plugins/drone/contrib/rboxcall.js +++ b/src/main/js/plugins/drone/contrib/rboxcall.js @@ -12,23 +12,23 @@ var Drone = require('../drone').Drone; * depth - (Optional) depth of the cube, defaults to width */ -Drone.extend("rboxcall", function(callback, probability, width, height, depth) { - this.chkpt('rboxcall-start'); +Drone.extend("rboxcall", function( callback, probability, width, height, depth ) { + this.chkpt('rboxcall-start'); - for(var i = 0; i < width; ++i) { - this.move('rboxcall-start').right(i); - for(var j = 0; j < depth; ++j) { - this.move('rboxcall-start').right(i).fwd(j); - for(var k = 0; k < height; ++k) { - if(Math.random()*100 < probability) { - callback.call(null, new Drone(this.x, this.y, this.z)); - } - this.up(); - } + for(var i = 0; i < width; ++i) { + this.move('rboxcall-start').right(i); + for(var j = 0; j < depth; ++j) { + this.move('rboxcall-start').right(i).fwd(j); + for(var k = 0; k < height; ++k) { + if(Math.random()*100 < probability) { + callback.call(null, new Drone(this.x, this.y, this.z)); + } + this.up(); } - } + } + } - this.move('rboxcall-start'); + this.move('rboxcall-start'); - return this; + return this; }); diff --git a/src/main/js/plugins/drone/contrib/skyscraper-example.js b/src/main/js/plugins/drone/contrib/skyscraper-example.js index 2a4adb0..465aad5 100644 --- a/src/main/js/plugins/drone/contrib/skyscraper-example.js +++ b/src/main/js/plugins/drone/contrib/skyscraper-example.js @@ -1,18 +1,18 @@ var Drone = require('../drone').Drone; var blocks = require('blocks'); -Drone.extend('skyscraper',function(floors){ - - 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) - .up(3); - } - return this.move('skyscraper'); +Drone.extend('skyscraper', function( floors ) { + var i = 0; + if ( typeof floors == 'undefined' ) { + floors = 10; + } + this.chkpt('skyscraper'); + 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'); }); diff --git a/src/main/js/plugins/drone/contrib/streamer.js b/src/main/js/plugins/drone/contrib/streamer.js index f0b00d9..28c8d75 100644 --- a/src/main/js/plugins/drone/contrib/streamer.js +++ b/src/main/js/plugins/drone/contrib/streamer.js @@ -7,25 +7,25 @@ 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") - maxIterations = 1000; - - var usage = "Usage: streamer({block-type}, {direction: 'up', 'down', 'fwd', 'back', 'left', 'right'}, {maximum-iterations: default 1000})\nE.g.\n" + +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"){ - throw new Error(usage); + if (typeof dir == 'undefined'){ + throw new Error(usage); + } + if (typeof block == 'undefined') { + throw new Error(usage); + } + 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; } - if (typeof block == "undefined") { - throw new Error(usage); - } - 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 - } - } - return this; + } + return this; }); diff --git a/src/main/js/plugins/drone/contrib/temple.js b/src/main/js/plugins/drone/contrib/temple.js index 8b9b98c..82d52c7 100644 --- a/src/main/js/plugins/drone/contrib/temple.js +++ b/src/main/js/plugins/drone/contrib/temple.js @@ -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; } diff --git a/src/main/js/plugins/drone/drone-firework.js b/src/main/js/plugins/drone/drone-firework.js index ac07f37..8ffddbc 100644 --- a/src/main/js/plugins/drone/drone-firework.js +++ b/src/main/js/plugins/drone/drone-firework.js @@ -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() ); }); diff --git a/src/main/js/plugins/drone/drone.js b/src/main/js/plugins/drone/drone.js index 0b5913b..fe2accd 100644 --- a/src/main/js/plugins/drone/drone.js +++ b/src/main/js/plugins/drone/drone.js @@ -1,5 +1,9 @@ -var utils = require('utils'); -var blocks = require('blocks'); +var utils = require('utils'), + blocks = require('blocks'), + Location = org.bukkit.Location, + Player = org.bukkit.entity.Player, + Sign = org.bukkit.block.Sign, + TreeType = org.bukkit.TreeType; /********************************************************************* ## Drone Plugin @@ -114,7 +118,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... @@ -256,7 +260,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); } // @@ -328,11 +332,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 @@ -356,7 +360,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) @@ -419,7 +423,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) @@ -434,13 +438,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) @@ -499,7 +503,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 @@ -511,9 +515,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 @@ -570,9 +574,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'); @@ -630,121 +634,128 @@ Used when placing torches so that they face towards the drone. // There is no need to read any further unless you want to understand how the Drone object works. // -var putBlock = function(x,y,z,blockId,metadata,world){ - if (typeof metadata == "undefined") - metadata = 0; - var block = world.getBlockAt(x,y,z); - if (block.typeId != blockId || block.data != metadata) - block.setTypeIdAndData(blockId,metadata,false); +var putBlock = function( x, y, z, blockId, metadata, world ) { + if ( typeof metadata == 'undefined' ) { + metadata = 0; + } + var block = world.getBlockAt( x, y, z ); + if ( block.typeId != blockId || block.data != metadata ) { + block.setTypeIdAndData( blockId, metadata, false ); + } }; -var putSign = function(texts, x, y, z, blockId, meta, world){ - if (blockId != 63 && blockId != 68) - throw new Error("Invalid Parameter: blockId must be 63 or 68"); - putBlock(x,y,z,blockId,meta,world); - var block = world.getBlockAt(x,y,z); - var state = block.state; - if (state instanceof org.bukkit.block.Sign){ - for (var i = 0;i < texts.length; i++) - state.setLine(i%4,texts[i]); - state.update(true); +var putSign = function( texts, x, y, z, blockId, meta, world ) { + var i, + block, + state; + + if ( blockId != 63 && blockId != 68 ) { + throw new Error( 'Invalid Parameter: blockId must be 63 or 68' ); + } + putBlock( x, y, z, blockId, meta, world ); + block = world.getBlockAt( x, y, z ); + state = block.state; + if ( state instanceof Sign ) { + for ( i = 0; i < texts.length; i++ ) { + state.setLine( i % 4, texts[ i ] ); } + state.update( true ); + } }; -Drone = function(x,y,z,dir,world) -{ - this.record = false; - var usePlayerCoords = false; - var player = self; - if (x instanceof org.bukkit.entity.Player){ - player = x; +var Drone = function( x, y, z, dir, world ) { + this.record = false; + var usePlayerCoords = false; + var player = self; + if ( x instanceof Player ) { + player = x; + } + var playerPos = utils.getPlayerPos( player ); + var that = this; + var populateFromLocation = function( loc ) { + that.x = loc.x; + that.y = loc.y; + that.z = loc.z; + that.dir = _getDirFromRotation(loc.yaw); + that.world = loc.world; + }; + var mp = utils.getMousePos( player ); + if ( typeof x == 'undefined' || x instanceof Player ) { + if ( mp ) { + populateFromLocation( mp ); + if ( playerPos ) { + this.dir = _getDirFromRotation(playerPos.yaw); + } + } else { + // base it on the player's current location + usePlayerCoords = true; + // + // it's possible that drone.js could be loaded by a non-playing op + // (from the server console) + // + if ( !playerPos ) { + return null; + } + populateFromLocation( playerPos ); } - var playerPos = utils.getPlayerPos(player); - var that = this; - var populateFromLocation = function(loc){ - that.x = loc.x; - that.y = loc.y; - that.z = loc.z; - that.dir = _getDirFromRotation(loc.yaw); - that.world = loc.world; - }; - var mp = utils.getMousePos(player); - if (typeof x == "undefined" || x instanceof org.bukkit.entity.Player) - { - if (mp){ - populateFromLocation(mp); - if (playerPos) - this.dir = _getDirFromRotation(playerPos.yaw); - }else{ - // base it on the player's current location - usePlayerCoords = true; - // - // it's possible that drone.js could be loaded by a non-playing op - // (from the server console) - // - if (!playerPos){ - return null; - } - populateFromLocation(playerPos); - } - }else{ - if (arguments[0] instanceof org.bukkit.Location){ - populateFromLocation(arguments[0]); - }else{ - this.x = x; - this.y = y; - this.z = z; - if (typeof dir == "undefined"){ - this.dir = _getDirFromRotation(playerPos.yaw); - }else{ - this.dir = dir%4; - } - if (typeof world == "undefined"){ - this.world = playerPos.world; - }else{ - this.world = world; - } - } + } else { + if ( arguments[0] instanceof Location ) { + populateFromLocation( arguments[ 0 ] ); + } else { + this.x = x; + this.y = y; + this.z = z; + if ( typeof dir == 'undefined' ) { + this.dir = _getDirFromRotation( playerPos.yaw ); + } else { + this.dir = dir%4; + } + if ( typeof world == 'undefined' ) { + this.world = playerPos.world; + } else { + this.world = world; + } } + } - if (usePlayerCoords){ - this.fwd(3); - } - this.chkpt('start'); - this.record = true; - this.history = []; - return this; + if ( usePlayerCoords ) { + this.fwd( 3 ); + } + this.chkpt( 'start' ); + this.record = true; + this.history = []; + return this; }; exports.Drone = Drone; /* - because this is a plugin, any of its exports will be exported globally. - Since 'blocks' is a module not a plugin it is convenient to export it via - the Drone module. -*/ + because this is a plugin, any of its exports will be exported globally. + Since 'blocks' is a module not a plugin it is convenient to export it via + the Drone module. + */ exports.blocks = blocks; // // add custom methods to the Drone object using this function // -Drone.extend = function(name, func) -{ - Drone.prototype['_' + name] = func; - Drone.prototype[name] = function(){ - if (this.record) - this.history.push([name,arguments]); - var oldVal = this.record; - this.record = false; - this['_' + name].apply(this,arguments); - this.record = oldVal; - return this; - }; - - global[name] = function(){ - var result = new Drone(self); - result[name].apply(result,arguments); - return result; - }; +Drone.extend = function( name, func ) { + Drone.prototype[ '_' + name ] = func; + Drone.prototype[ name ] = function( ) { + if ( this.record ) { + this.history.push( [ name, arguments ] ); + } + var oldVal = this.record; + this.record = false; + this[ '_' + name ].apply( this, arguments ); + this.record = oldVal; + return this; + }; + + global[name] = function( ) { + var result = new Drone( self ); + result[name].apply( result, arguments ); + return result; + }; }; /************************************************************************** @@ -762,7 +773,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 @@ -771,7 +782,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 @@ -814,751 +825,769 @@ Another example: This statement creates a row of trees 2 by 3 ... ![times example 1](img/times-trees.png) ***/ -Drone.prototype.times = function(numTimes,commands) { - if (typeof numTimes == "undefined") - numTimes = 2; - if (typeof commands == "undefined") - commands = this.history.concat(); - - this.history = [['times',[numTimes+1,commands]]]; - var oldVal = this.record; - this.record = false; - for (var j = 1; j < numTimes; j++) - { - for (var i = 0;i < commands.length; i++){ - var command = commands[i]; - var methodName = command[0]; - var args = command[1]; - print ("command=" + JSON.stringify(command) + ",methodName=" + methodName); - this[methodName].apply(this,args); - } +Drone.prototype.times = function( numTimes, commands ) { + if ( typeof numTimes == 'undefined' ) { + numTimes = 2; + } + if ( typeof commands == 'undefined' ) { + commands = this.history.concat(); + } + + this.history = [ [ 'times', [ numTimes + 1, commands ] ] ]; + var oldVal = this.record; + this.record = false; + for ( var j = 1; j < numTimes; j++ ) { + for ( var i = 0; i < commands.length; i++) { + var command = commands[i]; + var methodName = command[0]; + var args = command[1]; + print ('command=' + JSON.stringify(command ) + ',methodName=' + methodName ); + this[ methodName ].apply( this, args ); } - this.record = oldVal; - return this; + } + this.record = oldVal; + return this; }; Drone.prototype._checkpoints = {}; -Drone.extend('chkpt',function(name){ - this._checkpoints[name] = {x:this.x,y:this.y,z:this.z,dir:this.dir}; -}); +Drone.extend( 'chkpt', function( name ) { + this._checkpoints[ name ] = { x:this.x, y:this.y, z:this.z, dir:this.dir }; +} ); -Drone.extend('move', function() { - if (arguments[0] instanceof org.bukkit.Location){ - this.x = arguments[0].x; - this.y = arguments[0].y; - this.z = arguments[0].z; - this.dir = _getDirFromRotation(arguments[0].yaw); - this.world = arguments[0].world; - }else if (typeof arguments[0] === "string"){ - var coords = this._checkpoints[arguments[0]]; - if (coords){ - this.x = coords.x; - this.y = coords.y; - this.z = coords.z; - this.dir = coords.dir%4; - } - }else{ - // expect x,y,z,dir - switch(arguments.length){ - case 4: - this.dir = arguments[3]; - case 3: - this.z = arguments[2]; - case 2: - this.y = arguments[1]; - case 1:n - this.x = arguments[0]; - } +Drone.extend( 'move', function( ) { + if ( arguments[0] instanceof Location ) { + this.x = arguments[0].x; + this.y = arguments[0].y; + this.z = arguments[0].z; + this.dir = _getDirFromRotation(arguments[0].yaw ); + this.world = arguments[0].world; + } else if ( typeof arguments[0] === 'string' ) { + var coords = this._checkpoints[arguments[0]]; + if ( coords ) { + this.x = coords.x; + this.y = coords.y; + this.z = coords.z; + this.dir = coords.dir%4; + } + } else { + // expect x,y,z,dir + switch( arguments.length ) { + case 4: + this.dir = arguments[3]; + case 3: + this.z = arguments[2]; + case 2: + this.y = arguments[1]; + case 1: + this.x = arguments[0]; } + } +} ); + +Drone.extend( 'turn', function ( n ) { + if ( typeof n == 'undefined' ) { + n = 1; + } + this.dir += n; + this.dir %=4; +} ); + +Drone.extend( 'right', function( n ) { + if ( typeof n == 'undefined' ) { + n = 1; + } + _movements[ this.dir ].right( this, n ); }); -Drone.extend('turn',function(n){ - if (typeof n == "undefined") - n = 1; - this.dir += n; - this.dir %=4; +Drone.extend( 'left', function( n ) { + if ( typeof n == 'undefined') { + n = 1; + } + _movements[ this.dir ].left( this, n ); }); -Drone.extend('right',function(n){ - if (typeof n == "undefined") - n = 1; - _movements[this.dir].right(this,n); + +Drone.extend( 'fwd', function( n ) { + if ( typeof n == 'undefined' ) { + n = 1; + } + _movements[ this.dir ].fwd( this, n ); }); -Drone.extend('left',function(n){ - if (typeof n == "undefined") - n = 1; - _movements[this.dir].left(this,n); + +Drone.extend( 'back', function( n ) { + if ( typeof n == 'undefined' ) { + n = 1; + } + _movements[ this.dir ].back( this, n ); }); -Drone.extend('fwd',function(n){ - if (typeof n == "undefined") - n = 1; - _movements[this.dir].fwd(this,n); + +Drone.extend( 'up', function( n ) { + if ( typeof n == 'undefined' ) { + n = 1; + } + this.y+= n; }); -Drone.extend('back',function(n){ - if (typeof n == "undefined") - n = 1; - _movements[this.dir].back(this,n); -}); -Drone.extend('up',function(n){ - if (typeof n == "undefined") - n = 1; - this.y+= n; -}); -Drone.extend('down',function(n){ - if (typeof n == "undefined") - n = 1; - this.y-= n; + +Drone.extend( 'down', function( n ) { + if ( typeof n == 'undefined' ) { + n = 1; + } + this.y-= n; }); // // position // -Drone.prototype.getLocation = function() { - return new org.bukkit.Location(this.world, this.x, this.y, this.z); +Drone.prototype.getLocation = function( ) { + return new Location( this.world, this.x, this.y, this.z ); }; // // building // -Drone.extend('sign',function(message,block){ - if (message.constructor == Array){ - }else{ - message = [message]; - } - var bm = this._getBlockIdAndMeta(block); - block = bm[0]; - var meta = bm[1]; - if (block != 63 && block != 68){ - print("ERROR: Invalid block id for use in signs"); - return; - } - if (block == 68){ - meta = Drone.PLAYER_SIGN_FACING[this.dir%4]; - this.back(); - } - if (block == 63){ - meta = (12 + ((this.dir+2)*4)) % 16; - } - putSign(message,this.x,this.y,this.z,block,meta, this.world); - if (block == 68){ - this.fwd(); - } +Drone.extend( 'sign', function( message, block ) { + if ( message.constructor != Array ) { + message = [message]; + } + var bm = this._getBlockIdAndMeta( block ); + block = bm[0]; + var meta = bm[1]; + if ( block != 63 && block != 68 ) { + print('ERROR: Invalid block id for use in signs'); + return; + } + if ( block == 68 ) { + meta = Drone.PLAYER_SIGN_FACING[ this.dir % 4 ]; + this.back(); + } + if ( block == 63 ) { + meta = ( 12 + ( ( this.dir + 2 ) * 4 ) ) % 16; + } + putSign( message, this.x, this.y, this.z, block, meta, this.world ); + if ( block == 68 ) { + this.fwd(); + } }); -Drone.prototype.cuboida = function(/* Array */ blocks,w,h,d){ - var properBlocks = []; - var len = blocks.length; - for (var i = 0;i < len;i++){ - var bm = this._getBlockIdAndMeta(blocks[i]); - properBlocks.push([bm[0],bm[1]]); - } - if (typeof h == "undefined") - h = 1; - if (typeof d == "undefined") - d = 1; - if (typeof w == "undefined") - w = 1; - var that = this; - var dir = this.dir; - var pl = org.bukkit.entity.Player; - var cs = org.bukkit.command.BlockCommandSender; - var bi = 0; - /* - - */ - _traverse[dir].depth(that,d,function(){ - _traverseHeight(that,h,function(){ - _traverse[dir].width(that,w,function(){ - var block = that.world.getBlockAt(that.x,that.y,that.z); - var properBlock = properBlocks[bi%len]; - block.setTypeIdAndData(properBlock[0],properBlock[1],false); - bi++; - }); - }); + +Drone.prototype.cuboida = function(/* Array */ blocks, w, h, d ) { + var properBlocks = []; + var len = blocks.length; + for ( var i = 0; i < len; i++ ) { + var bm = this._getBlockIdAndMeta( blocks[ i ] ); + properBlocks.push( [ bm[0], bm[1] ] ); + } + if ( typeof h == 'undefined' ) { + h = 1; + } + if ( typeof d == 'undefined' ) { + d = 1; + } + if ( typeof w == 'undefined' ) { + w = 1; + } + var that = this; + var dir = this.dir; + var bi = 0; + /* + + */ + _traverse[dir].depth( that, d, function( ) { + _traverseHeight( that, h, function( ) { + _traverse[dir].width( that, w, function( ) { + var block = that.world.getBlockAt( that.x, that.y, that.z ); + var properBlock = properBlocks[ bi % len ]; + block.setTypeIdAndData( properBlock[0], properBlock[1], false ); + bi++; + }); }); - return this; - + }); + return this; + }; /* - faster cuboid because blockid, meta and world must be provided - use this method when you need to repeatedly place blocks -*/ -Drone.prototype.cuboidX = function(blockType, meta, w, h, d){ + faster cuboid because blockid, meta and world must be provided + use this method when you need to repeatedly place blocks + */ +Drone.prototype.cuboidX = function( blockType, meta, w, h, d ) { - if (typeof h == "undefined") - h = 1; - if (typeof d == "undefined") - d = 1; - if (typeof w == "undefined") - w = 1; - var that = this; - var dir = this.dir; + if ( typeof h == 'undefined' ) { + h = 1; + } + if ( typeof d == 'undefined' ) { + d = 1; + } + if ( typeof w == 'undefined' ) { + w = 1; + } + var that = this; + var dir = this.dir; - var depthFunc = function(){ - var block = that.world.getBlockAt(that.x,that.y,that.z); - block.setTypeIdAndData(blockType,meta,false); - // wph 20130210 - dont' know if this is a bug in bukkit but for chests, - // the metadata is ignored (defaults to 2 - south facing) - // only way to change data is to set it using property/bean. - block.data = meta; - }; - var heightFunc = function(){ - _traverse[dir].depth(that,d,depthFunc); - }; - var widthFunc = function(){ - _traverseHeight(that,h,heightFunc); - }; - - _traverse[dir].width(that,w,widthFunc); - return this; - + var depthFunc = function( ) { + var block = that.world.getBlockAt( that.x, that.y, that.z ); + block.setTypeIdAndData( blockType, meta, false ); + // wph 20130210 - dont' know if this is a bug in bukkit but for chests, + // the metadata is ignored (defaults to 2 - south facing) + // only way to change data is to set it using property/bean. + block.data = meta; + }; + var heightFunc = function( ) { + _traverse[dir].depth( that, d, depthFunc ); + }; + var widthFunc = function( ) { + _traverseHeight( that, h, heightFunc ); + }; + _traverse[dir].width( that, w, widthFunc ); + return this; + }; -Drone.prototype.cuboid = function(block,w,h,d){ - var bm = this._getBlockIdAndMeta(block); - return this.cuboidX(bm[0],bm[1], w,h,d); +Drone.prototype.cuboid = function( block, w, h, d ) { + var bm = this._getBlockIdAndMeta( block ); + return this.cuboidX( bm[0], bm[1], w, h, d ); }; -Drone.prototype.cuboid0 = function(block,w,h,d){ - this.chkpt('start_point'); - - // Front wall - this.cuboid(block, w, h, 1); - // Left wall - this.cuboid(block, 1, h, d); - // Right wall - this.right(w-1).cuboid(block, 1, h, d).left(w-1); - // Back wall - this.fwd(d-1).cuboid(block, w, h, 1); - - return this.move('start_point'); + +Drone.prototype.cuboid0 = function( block, w, h, d ) { + this.chkpt( 'start_point' ); + + // Front wall + this.cuboid( block, w, h, 1 ); + // Left wall + this.cuboid( block, 1, h, d ); + // Right wall + this.right( w - 1 ).cuboid( block, 1, h, d ).left( w - 1 ); + // Back wall + this.fwd( d - 1 ).cuboid( block, w, h, 1 ); + + return this.move( 'start_point' ); }; -Drone.extend('door',function(door){ - if (typeof door == "undefined"){ - door = 64; - }else{ - door = 71; - } - this.cuboid(door+':' + this.dir).up().cuboid(door+':8').down(); -}); -Drone.extend('door2',function(door){ - if (typeof door == "undefined"){ - door = 64; - }else{ - door = 71; - } - this - .box(door+':' + this.dir).up() - .box(door+':8').right() - .box(door+':9').down() - .box(door+':' + this.dir).left(); -}); + +Drone.extend( 'door', function( door ) { + if ( typeof door == 'undefined' ) { + door = 64; + } else { + door = 71; + } + this.cuboid( door+':' + this.dir ) + .up( ) + .cuboid( door+':8' ) + .down( ); +} ); + +Drone.extend( 'door2' , function( door ) { + if ( typeof door == 'undefined' ) { + door = 64; + } else { + door = 71; + } + this + .box( door+':' + this.dir ).up( ) + .box( door+':8' ).right( ) + .box( door+':9' ).down( ) + .box( door+':' + this.dir ).left( ); +} ); // player dirs: 0 = east, 1 = south, 2 = west, 3 = north // block dirs: 0 = east, 1 = west, 2 = south , 3 = north // sign dirs: 5 = east, 3 = south, 4 = west, 2 = north -Drone.PLAYER_STAIRS_FACING = [0,2,1,3]; +Drone.PLAYER_STAIRS_FACING = [ 0, 2, 1, 3 ]; // for blocks 68 (wall signs) 65 (ladders) 61,62 (furnaces) 23 (dispenser) and 54 (chest) -Drone.PLAYER_SIGN_FACING = [4,2,5,3]; -Drone.PLAYER_TORCH_FACING = [2,4,1,3]; +Drone.PLAYER_SIGN_FACING = [ 4, 2, 5, 3 ]; +Drone.PLAYER_TORCH_FACING = [ 2, 4, 1, 3 ]; -var _STAIRBLOCKS = {53: '5:0' // oak wood - ,67: 4 // cobblestone - ,108: 45 // brick - ,109: 98 // stone brick - ,114: 112 // nether brick - ,128: 24 // sandstone - ,134: '5:1' // spruce wood - ,135: '5:2' // birch wood - ,136: '5:3' // jungle wood - }; +var _STAIRBLOCKS = { + 53: '5:0' // oak wood + ,67: 4 // cobblestone + ,108: 45 // brick + ,109: 98 // stone brick + ,114: 112 // nether brick + ,128: 24 // sandstone + ,134: '5:1' // spruce wood + ,135: '5:2' // birch wood + ,136: '5:3' // jungle wood +}; // // prism private implementation // -var _prism = function(block,w,d) { - var stairEquiv = _STAIRBLOCKS[block]; - if (stairEquiv){ - this.fwd().prism(stairEquiv,w,d-2).back(); - var d2 = 0; - var middle = Math.floor(d/2); - var uc = 0,dc = 0; - while (d2 < d) - { - var di = (d2 < middle?this.dir:(this.dir+2)%4); - var bd = block + ':' + Drone.PLAYER_STAIRS_FACING[di]; - var putStep = true; - if (d2 == middle){ - if (d % 2 == 1){ - putStep = false; - } - } - if (putStep) - this.cuboid(bd,w); - if (d2 < middle-1){ - this.up(); - uc++; - } - var modulo = d % 2; - if (modulo == 1){ - if (d2 > middle && d2= middle && d2= 1){ - this.cuboid(block,w,1,d2); - d2 -= 2; - this.fwd().up(); - c++; + } + if ( putStep ) { + this.cuboid(bd,w ); + } + if ( d2 < middle-1 ) { + this.up( ); + uc++; + } + var modulo = d % 2; + if ( modulo == 1 ) { + if ( d2 > middle && d2= middle && d2= 1 ) { + this.cuboid(block,w,1,d2 ); + d2 -= 2; + this.fwd( ).up( ); + c++; + } + this.down(c ).back(c ); + } + return this; }; // // prism0 private implementation // -var _prism0 = function(block,w,d){ - this.prism(block,w,d) - .fwd().right() - .prism(0,w-2,d-2) - .left().back(); - var se = _STAIRBLOCKS[block]; - if (d % 2 == 1 && se){ - // top of roof will be open - need repair - var f = Math.floor(d/2); - this.fwd(f).up(f).cuboid(se,w).down(f).back(f); - } +var _prism0 = function( block,w,d ) { + this.prism(block,w,d ) + .fwd( ).right( ) + .prism(0,w-2,d-2 ) + .left( ).back( ); + var se = _STAIRBLOCKS[block]; + if ( d % 2 == 1 && se ) { + // top of roof will be open - need repair + var f = Math.floor(d/2 ); + this.fwd(f ).up(f ).cuboid(se,w ).down(f ).back(f ); + } }; -Drone.extend('prism0',_prism0); -Drone.extend('prism',_prism); -Drone.extend('box',Drone.prototype.cuboid); -Drone.extend('box0',Drone.prototype.cuboid0); -Drone.extend('boxa',Drone.prototype.cuboida); +Drone.extend('prism0',_prism0 ); +Drone.extend('prism',_prism ); +Drone.extend('box',Drone.prototype.cuboid ); +Drone.extend('box0',Drone.prototype.cuboid0 ); +Drone.extend('boxa',Drone.prototype.cuboida ); // // show the Drone's position and direction // -Drone.prototype.toString = function(){ - var dirs = ["east","south","west","north"]; - return "x: " + this.x + " y: "+this.y + " z: " + this.z + " dir: " + this.dir + " "+dirs[this.dir]; +Drone.prototype.toString = function( ) { + var dirs = ['east','south','west','north']; + return 'x: ' + this.x + ' y: '+this.y + ' z: ' + this.z + ' dir: ' + this.dir + ' '+dirs[this.dir]; }; -Drone.prototype.debug = function(){ - print(this.toString()); - return this; +Drone.prototype.debug = function( ) { + print(this.toString( ) ); + return this; }; /* - do the bresenham thing -*/ -var _bresenham = function(x0,y0,radius, setPixel, quadrants){ - // - // credit: Following code is copied almost verbatim from - // http://en.wikipedia.org/wiki/Midpoint_circle_algorithm - // Bresenham's circle algorithm - // - var f = 1 - radius; - var ddF_x = 1; - var ddF_y = -2 * radius; - var x = 0; - var y = radius; - var defaultQuadrants = {topleft: true, topright: true, bottomleft: true, bottomright: true}; - quadrants = quadrants?quadrants:defaultQuadrants; - /* - II | I - ------------ - III | IV - */ - if (quadrants.topleft || quadrants.topright) - setPixel(x0, y0 + radius); // quadrant I/II topmost - if (quadrants.bottomleft || quadrants.bottomright) - setPixel(x0, y0 - radius); // quadrant III/IV bottommost - if (quadrants.topright || quadrants.bottomright) - setPixel(x0 + radius, y0); // quadrant I/IV rightmost - if (quadrants.topleft || quadrants.bottomleft) - setPixel(x0 - radius, y0); // quadrant II/III leftmost - - while(x < y) - { - // ddF_x == 2 * x + 1; - // ddF_y == -2 * y; - // f == x*x + y*y - radius*radius + 2*x - y + 1; - if(f >= 0) - { - y--; - ddF_y += 2; - f += ddF_y; - } - x++; - ddF_x += 2; - f += ddF_x; - if (quadrants.topright){ - setPixel(x0 + x, y0 + y); // quadrant I - setPixel(x0 + y, y0 + x); // quadrant I - } - if (quadrants.topleft){ - setPixel(x0 - x, y0 + y); // quadrant II - setPixel(x0 - y, y0 + x); // quadrant II - } - if (quadrants.bottomleft){ - setPixel(x0 - x, y0 - y); // quadrant III - setPixel(x0 - y, y0 - x); // quadrant III - } - if (quadrants.bottomright){ - setPixel(x0 + x, y0 - y); // quadrant IV - setPixel(x0 + y, y0 - x); // quadrant IV - } + do the bresenham thing + */ +var _bresenham = function( x0,y0,radius, setPixel, quadrants ) { + // + // credit: Following code is copied almost verbatim from + // http://en.wikipedia.org/wiki/Midpoint_circle_algorithm + // Bresenham's circle algorithm + // + var f = 1 - radius; + var ddF_x = 1; + var ddF_y = -2 * radius; + var x = 0; + var y = radius; + var defaultQuadrants = {topleft: true, topright: true, bottomleft: true, bottomright: true}; + quadrants = quadrants?quadrants:defaultQuadrants; + /* + II | I + ------------ + III | IV + */ + if ( quadrants.topleft || quadrants.topright ) + setPixel(x0, y0 + radius ); // quadrant I/II topmost + if ( quadrants.bottomleft || quadrants.bottomright ) + setPixel(x0, y0 - radius ); // quadrant III/IV bottommost + if ( quadrants.topright || quadrants.bottomright ) + setPixel(x0 + radius, y0 ); // quadrant I/IV rightmost + if ( quadrants.topleft || quadrants.bottomleft ) + setPixel(x0 - radius, y0 ); // quadrant II/III leftmost + + while ( x < y ) { + if(f >= 0 ) { + y--; + ddF_y += 2; + f += ddF_y; } + x++; + ddF_x += 2; + f += ddF_x; + if ( quadrants.topright ) { + setPixel(x0 + x, y0 + y ); // quadrant I + setPixel(x0 + y, y0 + x ); // quadrant I + } + if ( quadrants.topleft ) { + setPixel(x0 - x, y0 + y ); // quadrant II + setPixel(x0 - y, y0 + x ); // quadrant II + } + if ( quadrants.bottomleft ) { + setPixel(x0 - x, y0 - y ); // quadrant III + setPixel(x0 - y, y0 - x ); // quadrant III + } + if ( quadrants.bottomright ) { + setPixel(x0 + x, y0 - y ); // quadrant IV + setPixel(x0 + y, y0 - x ); // quadrant IV + } + } }; -var _getStrokeDir = function(x,y){ - var absY = Math.abs(y); - var absX = Math.abs(x); - var strokeDir = 0; - if (y > 0 && absY >= absX) - strokeDir = 0 ; //down - else if (y < 0 && absY >= absX) - strokeDir = 1 ; // up - else if (x > 0 && absX >= absY) - strokeDir = 2 ; // left - else if (x < 0 && absX >= absY) - strokeDir = 3 ; // right - return strokeDir; +var _getStrokeDir = function( x,y ) { + var absY = Math.abs(y ); + var absX = Math.abs(x ); + var strokeDir = 0; + if ( y > 0 && absY >= absX ) + strokeDir = 0 ; //down + else if ( y < 0 && absY >= absX ) + strokeDir = 1 ; // up + else if ( x > 0 && absX >= absY ) + strokeDir = 2 ; // left + else if ( x < 0 && absX >= absY ) + strokeDir = 3 ; // right + return strokeDir; }; /* - The daddy of all arc-related API calls - - if you're drawing anything that bends it ends up here. -*/ -var _arc2 = function( params ) { + The daddy of all arc-related API calls - + if you're drawing anything that bends it ends up here. + */ +var _arc2 = function( params ) { - var drone = params.drone; - var orientation = params.orientation?params.orientation:"horizontal"; - var quadrants = params.quadrants?params.quadrants:{ - topright:1, - topleft:2, - bottomleft:3, - bottomright:4 - }; - var stack = params.stack?params.stack:1; - var radius = params.radius; - var strokeWidth = params.strokeWidth?params.strokeWidth:1; - drone.chkpt('arc2'); - var x0, y0, gotoxy,setPixel; - - if (orientation == "horizontal"){ - gotoxy = function(x,y){ return drone.right(x).fwd(y);}; - drone.right(radius).fwd(radius).chkpt('center'); - switch (drone.dir) { - case 0: // east - case 2: // west - x0 = drone.z; - y0 = drone.x; - break; - case 1: // south - case 3: // north - x0 = drone.x; - y0 = drone.z; + var drone = params.drone; + var orientation = params.orientation?params.orientation:'horizontal'; + var quadrants = params.quadrants?params.quadrants:{ + topright:1, + topleft:2, + bottomleft:3, + bottomright:4 + }; + var stack = params.stack?params.stack:1; + var radius = params.radius; + var strokeWidth = params.strokeWidth?params.strokeWidth:1; + drone.chkpt('arc2' ); + var x0, y0, gotoxy,setPixel; + + if ( orientation == 'horizontal' ) { + gotoxy = function( x,y ) { return drone.right(x ).fwd(y );}; + drone.right(radius ).fwd(radius ).chkpt('center' ); + switch ( drone.dir ) { + case 0: // east + case 2: // west + x0 = drone.z; + y0 = drone.x; + break; + case 1: // south + case 3: // north + x0 = drone.x; + y0 = drone.z; + } + setPixel = function( x,y ) { + x = (x-x0 ); + y = (y-y0 ); + if ( params.fill ) { + // wph 20130114 more efficient esp. for large cylinders/spheres + if ( y < 0 ) { + drone + .fwd(y ).right(x ) + .cuboidX(params.blockType,params.meta,1,stack,Math.abs(y*2 )+1 ) + .back(y ).left(x ); } - setPixel = function(x,y) { - x = (x-x0); - y = (y-y0); - if (params.fill){ - // wph 20130114 more efficient esp. for large cylinders/spheres - if (y < 0){ - drone - .fwd(y).right(x) - .cuboidX(params.blockType,params.meta,1,stack,Math.abs(y*2)+1) - .back(y).left(x); - } - }else{ - if (strokeWidth == 1){ - gotoxy(x,y) - .cuboidX(params.blockType, - params.meta, - 1, // width - stack, // height - strokeWidth // depth - ) - .move('center'); - } else { - var strokeDir = _getStrokeDir(x,y); - var width = 1, depth = 1; - switch (strokeDir){ - case 0: // down - y = y-(strokeWidth-1); - depth = strokeWidth; - break; - case 1: // up - depth = strokeWidth; - break; - case 2: // left - width = strokeWidth; - x = x-(strokeWidth-1); - break; - case 3: // right - width = strokeWidth; - break; - } - gotoxy(x,y) - .cuboidX(params.blockType, params.meta, width, stack, depth) - .move('center'); - - } - } - }; - }else{ - // vertical - gotoxy = function(x,y){ return drone.right(x).up(y);}; - drone.right(radius).up(radius).chkpt('center'); - switch (drone.dir) { - case 0: // east - case 2: // west - x0 = drone.z; - y0 = drone.y; + }else{ + if ( strokeWidth == 1 ) { + gotoxy(x,y ) + .cuboidX(params.blockType, + params.meta, + 1, // width + stack, // height + strokeWidth // depth + ) + .move('center' ); + } else { + var strokeDir = _getStrokeDir(x,y ); + var width = 1, depth = 1; + switch ( strokeDir ) { + case 0: // down + y = y-(strokeWidth-1 ); + depth = strokeWidth; break; - case 1: // south - case 3: // north - x0 = drone.x; - y0 = drone.y; + case 1: // up + depth = strokeWidth; + break; + case 2: // left + width = strokeWidth; + x = x-(strokeWidth-1 ); + break; + case 3: // right + width = strokeWidth; + break; + } + gotoxy(x,y ) + .cuboidX(params.blockType, params.meta, width, stack, depth ) + .move('center' ); + } - setPixel = function(x,y) { - x = (x-x0); - y = (y-y0); - if (params.fill){ - // wph 20130114 more efficient esp. for large cylinders/spheres - if (y < 0){ - drone - .up(y).right(x) - .cuboidX(params.blockType,params.meta,1,Math.abs(y*2)+1,stack) - .down(y).left(x); - } - }else{ - if (strokeWidth == 1){ - gotoxy(x,y) - .cuboidX(params.blockType,params.meta,strokeWidth,1,stack) - .move('center'); - }else{ - var strokeDir = _getStrokeDir(x,y); - var width = 1, height = 1; - switch (strokeDir){ - case 0: // down - y = y-(strokeWidth-1); - height = strokeWidth; - break; - case 1: // up - height = strokeWidth; - break; - case 2: // left - width = strokeWidth; - x = x-(strokeWidth-1); - break; - case 3: // right - width = strokeWidth; - break; - } - gotoxy(x,y) - .cuboidX(params.blockType, params.meta, width, height, stack) - .move('center'); - - } - } - }; - } - /* - setPixel assumes a 2D plane - need to put a block along appropriate plane - */ - _bresenham(x0,y0,radius,setPixel,quadrants); - - params.drone.move('arc2'); -}; - - -Drone.extend('arc',function(params) { - params.drone = this; - _arc2(params); -}); - -var _cylinder0 = function(block,radius,height,exactParams){ - var arcParams = { - radius: radius, - fill: false, - orientation: 'horizontal', - stack: height, + } }; - - if (exactParams){ - arcParams.blockType = exactParams.blockType; - arcParams.meta = exactParams.meta; - }else{ - var md = this._getBlockIdAndMeta(block); - arcParams.blockType = md[0]; - arcParams.meta = md[1]; + }else{ + // vertical + gotoxy = function( x,y ) { return drone.right(x ).up(y );}; + drone.right(radius ).up(radius ).chkpt('center' ); + switch ( drone.dir ) { + case 0: // east + case 2: // west + x0 = drone.z; + y0 = drone.y; + break; + case 1: // south + case 3: // north + x0 = drone.x; + y0 = drone.y; } - return this.arc(arcParams); -}; -var _cylinder1 = function(block,radius,height,exactParams){ - var arcParams = { - radius: radius, - fill: true, - orientation: 'horizontal', - stack: height, + setPixel = function( x,y ) { + x = (x-x0 ); + y = (y-y0 ); + if ( params.fill ) { + // wph 20130114 more efficient esp. for large cylinders/spheres + if ( y < 0 ) { + drone + .up(y ).right(x ) + .cuboidX(params.blockType,params.meta,1,Math.abs(y*2 )+1,stack ) + .down(y ).left(x ); + } + }else{ + if ( strokeWidth == 1 ) { + gotoxy(x,y ) + .cuboidX(params.blockType,params.meta,strokeWidth,1,stack ) + .move('center' ); + }else{ + var strokeDir = _getStrokeDir(x,y ); + var width = 1, height = 1; + switch ( strokeDir ) { + case 0: // down + y = y-(strokeWidth-1 ); + height = strokeWidth; + break; + case 1: // up + height = strokeWidth; + break; + case 2: // left + width = strokeWidth; + x = x-(strokeWidth-1 ); + break; + case 3: // right + width = strokeWidth; + break; + } + gotoxy(x,y ) + .cuboidX(params.blockType, params.meta, width, height, stack ) + .move('center' ); + + } + } }; - - if (exactParams){ - arcParams.blockType = exactParams.blockType; - arcParams.meta = exactParams.meta; - }else{ - var md = this._getBlockIdAndMeta(block); - arcParams.blockType = md[0]; - arcParams.meta = md[1]; - } - return this.arc(arcParams); + } + /* + setPixel assumes a 2D plane - need to put a block along appropriate plane + */ + _bresenham(x0,y0,radius,setPixel,quadrants ); + + params.drone.move('arc2' ); }; -var _paste = function(name) + + +Drone.extend('arc',function( params ) { + params.drone = this; + _arc2(params ); +} ); + +var _cylinder0 = function( block,radius,height,exactParams ) { + var arcParams = { + radius: radius, + fill: false, + orientation: 'horizontal', + stack: height, + }; + + if ( exactParams ) { + arcParams.blockType = exactParams.blockType; + arcParams.meta = exactParams.meta; + }else{ + var md = this._getBlockIdAndMeta(block ); + arcParams.blockType = md[0]; + arcParams.meta = md[1]; + } + return this.arc(arcParams ); +}; +var _cylinder1 = function( block,radius,height,exactParams ) { + var arcParams = { + radius: radius, + fill: true, + orientation: 'horizontal', + stack: height, + }; + + if ( exactParams ) { + arcParams.blockType = exactParams.blockType; + arcParams.meta = exactParams.meta; + }else{ + var md = this._getBlockIdAndMeta(block ); + arcParams.blockType = md[0]; + arcParams.meta = md[1]; + } + return this.arc(arcParams ); +}; +var _paste = function( name ) { - var ccContent = Drone.clipBoard[name]; - var srcBlocks = ccContent.blocks; - var srcDir = ccContent.dir; // direction player was facing when copied. - var dirOffset = (4 + (this.dir - srcDir)) %4; - var that = this; + var ccContent = Drone.clipBoard[name]; + var srcBlocks = ccContent.blocks; + var srcDir = ccContent.dir; // direction player was facing when copied. + var dirOffset = (4 + (this.dir - srcDir ) ) %4; + var that = this; - _traverse[this.dir].width(that,srcBlocks.length,function(ww){ - var h = srcBlocks[ww].length; - _traverseHeight(that,h,function(hh){ - var d = srcBlocks[ww][hh].length; - _traverse[that.dir].depth(that,d,function(dd){ - var b = srcBlocks[ww][hh][dd]; - var bm = that._getBlockIdAndMeta(b); - var cb = bm[0]; - var md = bm[1]; - // - // need to adjust blocks which face a direction - // - switch (cb) - { - // - // doors - // - case 64: // wood - case 71: // iron - // top half of door doesn't need to change - if (md < 8) { - md = (md + dirOffset) % 4; - } - break; - // - // stairs - // - case 53: // oak - case 67: // cobblestone - case 108: // red brick - case 109: // stone brick - case 114: // nether brick - case 128: // sandstone - case 134: // spruce - case 135: // birch - case 136: // junglewood - var dir = md & 0x3; - var a = Drone.PLAYER_STAIRS_FACING; - var len = a.length; - for (var c=0;c < len;c++){ - if (a[c] == dir){ - break; - } - } - c = (c + dirOffset) %4; - var newDir = a[c]; - md = (md >>2<<2) + newDir; - break; - // - // signs , ladders etc - // - case 23: // dispenser - case 54: // chest - case 61: // furnace - case 62: // burning furnace - case 65: // ladder - case 68: // wall sign - var a = Drone.PLAYER_SIGN_FACING; - var len = a.length; - for (var c=0;c < len;c++){ - if (a[c] == md){ - break; - } - } - c = (c + dirOffset) %4; - var newDir = a[c]; - md = newDir; - break; - } - putBlock(that.x,that.y,that.z,cb,md,that.world); - }); - }); - }); -}; -var _getDirFromRotation = function(r){ - // 0 = east, 1 = south, 2 = west, 3 = north - // 46 to 135 = west - // 136 to 225 = north - // 226 to 315 = east - // 316 to 45 = south - - r = (r + 360) % 360; // east could be 270 or -90 - - if (r > 45 && r <= 135) - return 2; // west - if (r > 135 && r <= 225) - return 3; // north - if (r > 225 && r <= 315) - return 0; // east - if (r > 315 || r < 45) - return 1; // south -}; -var _getBlockIdAndMeta = function(b){ - var defaultMeta = 0; - if (typeof b == 'string'){ - var bs = b; - var sp = bs.indexOf(':'); - if (sp == -1){ - b = parseInt(bs); - // wph 20130414 - use sensible defaults for certain blocks e.g. stairs - // should face the drone. - for (var i in blocks.stairs){ - if (blocks.stairs[i] === b){ - defaultMeta = Drone.PLAYER_STAIRS_FACING[this.dir]; - break; - } + _traverse[this.dir].width(that,srcBlocks.length,function( ww ) { + var h = srcBlocks[ww].length; + _traverseHeight(that,h,function( hh ) { + var d = srcBlocks[ww][hh].length; + _traverse[that.dir].depth(that,d,function( dd ) { + var b = srcBlocks[ww][hh][dd]; + var bm = that._getBlockIdAndMeta(b ); + var cb = bm[0]; + var md = bm[1]; + // + // need to adjust blocks which face a direction + // + switch ( cb ) { + // + // doors + // + case 64: // wood + case 71: // iron + // top half of door doesn't need to change + if ( md < 8 ) { + md = (md + dirOffset ) % 4; + } + break; + // + // stairs + // + case 53: // oak + case 67: // cobblestone + case 108: // red brick + case 109: // stone brick + case 114: // nether brick + case 128: // sandstone + case 134: // spruce + case 135: // birch + case 136: // junglewood + var dir = md & 0x3; + var a = Drone.PLAYER_STAIRS_FACING; + var len = a.length; + for ( var c=0;c < len;c++ ) { + if ( a[c] == dir ) { + break; } - return [b,defaultMeta]; - } - b = parseInt(bs.substring(0,sp)); - var md = parseInt(bs.substring(sp+1,bs.length)); - return [b,md]; - }else{ - // wph 20130414 - use sensible defaults for certain blocks e.g. stairs - // should face the drone. - for (var i in blocks.stairs){ - if (blocks.stairs[i] === b){ - defaultMeta = Drone.PLAYER_STAIRS_FACING[this.dir]; - break; + } + c = (c + dirOffset ) %4; + var newDir = a[c]; + md = (md >>2<<2 ) + newDir; + break; + // + // signs , ladders etc + // + case 23: // dispenser + case 54: // chest + case 61: // furnace + case 62: // burning furnace + case 65: // ladder + case 68: // wall sign + var a = Drone.PLAYER_SIGN_FACING; + var len = a.length; + for ( var c=0;c < len;c++ ) { + if ( a[c] == md ) { + break; } + } + c = (c + dirOffset ) %4; + var newDir = a[c]; + md = newDir; + break; } - return [b,defaultMeta]; + putBlock(that.x,that.y,that.z,cb,md,that.world ); + } ); + } ); + } ); +}; +var _getDirFromRotation = function( r ) { + // 0 = east, 1 = south, 2 = west, 3 = north + // 46 to 135 = west + // 136 to 225 = north + // 226 to 315 = east + // 316 to 45 = south + + r = (r + 360 ) % 360; // east could be 270 or -90 + + if ( r > 45 && r <= 135 ) + return 2; // west + if ( r > 135 && r <= 225 ) + return 3; // north + if ( r > 225 && r <= 315 ) + return 0; // east + if ( r > 315 || r < 45 ) + return 1; // south +}; +var _getBlockIdAndMeta = function(b ) { + var defaultMeta = 0; + if ( typeof b == 'string' ) { + var bs = b; + var sp = bs.indexOf(':' ); + if ( sp == -1 ) { + b = parseInt(bs ); + // wph 20130414 - use sensible defaults for certain blocks e.g. stairs + // should face the drone. + for ( var i in blocks.stairs ) { + if ( blocks.stairs[i] === b ) { + defaultMeta = Drone.PLAYER_STAIRS_FACING[this.dir]; + break; + } + } + return [b,defaultMeta]; } + b = parseInt(bs.substring(0,sp ) ); + var md = parseInt(bs.substring(sp+1,bs.length ) ); + return [b,md]; + }else{ + // wph 20130414 - use sensible defaults for certain blocks e.g. stairs + // should face the drone. + for ( var i in blocks.stairs ) { + if ( blocks.stairs[i] === b ) { + defaultMeta = Drone.PLAYER_STAIRS_FACING[this.dir]; + break; + } + } + return [b,defaultMeta]; + } }; // // movement // var _movements = [{},{},{},{}]; // east -_movements[0].right = function(that,n){ that.z +=n; return that;}; -_movements[0].left = function(that,n){ that.z -=n; return that;}; -_movements[0].fwd = function(that,n){ that.x +=n; return that;}; -_movements[0].back = function(that,n){ that.x -= n; return that;}; +_movements[0].right = function( that,n ) { that.z +=n; return that;}; +_movements[0].left = function( that,n ) { that.z -=n; return that;}; +_movements[0].fwd = function( that,n ) { that.x +=n; return that;}; +_movements[0].back = function( that,n ) { that.x -= n; return that;}; // south _movements[1].right = _movements[0].back; _movements[1].left = _movements[0].fwd; @@ -1576,145 +1605,144 @@ _movements[3].fwd = _movements[0].left; _movements[3].back = _movements[0].right; var _traverse = [{},{},{},{}]; // east -_traverse[0].width = function(that,n,callback){ - var s = that.z, e = s + n; - for (; that.z < e; that.z++){ - callback(that.z-s); - } - that.z = s; +_traverse[0].width = function( that,n,callback ) { + var s = that.z, e = s + n; + for ( ; that.z < e; that.z++ ) { + callback(that.z-s ); + } + that.z = s; }; -_traverse[0].depth = function(that,n,callback){ - var s = that.x, e = s+n; - for (;that.x < e;that.x++){ - callback(that.x-s); - } - that.x = s; +_traverse[0].depth = function( that,n,callback ) { + var s = that.x, e = s+n; + for ( ;that.x < e;that.x++ ) { + callback(that.x-s ); + } + that.x = s; }; // south -_traverse[1].width = function(that,n,callback){ - var s = that.x, e = s-n; - for (;that.x > e;that.x--){ - callback(s-that.x); - } - that.x = s; +_traverse[1].width = function( that,n,callback ) { + var s = that.x, e = s-n; + for ( ;that.x > e;that.x-- ) { + callback(s-that.x ); + } + that.x = s; }; _traverse[1].depth = _traverse[0].width; // west -_traverse[2].width = function(that,n,callback){ - var s = that.z, e = s-n; - for (;that.z > e;that.z--){ - callback(s-that.z); - } - that.z = s; +_traverse[2].width = function( that,n,callback ) { + var s = that.z, e = s-n; + for ( ;that.z > e;that.z-- ) { + callback(s-that.z ); + } + that.z = s; }; _traverse[2].depth = _traverse[1].width; // north _traverse[3].width = _traverse[0].depth; _traverse[3].depth = _traverse[2].width; -var _traverseHeight = function(that,n,callback){ - var s = that.y, e = s + n; - for (; that.y < e; that.y++){ - callback(that.y-s); - } - that.y = s; +var _traverseHeight = function( that,n,callback ) { + var s = that.y, e = s + n; + for ( ; that.y < e; that.y++ ) { + callback(that.y-s ); + } + that.y = s; }; // // standard fisher-yates shuffle algorithm // -var _fisherYates = function( myArray ) { - var i = myArray.length; - if ( i == 0 ) return false; - while ( --i ) { - var j = Math.floor( Math.random() * ( i + 1 ) ); - var tempi = myArray[i]; - var tempj = myArray[j]; - myArray[i] = tempj; - myArray[j] = tempi; - } +var _fisherYates = function( myArray ) { + var i = myArray.length; + if ( i == 0 ) return false; + while ( --i ) { + var j = Math.floor( Math.random( ) * ( i + 1 ) ); + var tempi = myArray[i]; + var tempj = myArray[j]; + myArray[i] = tempj; + myArray[j] = tempi; + } }; -var _copy = function(name, w, h, d) { - var that = this; - var ccContent = []; - _traverse[this.dir].width(that,w,function(ww){ - ccContent.push([]); - _traverseHeight(that,h,function(hh){ - ccContent[ww].push([]); - _traverse[that.dir].depth(that,d,function(dd){ - var b = that.world.getBlockAt(that.x,that.y,that.z); - ccContent[ww][hh][dd] = b; - }); - }); - }); - Drone.clipBoard[name] = {dir: this.dir, blocks: ccContent}; +var _copy = function( name, w, h, d ) { + var that = this; + var ccContent = []; + _traverse[this.dir].width(that,w,function( ww ) { + ccContent.push([] ); + _traverseHeight(that,h,function( hh ) { + ccContent[ww].push([] ); + _traverse[that.dir].depth(that,d,function( dd ) { + var b = that.world.getBlockAt(that.x,that.y,that.z ); + ccContent[ww][hh][dd] = b; + } ); + } ); + } ); + Drone.clipBoard[name] = {dir: this.dir, blocks: ccContent}; }; -var _garden = function(w,d) { - // make sure grass is present first - this.down().box(2,w,1,d).up(); - - // make flowers more common than long grass - var dist = {37: 3, // red flower - 38: 3, // yellow flower - '31:1': 2, // long grass - 0: 1 - }; - - return this.rand(dist,w,1,d); +var _garden = function( w,d ) { + // make sure grass is present first + this.down( ).box(2,w,1,d ).up( ); + + // make flowers more common than long grass + var dist = {37: 3, // red flower + 38: 3, // yellow flower + '31:1': 2, // long grass + 0: 1 + }; + + return this.rand(dist,w,1,d ); }; -var _rand = function(blockDistribution){ - if (!(blockDistribution.constructor == Array)){ - var a = []; - for (var p in blockDistribution){ - var n = blockDistribution[p]; - for (var i = 0;i < n;i++){ - a.push(p); - } - } - blockDistribution = a; +var _rand = function( blockDistribution ) { + if ( !(blockDistribution.constructor == Array ) ) { + var a = []; + for ( var p in blockDistribution ) { + var n = blockDistribution[p]; + for ( var i = 0;i < n;i++ ) { + a.push(p ); + } } - while (blockDistribution.length < 1000){ - // make array bigger so that it's more random - blockDistribution = blockDistribution.concat(blockDistribution); - } - _fisherYates(blockDistribution); - return blockDistribution; + blockDistribution = a; + } + while ( blockDistribution.length < 1000 ) { + // make array bigger so that it's more random + blockDistribution = blockDistribution.concat(blockDistribution ); + } + _fisherYates(blockDistribution ); + return blockDistribution; }; -Drone.extend('rand',function(dist,w,h,d){ - var randomized = _rand(dist); - this.boxa(randomized,w,h,d); -}); +Drone.extend('rand',function( dist,w,h,d ) { + var randomized = _rand(dist ); + this.boxa(randomized,w,h,d ); +} ); var _trees = { - oak: org.bukkit.TreeType.BIG_TREE , - birch: org.bukkit.TreeType.BIRCH , - jungle: org.bukkit.TreeType.JUNGLE, - spruce: org.bukkit.TreeType.REDWOOD + oak: TreeType.BIG_TREE , + birch: TreeType.BIRCH , + jungle: TreeType.JUNGLE, + spruce: TreeType.REDWOOD }; -for (var p in _trees) -{ - Drone.extend(p, function(v) { - return function() { - var block = this.world.getBlockAt(this.x,this.y,this.z); - if (block.typeId == 2){ - this.up(); - } - var treeLoc = new org.bukkit.Location(this.world,this.x,this.y,this.z); - var successful = treeLoc.world.generateTree(treeLoc,v); - if (block.typeId == 2){ - this.down(); - } - }; - }(_trees[p])); +for ( var p in _trees ) { + Drone.extend(p, function( v ) { + return function( ) { + var block = this.world.getBlockAt(this.x,this.y,this.z ); + if ( block.typeId == 2 ) { + this.up( ); + } + var treeLoc = new Location(this.world,this.x,this.y,this.z ); + var successful = treeLoc.world.generateTree(treeLoc,v ); + if ( block.typeId == 2 ) { + this.down( ); + } + }; + }(_trees[p] ) ); } // // Drone's clipboard // Drone.clipBoard = {}; -Drone.extend('garden',_garden); -Drone.extend('copy', _copy); -Drone.extend('paste',_paste); -Drone.extend('cylinder0',_cylinder0); -Drone.extend('cylinder', _cylinder1); +Drone.extend('garden',_garden ); +Drone.extend('copy', _copy ); +Drone.extend('paste',_paste ); +Drone.extend('cylinder0',_cylinder0 ); +Drone.extend('cylinder', _cylinder1 ); // // wph 20130130 - make this a method - extensions can use it. // diff --git a/src/main/js/plugins/drone/sphere.js b/src/main/js/plugins/drone/sphere.js index 3ba43eb..7b91a4f 100644 --- a/src/main/js/plugins/drone/sphere.js +++ b/src/main/js/plugins/drone/sphere.js @@ -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]); - lastRadius = 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 ] ); } - 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]); + lastRadius = newRadius; + } + 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] ); + + yOffset = -1; + for ( i = 1; i < slices.length; i++ ) { + yOffset += slices[i-1][1]; + 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 ); - var yOffset = -1; - for (var 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; - // 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); - - // 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); - } - return this.move('sphere'); + // 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 ); + } + return this.move( 'sphere' ); }); /************************************************************************ ### Drone.sphere0() method @@ -88,81 +103,80 @@ 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]); - lastRadius = 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 ] ); } - this.chkpt('sphere0'); - // - // mid section - // - //.cylinder(block,radius,(slices[0][1]*2)-1,{blockType: bm[0],meta: bm[1]}) - this.up(radius - slices[0][1]) - .arc({blockType: bm[0], - meta: bm[1], - radius: radius, - strokeWidth: 2, - stack: (slices[0][1]*2)-1, - fill: false - }) - .down(radius-slices[0][1]); + lastRadius = newRadius; + } + this.chkpt( 'sphere0' ); + // + // mid section + // + 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] ); + + yOffset = -1; + len = slices.length; + for ( i = 1; i < len; i++ ) { + yOffset += slices[i-1][1]; + 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 ) + .arc({ + blockType: bm[0], + meta: bm[1], + radius: sr, + stack: sh, + fill: false, + strokeWidth: i < len - 1 ? 1 + ( sr - slices[ i + 1 ][ 0 ] ) : 1 + }) + .left( h ).back( h ).down( v ); - var yOffset = -1; - var len = slices.length; - for (var 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; - // northern hemisphere - // .cylinder(block,sr,sh,{blockType: bm[0],meta: bm[1]}) - this.up(v).fwd(h).right(h) - .arc({ - blockType: bm[0], - meta: bm[1], - radius: sr, - stack: sh, - fill: false, - strokeWidth: i : Go to player's home", - "/jsp home set : Set your current location as home", - "/jsp home delete : Delete your home location", +var homes = plugin( 'homes', { - /* social */ - "/jsp home list : List homes you can visit", - "/jsp home ilist : List players who can visit your home", - "/jsp home invite : Invite to your home", - "/jsp home uninvite : Uninvite to your home", - "/jsp home public : Open your home to all players", - "/jsp home private : Make your home private", + help: function( ) { + return [ + /* basic functions */ + '/jsp home : Return to your own home', + '/jsp home : Go to player home', + '/jsp home set : Set your current location as home', + '/jsp home delete : Delete your home location', - /* administration */ - "/jsp home listall : Show all houses (ops only)", - "/jsp home clear : Clears player's home location (ops only)" - ]; - }, - /* ======================================================================== - basic functions - ======================================================================== */ + /* social */ + '/jsp home list : List homes you can visit', + '/jsp home ilist : List players who can visit your home', + '/jsp home invite : Invite to your home', + '/jsp home uninvite : Uninvite to your home', + '/jsp home public : Open your home to all players', + '/jsp home private : Make your home private', - go: function(guest, host){ - 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"); - return; - } - if (!this._canVisit(guest,host)){ - guest.sendMessage("You can't 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); - }, - /* - determine whether a guest is allow visit a host's home - */ - _canVisit: function(guest, host){ - if (guest == host) - return true; - 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) - return true; - return false; - }, - set: function(player){ - player = utils.player(player); - var loc = player.location; - _store.houses[player.name] = utils.locationToJSON(loc); - }, - remove: function(player){ - player = utils.player(player); - delete _store.houses[player.name]; - }, - /* ======================================================================== - social functions - ======================================================================== */ - - /* - list homes which the player can visit - */ - list: function(player){ - var result = []; - for (var 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) - result.push(host); - } - return result; - }, - /* - list who can visit the player's home - */ - ilist: function(player){ - player = utils.player(player); - var result = []; - // if home is public - all players - if (_store.openHouses[player.name]){ - var online = org.bukkit.Bukkit.getOnlinePlayers(); - for (var i = 0;i < online.length; i++) - if (online[i].name != player.name) - result.push(online[i].name); - }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); - var invitations = []; - if (_store.invites[host.name]) - invitations = _store.invites[host.name]; - invitations.push(guest.name); - _store.invites[host.name] = invitations; - guest.sendMessage(host.name + " has invited you to their home."); - guest.sendMessage("type '/jsp home " + host.name + "' to accept"); - }, - /* - 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) - return; - var revisedInvites = []; - for (var 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 - */ - 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 - */ - close: function(player){ - player = utils.player(player); - delete _store.openHouses[player.name]; - }, - /* ======================================================================== - admin functions - ======================================================================== */ - listall: function(){ - var result = []; - 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]; - }, - store: _store -}, true); + /* administration */ + '/jsp home listall : Show all houses (ops only)', + '/jsp home clear : Clears player home location (ops only)' + ]; + }, + /* ======================================================================== + basic functions + ======================================================================== */ + + go: function( guest, host ) { + var loc, + homeLoc; + if ( typeof host == 'undefined' ) { + host = guest; + } + 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 not visit ' + host.name + "'s home yet" ); + return; + } + homeLoc = utils.locationFromJSON( loc ); + guest.teleport(homeLoc, TeleportCause.PLUGIN); + }, + /* + determine whether a guest is allow visit a host's home + */ + _canVisit: function( guest, host ) { + var invitations, + i; + if ( guest == host ) { + return true; + } + if ( _store.openHouses[ host.name ] ) { + return true; + } + invitations = _store.invites[ host.name ]; + if ( invitations ) { + for ( i = 0; i < invitations.length; i++ ) { + if ( invitations[i] == guest.name ) { + return true; + } + } + } + return false; + }, + + set: function( player ) { + player = utils.player( player ); + var loc = player.location; + _store.houses[player.name] = utils.locationToJSON( loc ); + }, + + remove: function( player ) { + player = utils.player( player ); + delete _store.houses[ player.name ]; + }, + /* ======================================================================== + social functions + ======================================================================== */ + + /* + list homes which the player can visit + */ + list: function( player ) { + var result = [], + ohp, + host, + guests, + i; + for ( ohp in _store.openHouses ) { + result.push(ohp); + } + player = utils.player(player); + 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 home + */ + ilist: function( player ) { + var result = [], + onlinePlayers, + i; + player = utils.player( player ); + // if home is public - all players + 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 ); + var invitations = []; + if ( _store.invites[host.name] ) { + invitations = _store.invites[host.name]; + } + invitations.push( guest.name ); + _store.invites[host.name] = invitations; + guest.sendMessage( host.name + ' has invited you to their home.' ); + guest.sendMessage( 'type "/jsp home ' + host.name + '" to accept' ); + }, + /* + Uninvite someone to the home + */ + uninvite: function( host, guest ) { + var invitations, + revisedInvites, + i; + host = utils.player( host ); + guest = utils.player( guest ); + invitations = _store.invites[ host.name ]; + if ( !invitations ) { + return; + } + 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 house public + */ + open: function( player, optionalMsg ) { + player = utils.player( player ); + _store.openHouses[ player.name ] = true; + if ( typeof optionalMsg != 'undefined' ) { + __plugin.server.broadcastMessage( optionalMsg ); + } + }, + + /* + make the player house private + */ + close: function( player ) { + player = utils.player( player ); + delete _store.openHouses[ player.name ]; + }, + /* ======================================================================== + admin functions + ======================================================================== */ + listall: function( ) { + var result = []; + 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 ]; + }, + store: _store +}, true ); exports.homes = homes; /* - define a set of command options that can be used by players -*/ + define a set of command options that can be used by players + */ var options = { - '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"); - return; - }else{ - sender.sendMessage([ - "You can visit any of these " + visitable.length + " homes" - ,visitable.join(", ") - ]); - } - }, - 'ilist': function(params, sender){ - var potentialVisitors = homes.ilist(); - if (potentialVisitors.length == 0) - sender.sendMessage("No one can visit your home"); - else - sender.sendMessage([ - "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"); - return; - } - var playerName = params[1]; - 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"); - return; - } - var playerName = params[1]; - 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"); - }, - '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(", ")); - }, - 'clear': function(params,sender){ - if (!sender.isOp()) - sender.sendMessage("Only operators can do this"); - else - homes.clear(params[1], 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' ); + return; + } else { + sender.sendMessage([ + 'You can visit any of these ' + visitable.length + ' homes' + ,visitable.join(', ') + ]); } + }, + + 'ilist': function( params, sender ) { + var potentialVisitors = homes.ilist(); + if ( potentialVisitors.length == 0 ) { + sender.sendMessage('No one can visit your home'); + } else { + sender.sendMessage([ + '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 name' ); + return; + } + var playerName = params[1]; + 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 name' ); + return; + } + var playerName = params[1]; + 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' ); + }, + + '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(', ') ); + } + }, + + '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) - optionList.push(o); +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); - return; + Expose a set of commands that players can use at the in-game command prompt + */ +command( 'home', function ( params , sender) { + var option, + host; + if ( params.length == 0 ) { + homes.go( sender, sender ); + return; + } + 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 ); } - 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); - } -},optionList); + } +}, optionList ); diff --git a/src/main/js/plugins/minigames/NumberGuess.js b/src/main/js/plugins/minigames/NumberGuess.js index 5dbac98..6fb0938 100644 --- a/src/main/js/plugins/minigames/NumberGuess.js +++ b/src/main/js/plugins/minigames/NumberGuess.js @@ -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; + var guesses = 0; - 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; + sb( 'objectives add NumberGuess dummy Guesses' ); + sb( 'players set ' + sender.name + ' NumberGuess ' + guesses ); + sb( 'objectives setdisplay sidebar NumberGuess' ); - var number = Math.ceil(Math.random() * 10); - - var prompt = new Prompt() - { - getPromptText: function(ctx){ - var hint = ""; - var h = ctx.getSessionData("hint"); - if (h){ - hint = h; - } - 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); - return null; - }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); - - return prompt; - } - }, - blocksForInput: function(ctx){ return true; } - }; - var cf = new ConversationFactory(__plugin); - var conv = cf.withModality(true) - .withFirstPrompt(prompt) - .withPrefix(new ConversationPrefix(){ getPrefix: function(ctx){ return "[1-10] ";} }) - .buildConversation(sender); - conv.begin(); - } + var number = Math.ceil( Math.random() * 10 ); + + var prompt = new Prompt( ) { + + getPromptText: function( ctx ) { + var hint = ''; + var h = ctx.getSessionData( 'hint' ); + if ( h ) { + hint = h; + } + 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 ); + return null; + } 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 ); + + return prompt; + } + }, + + blocksForInput: function( ctx ) { + return true; + } + }; + var convPrefix = new ConversationPrefix( ) { + getPrefix: function( ctx ) { + return '[1-10] '; + } + }; + new ConversationFactory( __plugin ) + .withModality( true ) + .withFirstPrompt( prompt ) + .withPrefix( convPrefix ) + .buildConversation( sender ) + .begin( ); + } }; diff --git a/src/main/js/plugins/minigames/SnowballFight.js b/src/main/js/plugins/minigames/SnowballFight.js index d7ea67a..afa17a9 100644 --- a/src/main/js/plugins/minigames/SnowballFight.js +++ b/src/main/js/plugins/minigames/SnowballFight.js @@ -42,141 +42,170 @@ cover to make the game more fun. ***/ -var _startGame = function(gameState){ - // don't let game start if already in progress (wait for game to finish) - if (gameState.inProgress){ - return; - } - gameState.inProgress = true; - // reset timer - 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 (var 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); - } - } -}; -/* - end the game -*/ -var _endGame = function(gameState){ - var scores = []; - - var leaderBoard = []; - for (var 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 (var teamName in gameState.teams) { - var team = gameState.teams[teamName]; - for (var 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); - } - } - var handlerList = org.bukkit.event.entity.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) - 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 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 _gameState = { - teams: teams, - duration: duration, - originalDuration: duration, - inProgress: false, - teamScores: {}, - listener: null, - savedModes: {}, - ammo: [_snowBalls] - }; - if (typeof duration == "undefined"){ - duration = 60; +var _startGame = function( gameState ) { + var i, + teamName, + team, + player; + + // don't let game start if already in progress (wait for game to finish) + if ( gameState.inProgress ) { + return; + } + gameState.inProgress = true; + // reset timer + 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 ( i = 10; i < gameState.duration; i += 10 ) { + gameState.ammo.push( gameState.ammo[ 0 ] ); + } + + for ( teamName in gameState.teams ) { + gameState.teamScores[teamName] = 0; + 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 ); } - 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); - } + } +}; +/* + end the game + */ +var _endGame = function( gameState ) { + var scores = [], + leaderBoard = [], + tn, + i, + teamName, + team, + player, + handlerList; + + leaderBoard = []; + for ( tn in gameState.teamScores){ + leaderBoard.push([tn,gameState.teamScores[tn]]); + } + leaderBoard.sort(function(a,b){ return b[1] - a[1];}); + + for ( i = 0; i < leaderBoard.length; i++ ) { + scores.push( 'Team ' + leaderBoard[i][0] + ' scored ' + leaderBoard[i][1] ); + } + + 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 + player = server.getPlayer( team[i] ); + player.gameMode = gameState.savedModes[ player.name ]; + player.inventory.removeItem( gameState.ammo ); + player.sendMessage( 'GAME OVER.' ); + player.sendMessage( scores ); } - // - // 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){ - _gameState.teams = {}; - for (var i = 0;i < teams.length; i++) - _gameState.teams[teams[i]] = [teams[i]]; + } + handlerList = EntityDamageByEntityEvent.getHandlerList(); + handlerList.unregister( gameState.listener ); + gameState.inProgress = false; +}; +/* + get the team the player belongs to + */ +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 players, + i, + _snowBalls = new ItemStack( Material.SNOW_BALL, 64 ); + + var _gameState = { + teams: teams, + duration: duration, + originalDuration: duration, + inProgress: false, + teamScores: {}, + listener: null, + savedModes: {}, + ammo: [ _snowBalls ] + }; + if ( typeof duration == 'undefined' ) { + duration = 60; + } + if ( typeof teams == 'undefined' ) { /* - this function is called every time a player is damaged by another entity/player - */ - var _onSnowballHit = function(l,event){ - var snowball = event.damager; - if (!snowball || !(snowball instanceof org.bukkit.entity.Snowball)) - return; - 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]--; - }; - - return { - 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) - _endGame(_gameState); - }).start(); - } - }; + wph 20130511 use all players + */ + teams = []; + 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 ) { + _gameState.teams = {}; + for ( i = 0;i < teams.length; i++ ) { + _gameState.teams[ teams[i] ] = [ teams[i] ]; + } + } + /* + this function is called every time a player is damaged by another entity/player + */ + var _onSnowballHit = function( l, event ) { + var snowball = event.damager; + if ( !snowball || !( snowball instanceof Snowball ) ) { + return; + } + 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 ]--; + } + }; + + return { + 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) + } + _endGame(_gameState); + } ).start( ); + } + }; }; exports.Game_SnowballFight = createGame; diff --git a/src/main/js/plugins/minigames/cow-clicker.js b/src/main/js/plugins/minigames/cow-clicker.js index 16615ae..d03027d 100644 --- a/src/main/js/plugins/minigames/cow-clicker.js +++ b/src/main/js/plugins/minigames/cow-clicker.js @@ -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 ] ) { + return; + } + + var sound = function( snd, vol, pitch ) { + loc.world.playSound( loc, snd, vol, pitch ); + }; + + if ( clickedEntity instanceof Cow) { + store[ player.name ].score++; + scoreboard.update( 'cowclicker', player, store[ player.name ].score ); - if (!store[player.name]) - return; - - var clickedEntity = event.rightClicked; - var loc = clickedEntity.location; - var sound = function(snd,vol,pitch){ - loc.world.playSound(loc,snd,vol,pitch); - }; - if (clickedEntity instanceof org.bukkit.entity.Cow) - { - 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); + 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 _onPlayerJoin = function( listener, event ) { + var gamePlayer = store[event.player.name]; + if ( gamePlayer ) { + _addPlayer( event.player, gamePlayer.score ); + } +}; + +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 ); + + scoreboard.start(); + + 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 ); } -}; -var _onPlayerQuit = function(listener, event){ - _removePlayer(event.player) -}; -var _onPlayerJoin = function(listener, event){ - var gamePlayer = store[event.player.name]; - if (gamePlayer) - _addPlayer(event.player, gamePlayer.score); + } }; -var _startGame = function(){ - if (config.verbose) - console.log('Staring game: Cow Clicker'); - - events.on('player.PlayerQuitEvent', _onPlayerQuit); - events.on('player.PlayerJoinEvent', _onPlayerJoin); - events.on('player.PlayerInteractEntityEvent', _onPlayerInteract); +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); + + player.sendMessage( 'Go forth and click some cows!' ); +}; - scoreboard.start(); +var _removePlayer = function( player, notify ) { - store = persist('cowclicker',store); - for (var p in store){ - var player = server.getPlayer(p); - if (player){ - /* - only add online players - */ - var score = store[p].score; - _addPlayer(player, score); - } + if ( player instanceof OfflinePlayer && player.player ) { + player = player.player; + } + + if ( !store[player.name] ) { + return; + } + if ( config.verbose ) { + console.log( 'Removing player %s from Cow Clicker', player ); + } + + var playerScore = store[ player.name ].score; + + scoreboard.restore( player ); + + 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' ) { + notify = false; + } + for ( var p in store ) { + var player = server.getOfflinePlayer( p ); + if ( player ) { + _removePlayer( player, notify ); } -}; -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); - - player.sendMessage('Go forth and click some cows!'); + delete store[p]; + } }; -var _removePlayer = function(player,notify){ - - if (player instanceof org.bukkit.OfflinePlayer && player.player) - player = player.player; - - if (!store[player.name]) - return; - if (config.verbose) - console.log('Removing player %s from Cow Clicker', player); - - var playerScore = store[player.name].score; - - scoreboard.restore(player); - - 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') - notify = false; - 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') - removePlayers = true; - if (config.verbose) - console.log('Stopping game: Cow Clicker'); - scoreboard.stop(); - if (!removePlayers) - return; - _removeAllPlayers(false); - persist('cowclicker',store.pers,'w'); +var _stopGame = function( removePlayers ) { + if ( typeof removePlayers == 'undefined' ) { + removePlayers = true; + } + if ( config.verbose ) { + console.log( 'Stopping game: Cow Clicker' ); + } + scoreboard.stop(); + if ( !removePlayers ) { + return; + } + _removeAllPlayers( false ); + persist( 'cowclicker', store.pers, 'w' ); }; /* - start the game automatically when this module is loaded. -*/ + start the game automatically when this module is loaded. + */ _startGame(); /* - 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); + 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 ); + } }); /* - stop the game when ScriptCraft is unloaded. -*/ -addUnloadHandler(function(){ - _stopGame(false); -}); + stop the game when ScriptCraft is unloaded. + */ +addUnloadHandler( function( ) { + _stopGame( false ); +} ); diff --git a/src/main/js/plugins/spawn.js b/src/main/js/plugins/spawn.js index 975de56..97e4c4c 100644 --- a/src/main/js/plugins/spawn.js +++ b/src/main/js/plugins/spawn.js @@ -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){ - entities.push(t); - } +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'); - return; - } - var location = sender.location; - var world = location.world; - var type = ('' + parameters[0]).toUpperCase(); - world.spawnEntity(location, org.bukkit.entity.EntityType[type]); -},entities); +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, EntityType[type] ); +}, entities ); diff --git a/src/main/resources/boot.js b/src/main/resources/boot.js index 5cdd1d6..aed8412 100644 --- a/src/main/resources/boot.js +++ b/src/main/resources/boot.js @@ -1,76 +1,87 @@ /* - This file is the first and only file executed directly from the Java Plugin. -*/ + This file is the first and only file executed directly from the Java Plugin. + */ var __scboot = null; (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 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; - while ( ( entry = zis.nextEntry ) != null ) { + while ( ( entry = zis.nextEntry ) != null ) { - newFile = new File(jsPlugins, entry.name); - if (entry.isDirectory()){ - newFile.mkdirs(); - zis.closeEntry(); - continue; - } - reason = null; - zTime = entry.time; - unzipFile = false; - if (!newFile.exists()) { - reason = 'NE'; - unzipFile = true; - }else{ - fTime = newFile.lastModified(); - if (zTime > fTime) { - reason = ((zTime - fTime) / 3600000) + "h"; - unzipFile = true; - } - } - if (unzipFile) { - logger.info('Unzipping ' + newFile.canonicalPath + ' (' + reason + ')' ); - fout = new FileOutputStream(newFile); - for (c = zis.read(); c != -1; c = zis.read()) { - fout.write(c); - } - fout.close(); - } - zis.closeEntry(); + newFile = new File(jsPlugins, entry.name); + if (entry.isDirectory()){ + newFile.mkdirs(); + zis.closeEntry(); + continue; + } + reason = null; + zTime = entry.time; + unzipFile = false; + if (!newFile.exists()) { + reason = 'NE'; + unzipFile = true; + }else{ + fTime = newFile.lastModified(); + if (zTime > fTime) { + reason = ((zTime - fTime) / 3600000) + "h"; + unzipFile = true; } - zis.close(); - }; + } + if (unzipFile) { + logger.info('Unzipping ' + newFile.canonicalPath + ' (' + reason + ')' ); + fout = new FileOutputStream(newFile); + for (c = zis.read(); c != -1; c = zis.read()) { + fout.write(c); + } + fout.close(); + } + zis.closeEntry(); + } + 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; + + if (!jsPlugins.exists()){ + logger.info('Directory ' + jsPlugins.canonicalPath + ' does not exist.'); + logger.info('Initializing ' + jsPlugins.canonicalPath + ' directory with contents from plugin archive.'); + jsPlugins.mkdirs(); + } + + for (i = 0; i < len;i++){ + cfgName = 'extract-js.' + zips[i]; + if (cfg.getBoolean(cfgName)){ + unzip( zips[i] + '.zip',logger,plugin); + } + } + plugin.saveDefaultConfig(); - __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; - - if (!jsPlugins.exists()){ - logger.info('Directory ' + jsPlugins.canonicalPath + ' does not exist.'); - logger.info('Initializing ' + jsPlugins.canonicalPath + ' directory with contents from plugin archive.'); - jsPlugins.mkdirs(); - } - - for (i = 0; i < len;i++){ - cfgName = 'extract-js.' + zips[i]; - if (cfg.getBoolean(cfgName)){ - unzip( zips[i] + '.zip',logger,plugin); - } - } - plugin.saveDefaultConfig(); - - engine.eval(new FileReader(initScriptFile)); - __onEnable(engine, plugin, initScriptFile); - }; + engine.eval(new FileReader(initScriptFile)); + __onEnable(engine, plugin, initScriptFile); + }; })();