Added items to API docs, added recipes. added utils.players() and utils.playerNames() functions.

This commit is contained in:
walterhiggins 2014-10-05 17:29:04 +01:00
parent b091c33fbf
commit 70282e278d
10 changed files with 1624 additions and 1279 deletions

View file

@ -53,9 +53,21 @@
<arg value="src/docs/js/generateApiDocs.js"/>
<arg value="${dist}/js"/>
</java>
<java classname="jscript" failonerror="true" fork="true" output="${dist}/items.md" error="${dist}/genitemserror.log">
<classpath>
<pathelement path="${build}"/>
<pathelement path="lib/canary.jar"/>
</classpath>
<arg value="src/docs/js/generateItemsDoc.js"/>
</java>
<concat destfile="${dist}/apiref-con.md">
<fileset file="${dist}/apiref.md" />
<fileset file="${dist}/items.md" />
</concat>
</target>
<target name="gen-events-helper-canary" depends="compile-docs,init">
<mkdir dir="${dist}/js/lib"/>
<java classname="jscript" failonerror="true" fork="true" output="${dist}/js/lib/events-helper.js" error="${dist}/geneventserror.log">
@ -99,7 +111,7 @@ Walter Higgins
</header>
<fileset file="${dist}/toc-apiref.md" />
<fileset file="${dist}/apiref.md" />
<fileset file="${dist}/apiref-con.md" />
</concat>
</target>
@ -109,7 +121,7 @@ Walter Higgins
<pathelement path="${build}"/>
</classpath>
<arg value="src/docs/js/generateTOC.js"/>
<arg value="${dist}/apiref.md"/>
<arg value="${dist}/apiref-con.md"/>
</java>
</target>

File diff suppressed because it is too large Load diff

View file

