This commit is contained in:
walterhiggins 2013-12-24 00:17:33 +00:00
parent aa93491a6c
commit d0da034fb7
5 changed files with 356 additions and 330 deletions

View file

@ -15,7 +15,7 @@ Example....
... creates a single firework, while .... ... creates a single firework, while ....
/js firework.fwd(3).times(5) /js firework().fwd(3).times(5)
... creates 5 fireworks in a row. Fireworks have also been added as a ... creates 5 fireworks in a row. Fireworks have also been added as a
possible option for the `arrow` module. To have a firework launch possible option for the `arrow` module. To have a firework launch
@ -26,16 +26,17 @@ where an arrow strikes...
To call the fireworks.firework() function directly, you must provide a To call the fireworks.firework() function directly, you must provide a
location. For example... location. For example...
/js var fireworks = require('fireworks');
/js fireworks.firework(self.location); /js fireworks.firework(self.location);
![firework example](img/firework.png) ![firework example](img/firework.png)
***/ ***/
plugin("fireworks", {
/* /*
create a firework at the given location create a firework at the given location
*/ */
firework: function(location){ var firework = function(location){
importPackage(org.bukkit.entity); importPackage(org.bukkit.entity);
importPackage(org.bukkit); importPackage(org.bukkit);
@ -72,9 +73,7 @@ plugin("fireworks", {
fwm.addEffect(effect); fwm.addEffect(effect);
fwm.setPower(randInt(2)+1); fwm.setPower(randInt(2)+1);
fw.setFireworkMeta(fwm); fw.setFireworkMeta(fwm);
} };
});
Drone.extend('firework',function() exports.firework = firework;
{
fireworks.firework(this.getLocation());
});

View file

@ -25,12 +25,14 @@ Example
The following example illustrates how to use http.request to make a request to a JSON web service and evaluate its response... The following example illustrates how to use http.request to make a request to a JSON web service and evaluate its response...
var jsResponse; var jsResponse;
var http = require('./http/request');
http.request("http://scriptcraftjs.org/sample.json",function(responseCode, responseBody){ http.request("http://scriptcraftjs.org/sample.json",function(responseCode, responseBody){
jsResponse = eval("(" + responseBody + ")"); jsResponse = eval("(" + responseBody + ")");
}); });
... The following example illustrates a more complex use-case POSTing parameters to a CGI process on a server... ... The following example illustrates a more complex use-case POSTing parameters to a CGI process on a server...
var http = require('./http/request');
http.request({ url: "http://pixenate.com/pixenate/pxn8.pl", http.request({ url: "http://pixenate.com/pixenate/pxn8.pl",
method: "POST", method: "POST",
params: {script: "[]"} params: {script: "[]"}
@ -39,9 +41,7 @@ The following example illustrates how to use http.request to make a request to a
}); });
***/ ***/
var http = http ? http : {}; exports.request = function( request, callback)
http.request = function( request, callback)
{ {
var paramsToString = function(params){ var paramsToString = function(params){
var result = ""; var result = "";

View file

@ -1,9 +1,12 @@
var _utils = require('utils');
var stringExt = require('utils/string-exts');
var events = require('events');
/* /*
Define the signs module - signs are persistent Define the signs module - signs are persistent
(that is - a menu sign will still be a menu after th (that is - a menu sign will still be a menu after the
server has shut down and started up) plugins now have persistent state - Yay! server has shut down and started up) plugins now have persistent state - Yay!
*/ */
var signs = signs || plugin("signs", { 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.
*/ */
@ -12,19 +15,15 @@ var signs = signs || plugin("signs", {
/* Array */ options, /* Array */ options,
/* Function */ onInteract, /* Function */ onInteract,
/* Number */ defaultSelection ){} /* Number */ defaultSelection ){}
/*
more to come - clocks
*/
},true); },true);
module.exports = signs;
/* /*
private implementation
*/
(function(){
/*
redraw a menu sign redraw a menu sign
*/ */
var _redrawMenuSign = function(p_sign,p_selectedIndex,p_displayOptions) var _redrawMenuSign = function(p_sign,p_selectedIndex,p_displayOptions)
{ {
var optLen = p_displayOptions.length; var optLen = p_displayOptions.length;
// the offset is where the menu window begins // the offset is where the menu window begins
var offset = Math.max(0, Math.min(optLen-3, Math.floor(p_selectedIndex/3) * 3)); var offset = Math.max(0, Math.min(optLen-3, Math.floor(p_selectedIndex/3) * 3));
@ -37,19 +36,20 @@ var signs = signs || plugin("signs", {
p_sign.setLine(i+1,text); p_sign.setLine(i+1,text);
} }
p_sign.update(true); p_sign.update(true);
}; };
signs._updaters = {}; var _updaters = {};
var _store = {};
/* signs.store = _store;
/*
construct an interactive menu to be subsequently attached to construct an interactive menu to be subsequently attached to
one or more Signs. one or more Signs.
*/ */
signs.menu = function( signs.menu = function(
/* String */ label, /* String */ label,
/* Array */ options, /* Array */ options,
/* Function */ callback, /* Function */ callback,
/* Number */ selectedIndex) /* Number */ selectedIndex)
{ {
if (typeof selectedIndex == "undefined") if (typeof selectedIndex == "undefined")
selectedIndex = 0; selectedIndex = 0;
@ -66,9 +66,6 @@ var signs = signs || plugin("signs", {
for (var i =0;i < options.length;i++){ for (var i =0;i < options.length;i++){
displayOptions[i] = (" " + options[i] + optionPadding).substring(0,15); displayOptions[i] = (" " + options[i] + optionPadding).substring(0,15);
} }
var theSigns = this;
/* /*
this function is returned by signs.menu and when it is invoked it will this function is returned by signs.menu and when it is invoked it will
attach menu behaviour to an existing sign in the world. attach menu behaviour to an existing sign in the world.
@ -81,7 +78,7 @@ var signs = signs || plugin("signs", {
save = true; save = true;
if (typeof sign == "undefined"){ if (typeof sign == "undefined"){
var mouseLoc = getMousePos(); var mouseLoc = _utils.getMousePos();
if (mouseLoc){ if (mouseLoc){
sign = mouseLoc.block.state; sign = mouseLoc.block.state;
}else{ }else{
@ -113,7 +110,7 @@ var signs = signs || plugin("signs", {
/* /*
keep a reference to the update function for use by the event handler keep a reference to the update function for use by the event handler
*/ */
theSigns._updaters[menuSignUID] = _updateSign; _updaters[menuSignUID] = _updateSign;
// initialize the sign // initialize the sign
_redrawMenuSign(sign,cSelectedIndex,displayOptions); _redrawMenuSign(sign,cSelectedIndex,displayOptions);
@ -125,11 +122,11 @@ var signs = signs || plugin("signs", {
when the server starts up again. when the server starts up again.
*/ */
if (save){ if (save){
if (typeof theSigns.store.menus == "undefined") if (typeof _store.menus == "undefined")
theSigns.store.menus = {}; _store.menus = {};
var signLocations = theSigns.store.menus[label]; var signLocations = _store.menus[label];
if (typeof signLocations == "undefined") if (typeof signLocations == "undefined")
signLocations = theSigns.store.menus[label] = []; signLocations = _store.menus[label] = [];
signLocations.push(menuSignSaveData); signLocations.push(menuSignSaveData);
} }
return sign; return sign;
@ -142,9 +139,9 @@ var signs = signs || plugin("signs", {
world with this same label and make dynamic again. world with this same label and make dynamic again.
*/ */
if (this.store.menus && this.store.menus[label]) if (_store.menus && _store.menus[label])
{ {
var signsOfSameLabel = this.store.menus[label]; var signsOfSameLabel = _store.menus[label];
var defragged = []; var defragged = [];
var len = signsOfSameLabel.length; var len = signsOfSameLabel.length;
for (var i = 0; i < len ; i++) for (var i = 0; i < len ; i++)
@ -163,43 +160,16 @@ var signs = signs || plugin("signs", {
remove data for signs which no longer exist. remove data for signs which no longer exist.
*/ */
if (defragged.length != len){ if (defragged.length != len){
this.store.menus[label] = defragged; _store.menus[label] = defragged;
} }
} }
return convertToMenuSign; return convertToMenuSign;
}; };
/* //
All dependecies ( 'events' module ) have loaded // update it every time player interacts with it.
*/ //
ready(function(){ events.on("player.PlayerInteractEvent",function(listener, event) {
//
// Usage:
// In game, create a sign , target it and type /js signs.testMenu()
//
signs.testMenu = signs.menu(
"Dinner",
["Lamb","Pork","Chicken","Duck","Beef"],
function(event){
event.player.sendMessage("You chose " + event.text);
});
//
// This is an example sign that displays a menu of times of day
// interacting with the sign will change the time of day accordingly.
//
// In game, create a sign , target it and type /js signs.timeOfDay()
//
signs.timeOfDay = signs.menu(
"Time",
["Dawn","Midday","Dusk","Midnight"],
function(event){
event.player.location.world.setTime( event.number * 6000 );
});
//
// 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 look up our list of menu signs. If there's a matching location and there's
a sign, then update it. a sign, then update it.
@ -207,12 +177,10 @@ var signs = signs || plugin("signs", {
if (! event.clickedBlock.state instanceof org.bukkit.block.Sign) if (! event.clickedBlock.state instanceof org.bukkit.block.Sign)
return; return;
var evtLocStr = utils.locationToString(event.clickedBlock.location); var evtLocStr = _utils.locationToString(event.clickedBlock.location);
var signUpdater = signs._updaters[evtLocStr] var signUpdater = _updaters[evtLocStr]
if (signUpdater) if (signUpdater)
signUpdater(event.player, event.clickedBlock.state); signUpdater(event.player, event.clickedBlock.state);
}); });
});
}());

View file

@ -41,9 +41,8 @@ Example
<p style="color:gold;font-weight:bold">Hello World</p> <p style="color:gold;font-weight:bold">Hello World</p>
***/ ***/
(function(){ var c = org.bukkit.ChatColor;
var c = org.bukkit.ChatColor; var formattingCodes = {
var formattingCodes = {
aqua: c.AQUA, aqua: c.AQUA,
black: c.BLACK, black: c.BLACK,
blue: c.BLUE, blue: c.BLUE,
@ -72,10 +71,9 @@ Example
magic: c.MAGIC, magic: c.MAGIC,
underline: c.UNDERLINE, underline: c.UNDERLINE,
reset: c.RESET reset: c.RESET
}; };
for (var method in formattingCodes){ for (var method in formattingCodes){
String.prototype[method] = function(c){ String.prototype[method] = function(c){
return function(){return c+this;}; return function(){return c+this;};
}(formattingCodes[method]); }(formattingCodes[method]);
} }
}());

View file

@ -8,21 +8,55 @@ Miscellaneous utility functions and classes to help with programming.
* getPlayerObject(playerName) - returns the Player object for a named * getPlayerObject(playerName) - returns the Player object for a named
player or `self` if no name is provided. player or `self` if no name is provided.
***/ * getPlayerPos(playerName) - returns the player's x,y,z and yaw (direction) for a named player
var utils = utils ? utils : { or player or `self` if no parameter is provided.
locationToString: function(location){
return JSON.stringify([""+location.world.name,location.x, location.y, location.z]);
},
getPlayerObject: function(playerName){ * getMousePos(playerName) - returns the x,y,z of the current block being targeted by the named player
if (typeof playerName == "undefined") or player or `self` if no paramter is provided.
***/
var _getPlayerObject = function ( playerName ) {
if (typeof playerName == "undefined"){
if (typeof self == "undefined"){
return null;
} else {
return self; return self;
}
} else {
if (typeof playerName == "string") if (typeof playerName == "string")
return org.bukkit.Bukkit.getPlayer(playerName); return org.bukkit.Bukkit.getPlayer(playerName);
return player; else
}, return playerName; // assumes it's a player object
}
};
exports.locationToString = function(location){
return JSON.stringify([""+location.world.name,location.x, location.y, location.z]);
};
exports.getPlayerObject = _getPlayerObject;
exports.getPlayerPos = function( player ) {
player = _getPlayerObject(player);
return player.location;
};
exports.getMousePos = function (player) {
player = _getPlayerObject(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 foreach() function
======================== ========================
The utils.foreach() function is a utility function for iterating over The utils.foreach() function is a utility function for iterating over
an array of objects (or a java.util.Collection of objects) and processing each object in turn. Where an array of objects (or a java.util.Collection of objects) and processing each object in turn. Where
@ -70,6 +104,7 @@ Example
------- -------
The following example illustrates how to use foreach for immediate processing of an array... The following example illustrates how to use foreach for immediate processing of an array...
var utils = require('./utils/_utils');
var players = ["moe", "larry", "curly"]; var players = ["moe", "larry", "curly"];
utils.foreach (players, function(item){ utils.foreach (players, function(item){
server.getPlayer(item).sendMessage("Hi " + item); server.getPlayer(item).sendMessage("Hi " + item);
@ -89,6 +124,7 @@ without hogging CPU usage...
// build a structure 200 wide x 200 tall x 200 long // build a structure 200 wide x 200 tall x 200 long
// (That's 8 Million Blocks - enough to tax any machine!) // (That's 8 Million Blocks - enough to tax any machine!)
var utils = require('./utils/_utils');
var a = []; var a = [];
a.length = 200; a.length = 200;
@ -106,7 +142,7 @@ without hogging CPU usage...
utils.foreach (a, processItem, null, 10, onDone); utils.foreach (a, processItem, null, 10, onDone);
***/ ***/
foreach: function(array, callback, object, delay, onCompletion) { var _foreach = function(array, callback, object, delay, onCompletion) {
if (array instanceof java.util.Collection) if (array instanceof java.util.Collection)
array = array.toArray(); array = array.toArray();
var i = 0; var i = 0;
@ -120,7 +156,8 @@ without hogging CPU usage...
callback(array[i],i,object,array); callback(array[i],i,object,array);
} }
} }
}, };
exports.foreach = _foreach;
/************************************************************************ /************************************************************************
utils.nicely() function utils.nicely() function
======================= =======================
@ -147,7 +184,7 @@ Example
See the source code to utils.foreach for an example of how utils.nicely is used. See the source code to utils.foreach for an example of how utils.nicely is used.
***/ ***/
nicely: function(next, hasNext, onDone, delay){ exports.nicely = function(next, hasNext, onDone, delay){
if (hasNext()){ if (hasNext()){
next(); next();
server.scheduler.runTaskLater(__plugin,function(){ server.scheduler.runTaskLater(__plugin,function(){
@ -157,7 +194,7 @@ See the source code to utils.foreach for an example of how utils.nicely is used.
if (onDone) if (onDone)
onDone(); onDone();
} }
}, };
/************************************************************************ /************************************************************************
utils.at() function utils.at() function
=================== ===================
@ -177,6 +214,8 @@ Example
To warn players when night is approaching... To warn players when night is approaching...
var utils = require('./utils/_utils');
utils.at( "19:00", function() { utils.at( "19:00", function() {
utils.foreach( server.onlinePlayers, function(player){ utils.foreach( server.onlinePlayers, function(player){
@ -186,7 +225,7 @@ To warn players when night is approaching...
}, self.world); }, self.world);
***/ ***/
at: function(time24hr, callback, world){ exports.at = function(time24hr, callback, world) {
var forever = function(){ return true;}; var forever = function(){ return true;};
var timeParts = time24hr.split(":"); var timeParts = time24hr.split(":");
var hrs = ((timeParts[0] * 1000) + 18000) % 24000; var hrs = ((timeParts[0] * 1000) + 18000) % 24000;
@ -205,5 +244,27 @@ To warn players when night is approaching...
callback(); callback();
} }
},forever, null, 100); },forever, null, 100);
},
}; };
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);
}
});
}
recurse(dir,result);
return result;
}