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 ....
/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
possible option for the `arrow` module. To have a firework launch
@ -26,55 +26,54 @@ where an arrow strikes...
To call the fireworks.firework() function directly, you must provide a
location. For example...
/js var fireworks = require('fireworks');
/js fireworks.firework(self.location);
![firework example](img/firework.png)
***/
plugin("fireworks", {
/*
create a firework at the given location
*/
firework: function(location){
importPackage(org.bukkit.entity);
importPackage(org.bukkit);
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);
}
});
Drone.extend('firework',function()
{
fireworks.firework(this.getLocation());
});
/*
create a firework at the given location
*/
var firework = function(location){
importPackage(org.bukkit.entity);
importPackage(org.bukkit);
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;

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...
var jsResponse;
var http = require('./http/request');
http.request("http://scriptcraftjs.org/sample.json",function(responseCode, responseBody){
jsResponse = eval("(" + responseBody + ")");
});
... 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: "[]"}
@ -39,9 +41,7 @@ The following example illustrates how to use http.request to make a request to a
});
***/
var http = http ? http : {};
http.request = function( request, callback)
exports.request = function( request, callback)
{
var paramsToString = function(params){
var result = "";

View file

@ -1,218 +1,186 @@
var _utils = require('utils');
var stringExt = require('utils/string-exts');
var events = require('events');
/*
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!
*/
var signs = signs || plugin("signs", {
var signs = plugin("signs", {
/*
construct an interactive menu which can then be attached to a Sign.
*/
*/
menu: function(
/* String */ label,
/* Array */ options,
/* Function */ onInteract,
/* Number */ defaultSelection ){}
/*
more to come - clocks
*/
},true);
module.exports = signs;
/*
private implementation
redraw a menu sign
*/
(function(){
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);
}
p_sign.update(true);
};
var _updaters = {};
var _store = {};
signs.store = _store;
/*
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);
}
/*
redraw a menu sign
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 _redrawMenuSign = function(p_sign,p_selectedIndex,p_displayOptions)
var convertToMenuSign = function(/* Sign */ sign, save)
{
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);
}
p_sign.update(true);
};
signs._updaters = {};
if (typeof save == "undefined")
save = true;
/*
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);
}
var theSigns = this;
/*
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;
if (typeof sign == "undefined"){
var mouseLoc = getMousePos();
if (mouseLoc){
sign = mouseLoc.block.state;
}else{
throw new Exception("You must provide a sign!");
}
if (typeof sign == "undefined"){
var mouseLoc = _utils.getMousePos();
if (mouseLoc){
sign = mouseLoc.block.state;
}else{
throw new Exception("You must provide a sign!");
}
//
// 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 = [""+signLoc.world.name, signLoc.x,signLoc.y,signLoc.z];
var menuSignUID = JSON.stringify(menuSignSaveData);
/*
keep a reference to the update function for use by the event handler
*/
theSigns._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 theSigns.store.menus == "undefined")
theSigns.store.menus = {};
var signLocations = theSigns.store.menus[label];
if (typeof signLocations == "undefined")
signLocations = theSigns.store.menus[label] = [];
signLocations.push(menuSignSaveData);
}
return sign;
}
//
// 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 = [""+signLoc.world.name, signLoc.x,signLoc.y,signLoc.z];
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 (this.store.menus && this.store.menus[label])
{
var signsOfSameLabel = this.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[0]);
if (!world)
continue;
var block = world.getBlockAt(loc[1],loc[2],loc[3]);
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){
this.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;
};
/*
All dependecies ( 'events' module ) have loaded
*/
ready(function(){
//
// 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 );
});
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.
*/
//
// 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.
*/
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[0]);
if (!world)
continue;
var block = world.getBlockAt(loc[1],loc[2],loc[3]);
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;
};
if (! event.clickedBlock.state instanceof org.bukkit.block.Sign)
return;
var evtLocStr = utils.locationToString(event.clickedBlock.location);
var signUpdater = signs._updaters[evtLocStr]
if (signUpdater)
signUpdater(event.player, event.clickedBlock.state);
});
});
}());
//
// 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.
*/
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);
});

View file

@ -41,41 +41,39 @@ Example
<p style="color:gold;font-weight:bold">Hello World</p>
***/
(function(){
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,
green: c.GREEN,
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]);
}
}());
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,
green: c.GREEN,
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]);
}

View file

@ -8,21 +8,55 @@ Miscellaneous utility functions and classes to help with programming.
* getPlayerObject(playerName) - returns the Player object for a named
player or `self` if no name is provided.
***/
var utils = utils ? utils : {
locationToString: function(location){
return JSON.stringify([""+location.world.name,location.x, location.y, location.z]);
},
* getPlayerPos(playerName) - returns the player's x,y,z and yaw (direction) for a named player
or player or `self` if no parameter is provided.
* getMousePos(playerName) - returns the x,y,z of the current block being targeted by the named player
or player or `self` if no paramter is provided.
getPlayerObject: function(playerName){
if (typeof playerName == "undefined")
***/
var _getPlayerObject = 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);
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
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...
var utils = require('./utils/_utils');
var players = ["moe", "larry", "curly"];
utils.foreach (players, function(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
// (That's 8 Million Blocks - enough to tax any machine!)
var utils = require('./utils/_utils');
var a = [];
a.length = 200;
@ -106,21 +142,22 @@ without hogging CPU usage...
utils.foreach (a, processItem, null, 10, onDone);
***/
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;};
utils.nicely(next,hasNext,onCompletion,delay);
}else{
for (;i < len; i++){
callback(array[i],i,object,array);
}
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;};
utils.nicely(next,hasNext,onCompletion,delay);
}else{
for (;i < len; i++){
callback(array[i],i,object,array);
}
},
}
};
exports.foreach = _foreach;
/************************************************************************
utils.nicely() function
=======================
@ -147,17 +184,17 @@ Example
See the source code to utils.foreach for an example of how utils.nicely is used.
***/
nicely: function(next, hasNext, onDone, delay){
if (hasNext()){
next();
server.scheduler.runTaskLater(__plugin,function(){
utils.nicely(next,hasNext,onDone,delay);
},delay);
}else{
if (onDone)
onDone();
}
},
exports.nicely = function(next, hasNext, onDone, delay){
if (hasNext()){
next();
server.scheduler.runTaskLater(__plugin,function(){
utils.nicely(next,hasNext,onDone,delay);
},delay);
}else{
if (onDone)
onDone();
}
};
/************************************************************************
utils.at() function
===================
@ -177,6 +214,8 @@ Example
To warn players when night is approaching...
var utils = require('./utils/_utils');
utils.at( "19:00", function() {
utils.foreach( server.onlinePlayers, function(player){
@ -186,24 +225,46 @@ To warn players when night is approaching...
}, self.world);
***/
at: function(time24hr, callback, world){
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 world == "undefined"){
world = server.worlds.get(0);
exports.at = function(time24hr, callback, world) {
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 world == "undefined"){
world = server.worlds.get(0);
}
utils.nicely(function(){
var time = world.getTime();
var diff = timeMc - time;
if (diff > 0 && diff < 100){
callback();
}
utils.nicely(function(){
var time = world.getTime();
var diff = timeMc - time;
if (diff > 0 && diff < 100){
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;
}