@ -1,135 +1,138 @@
/*
This script is run at build time to generate api.md - a single Markdown document containing documentation for ScriptCraft's API
*/
This script is run at build time to generate api.md - a single Markdown document containing documentation for ScriptCraft's API
*/
function foreach(array, func){
for (var i =0; i < array.length; i++){
func(array[i],i,array);
}
}
/*
find - a (very) basic implementation of the unix command line tool.
*/
function find(dir,store,re) {
var files = dir.listFiles();
foreach (files, function(filename){
filename = "" + filename;
var file = new File(filename);
if (file.isDirectory()) {
find(file,store,re);
} else {
if (typeof re == "undefined")
store.push(filename);
else if (filename.match(re))
store.push(filename);
}
});
}
/*
the main module file for a given directory
(assuming the main module is in a file with the same name as the parent
directory) - e.g. drone/drone.js
*/
function sorter( precedence ){
return function(a,b)
{
// convert from Java string to JS string
a = '' + a;
b = '' + b;
var aparts = a.split(/\//);
var bparts = b.split(/\//);
var adir = aparts.slice(3,aparts.length-1).join('/');
var afile = aparts[aparts.length-1];
var bdir = bparts.slice(3,bparts.length-1).join('/');
var bfile = bparts[bparts.length-1];
for (var i = 0;i < precedence.length; i++){
var re = precedence[i];
if (a.match(re) && b.match(re)){
if (afile < bfile)
return -1;
if (afile > bfile)
return 1;
}
if (a.match(re))
return -1;
if (b.match(re))
return 1;
}
if(adir<bdir) return -1;
if(adir>bdir) return 1;
afile = afile.replace(/\.js$/,'');
if (afile == adir){
return -1;
}
else {
var result = 0;
if (afile < bfile){
result = -1;
}
if (afile > bfile){
result = 1;
}
//err.println("afile: " + afile + ", bfile:" + bfile + ",result=" + result);
return result;
}
};
}
function sortByModule(a,b)
{
var aparts = (''+a).split(/\//);
var bparts = (''+b).split(/\//);
var adir = aparts[aparts.length-2];
var afile = aparts[aparts.length-1];
var bdir = bparts[bparts.length-2];
var bfile = bparts[bparts.length-1];
if (afile == '_scriptcraft.js')
return -1;
if (bfile == '_scriptcraft.js')
return 1;
if(adir<bdir) return -1;
if(adir>bdir) return 1;
if (afile.indexOf(adir) == 0)
return -1;
else
return 1;
}
var err = java.lang.System.err;
args = Array.prototype.slice.call(args,1);
if (typeof importPackage == 'undefined'){
// load compatibility script
load('nashorn:mozilla_compat.js');
// load compatibility script
load('nashorn:mozilla_compat.js');
}
var dir = args[0];
var foreach = function(array, func){
for (var i =0; i < array.length; i++){
func(array[i],i,array);
}
};
importPackage(java.io);
/*
find - a (very) basic implementation of the unix command line tool.
*/
var find = function(dir,store,re)
{
var files = dir.listFiles();
foreach (files, function(filename){
filename = "" + filename;
var file = new File(filename);
if (file.isDirectory()) {
find(file,store,re);
} else {
if (typeof re == "undefined")
store.push(filename);
else if (filename.match(re))
store.push(filename);
}
});
};
/*
the main module file for a given directory
(assuming the main module is in a file with the same name as the parent
directory) - e.g. drone/drone.js
*/
var sorter = function( precedence ){
return function(a,b)
{
// convert from Java string to JS string
a = '' + a;
b = '' + b;
var aparts = a.split(/\//);
var bparts = b.split(/\//);
var adir = aparts.slice(3,aparts.length-1).join('/');
var afile = aparts[aparts.length-1];
var bdir = bparts.slice(3,bparts.length-1).join('/');
var bfile = bparts[bparts.length-1];
for (var i = 0;i < precedence.length; i++){
var re = precedence[i];
if (a.match(re) && b.match(re)){
if (afile < bfile)
return -1;
if (afile > bfile)
return 1;
}
if (a.match(re))
return -1;
if (b.match(re))
return 1;
}
if(adir<bdir) return -1;
if(adir>bdir) return 1;
afile = afile.replace(/\.js$/,'');
if (afile == adir){
return -1;
}
else {
var result = 0;
if (afile < bfile){
result = -1;
}
if (afile > bfile){
result = 1;
}
//err.println("afile: " + afile + ", bfile:" + bfile + ",result=" + result);
return result;
}
};
};
var sortByModule = function(a,b)
{
var aparts = (''+a).split(/\//);
var bparts = (''+b).split(/\//);
var adir = aparts[aparts.length-2];
var afile = aparts[aparts.length-1];
var bdir = bparts[bparts.length-2];
var bfile = bparts[bparts.length-1];
if (afile == '_scriptcraft.js')
return -1;
if (bfile == '_scriptcraft.js')
return 1;
if(adir<bdir) return -1;
if(adir>bdir) return 1;
if (afile.indexOf(adir) == 0)
return -1;
else
return 1;
};
var store = [];
find(new File(dir),store,/\/[a-zA-Z0-9_\-]+\.js$/);
store.sort(sorter([
/lib\/scriptcraft\.js$/,
/lib\/require\.js$/,
/lib\/plugin\.js$/,
/lib\/events\.js$/,
/lib\//,
/modules\//,
/drone\.js/,
/drone\//,
/examples\//
/lib\/scriptcraft\.js$/,
/lib\/require\.js$/,
/lib\/plugin\.js$/,
/lib\/events\.js$/,
/lib\//,
/modules\//,
/drone\.js/,
/drone\//,
/examples\//
]));
//err.println("store=" + JSON.stringify(store));
var contents = [];
foreach(store, function(filename){
var br = new BufferedReader(new FileReader(filename));
var line ;
while ( (line = br.readLine()) != null){
contents.push(line);
}
br.close();
var br = new BufferedReader(new FileReader(filename));
var line ;
while ( (line = br.readLine()) != null){
contents.push(line);
}
br.close();
});
var len = contents.length;
@ -138,16 +141,16 @@ var startComment = /^\/\*{10}/;
var endComment = /^\*{3}\//;
for (var i = 0;i < contents.length; i++){
var line = contents[i];
if (line.match(startComment)){
writeComment = true;
i++;
}
if (line.match(endComment)){
writeComment = false;
}
if (writeComment){
java.lang.System.out.println(contents[i]);
}
var line = contents[i];
if (line.match(startComment)){
writeComment = true;
i++;
}
if (line.match(endComment)){
writeComment = false;
}
if (writeComment){
java.lang.System.out.println(contents[i]);
}
}

View file

@ -0,0 +1,45 @@
args = Array.prototype.slice.call(args,1);
// [0] = type, [1] = lib.jar [2] = blockX, [3] = classX
var out = java.lang.System.out,
err = java.lang.System.err,
entry = null;
var content = [
'/*********************',
'## Items module',
'The Items module provides a suite of functions - one for each possible item.',
'See https://ci.visualillusionsent.net/job/CanaryLib/javadoc/net/canarymod/api/inventory/ItemType.html for a list of possible items',
'',
'### Usage',
'',
' items.book(); // returns net.canarymod.api.inventory.ItemType.Book',
' items.book(2); // returns a new net.canarymod.api.inventory.Item object with an amount 2 (2 books)',
' items.book( itemType ); // compares itemType parameter to ItemType.Book or an Item of type book',
'',
'The following functions are provided:',
''
];
//var ItemType = java.lang.Class.forName('net.canarymod.api.inventory.ItemType');
var ItemType = Packages.net.canarymod.api.inventory.ItemType;
var materials = ItemType.class.getDeclaredFields();
var enumVals = [];
for (var i = 0;i < materials.length; i++ ){
if (materials[i].type != ItemType.class) {
continue;
}
var materialField = materials[i];
var name = (''+materialField.name).replace(/^(.)/,function(a){ return a.toLowerCase() });
enumVals.push(' * ' + name + '()');
}
enumVals.sort();
content = content.concat(enumVals);
content.push('');
content.push('***/');
for (var i = 0; i< content.length; i++){
out.println(content[i]);
}

View file

@ -16,21 +16,24 @@ import net.canarymod.commandsys.Command;
import net.canarymod.commandsys.TabComplete;
import net.canarymod.chat.MessageReceiver;
import net.canarymod.Canary;
import net.canarymod.api.inventory.recipes.CraftingRecipe;
import net.canarymod.api.inventory.recipes.RecipeRow;
import net.canarymod.api.inventory.Item;
public class ScriptCraftPlugin extends Plugin implements PluginListener, CommandListener
{
public boolean canary = true;
public boolean bukkit = false;
private String NO_JAVASCRIPT_MESSAGE = "No JavaScript Engine available. " +
"ScriptCraft will not work without Javascript.";
"ScriptCraft will not work without Javascript.";
protected ScriptEngine engine = null;
@Override
public void disable(){
try {
((Invocable)this.engine).invokeFunction("__onDisable", this.engine, this);
}catch ( Exception e) {
this.getLogman().error(e.getMessage());
}
try {
((Invocable)this.engine).invokeFunction("__onDisable", this.engine, this);
}catch ( Exception e) {
this.getLogman().error(e.getMessage());
}
}
@Override
public boolean enable()
@ -38,50 +41,57 @@ public class ScriptCraftPlugin extends Plugin implements PluginListener, Command
try{
ScriptEngineManager factory = new ScriptEngineManager();
this.engine = factory.getEngineByName("JavaScript");
if (this.engine == null){
this.getLogman().error(NO_JAVASCRIPT_MESSAGE);
} else {
Invocable inv = (Invocable)this.engine;
//File f = new File(this.getJarPath());
InputStreamReader reader = new InputStreamReader(getClass()
.getClassLoader()
.getResourceAsStream("boot.js"));
this.engine.eval(reader);
inv.invokeFunction("__scboot", this, engine, getClass().getClassLoader());
}
if (this.engine == null){
this.getLogman().error(NO_JAVASCRIPT_MESSAGE);
} else {
Invocable inv = (Invocable)this.engine;
//File f = new File(this.getJarPath());
InputStreamReader reader = new InputStreamReader(getClass()
.getClassLoader()
.getResourceAsStream("boot.js"));
this.engine.eval(reader);
inv.invokeFunction("__scboot", this, engine, getClass().getClassLoader());
}
Canary.commands().registerCommands(this, this, false);
Canary.commands().registerCommands(this, this, false);
}catch(Exception e){
e.printStackTrace();
this.getLogman().error(e.getMessage());
}
return true;
return true;
}
public CraftingRecipe makeShapedRecipe(Item resultingItem, RecipeRow... rows){
CraftingRecipe result = new CraftingRecipe(resultingItem, rows);
return result;
}
public CraftingRecipe makeShapelessRecipe(Item resultingItem, Item... items){
CraftingRecipe result = new CraftingRecipe(resultingItem, items);
return result;
}
static class ScriptCraftTask extends ServerTask {
private Runnable runnable = null;
public ScriptCraftTask(Runnable runnable, TaskOwner owner, long delay, boolean continuous){
super(owner, delay, continuous);
this.runnable = runnable;
}
@Override
public void run(){
this.runnable.run();
}
private Runnable runnable = null;
public ScriptCraftTask(Runnable runnable, TaskOwner owner, long delay, boolean continuous){
super(owner, delay, continuous);
this.runnable = runnable;
}
@Override
public void run(){
this.runnable.run();
}
}
public ServerTask createServerTask(Runnable runnable, long delay, boolean continuous){
return new ScriptCraftTask(runnable, this, delay, continuous);
return new ScriptCraftTask(runnable, this, delay, continuous);
}
private void executeCommand( MessageReceiver sender, String[] args) {
boolean result = false;
String javascriptCode = "";
Object jsResult = null;
if (this.engine == null){
this.getLogman().error(NO_JAVASCRIPT_MESSAGE);
return;
}
if (this.engine == null){
this.getLogman().error(NO_JAVASCRIPT_MESSAGE);
return;
}
try {
jsResult = ((Invocable)this.engine).invokeFunction("__onCommand", sender, args);
}catch (Exception se){
@ -95,34 +105,34 @@ public class ScriptCraftPlugin extends Plugin implements PluginListener, Command
return;
}
@Command(
aliases = { "js" },
description = "Execute Javascript code",
permissions = { "canary.super.js", "canary.command.super.js" },
toolTip = "/js javascript expression")
public void jsCommand(MessageReceiver sender, String[] args) {
aliases = { "js" },
description = "Execute Javascript code",
permissions = { "scriptcraft.evaluate", "*" },
toolTip = "/js javascript expression")
public void jsCommand(MessageReceiver sender, String[] args) {
executeCommand(sender, args);
executeCommand(sender, args);
}
/*
groupmod permission add visitors canary.jsp
groupmod permission add visitors canary.command.jsp
*/
@Command(
aliases = { "jsp" },
description = "Run javascript-provided command",
permissions = { "canary.jsp", "canary.command.jsp" },
toolTip = "/jsp command")
public void jspCommand(MessageReceiver sender, String[] args) {
aliases = { "jsp" },
description = "Run javascript-provided command",
permissions = { "" },
toolTip = "/jsp command")
public void jspCommand(MessageReceiver sender, String[] args) {
executeCommand(sender, args);
executeCommand(sender, args);
}
private List<String> complete(MessageReceiver sender, String[] args, String cmd){
List<String> result = new ArrayList<String>();
if (this.engine == null){
this.getLogman().error(NO_JAVASCRIPT_MESSAGE);
return null;
}
if (this.engine == null){
this.getLogman().error(NO_JAVASCRIPT_MESSAGE);
return null;
}
try {
Invocable inv = (Invocable)this.engine;
inv.invokeFunction("__onTabComplete", result, sender, args, cmd);
@ -134,10 +144,10 @@ public class ScriptCraftPlugin extends Plugin implements PluginListener, Command
}
@TabComplete (commands = { "js" })
public List<String> jsComplete(MessageReceiver sender, String[] args){
return complete(sender, args, "js");
return complete(sender, args, "js");
}
@TabComplete (commands = { "jsp" })
public List<String> jspComplete(MessageReceiver sender, String[] args){
return complete(sender, args, "jsp");
return complete(sender, args, "jsp");
}
}

View file

@ -678,7 +678,7 @@ function __onEnable ( __engine, __plugin, __script ) {
configFile = new File(configFile,'global-config.json');
var config = _load( configFile );
if ( !config ) {
config = { verbose: true };
config = { verbose: false };
}
global.config = config;
global.__plugin = __plugin;

View file

@ -0,0 +1,15 @@
var items = require('items');
var bkShapedRecipe = org.bukkit.inventory.ShapedRecipe;
exports.add = function( recipe ){
var result = new bkShapedRecipe( recipe.result );
result.shape( recipe.shape );
for (var i in recipe.ingredients ){
result.setIngredient( i, recipe.ingredients[i] );
}
server.addRecipe(result);
return result;
};
exports.remove = function( recipe ) {
server.removeRecipe(recipe);
};

View file

@ -0,0 +1,36 @@
var cm = Packages.net.canarymod;
var cmRecipe = cm.api.inventory.recipes.CraftingRecipe;
var cmRecipeRow = cm.api.inventory.recipes.RecipeRow;
function addRecipe( recipe ){
if (!recipe){
return null;
}
var result,
rows,
i,j,
cells,
rr;
if (recipe.shape){
rows = [];
for (i = 0; i < recipe.shape.length; i++){
cells = recipe.shape[i].split('');
rr = [];
for ( j = 0; j < cells.length ; j++){
if (cells[j] != ' '){
rr.push(recipe.ingredients[cells[j]]);
}
}
rows.push( new cmRecipeRow(recipe.shape[i], rr) );
}
result = __plugin.makeShapedRecipe( recipe.result, rows);
} else {
result = __plugin.makeShapelessRecipe( recipe.result, recipe.ingredients );
}
return result;
}
function removeRecipe( recipe ){
server.removeRecipe( recipe );
}
exports.add = addRecipe;
exports.remove = removeRecipe;

View file

@ -0,0 +1,32 @@
/*************************************************************************
## The recipes module
The Recipes module provides convenience functions for adding and removing recipes
from the game.
### Example
To add an EnderBow to the game (assumes there's an enchanted Item variable called enderBow)...
var recipes = require('recipes');
var items = require('items');
...
var enderBowRecipe = recipes.add( {
result: enderBow,
ingredients: {
E: items.enderPearl(1),
S: items.stick(1),
W: items.string(1)
},
shape: [ 'ESW',
'SEW',
'ESW' ]
} );
// to remove...
recipes.remove( enderBowRecipe );
***/
if (__plugin.canary) {
module.exports = require('./canary/recipes');
} else {
module.exports = require('./bukkit/recipes');
}

View file

@ -746,6 +746,16 @@ exports.array = function( ){
}
return result;
};
/*************************************************************************
### utils.players() function
This function returns a javascript array of all online players on the server.
### utils.playerNames() function
This function returns a javascript array of player names (as javascript strings)
***/
function getPlayersBukkit(){
var result = [];
for (var i = 0; i < server.onlinePlayers.length; i++){
@ -761,6 +771,13 @@ function getPlayersCanary(){
}
return result;
}
var getPlayers = null;
if (__plugin.canary) {
getPlayers = getPlayersCanary;
} else {
getPlayers = getPlayersBukkit;
}
function getStatBukkit(player, stat){
return player.getStatistic(org.bukkit.Statistic[stat.toUpperCase()]);
}
@ -768,7 +785,12 @@ function getStatCanary(player, stat){
var cmStatistics = Packages.net.canarymod.api.statistics.Statistics;
return player.getStat(cmStatistics[stat.toUpperCase()].instance);
}
exports.players = __plugin.canary ? getPlayersCanary: getPlayersBukkit;
function getPlayerNames(){
return getPlayers().map(function(p){ return p.name; });
}
exports.players = getPlayers;
exports.playerNames = getPlayerNames;
/*************************************************************************
### utils.stat() function