Category Archives: JavaScript

Simple JavaScript Console

Here are more details on the console thingy seen in my post about scripting, it’s nothing terribly special, just a simple UI with a few extras like redirecting System.out/err to the output area in the frame, download the code below and take a look.

Here is how you use it:

public class ConsoleDemo extends Scene2D {
private ImageSprite man, spirit;

@Override
public void load() {
add(new FilledSprite(Colors.WHITE));

man = new ImageSprite("Man.png", 10, 10);
add(man);
spirit = new ImageSprite("Spirit.png", 100, 10);
add(spirit);

ConsoleFrame consoleFrame = new ConsoleFrame();

ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
scriptEngine.put("demo", this);

consoleFrame.setScriptEngine(scriptEngine);
consoleFrame.setLocation(900, 200);
consoleFrame.setVisible(true);
}

public ImageSprite getMan() {
return man;
}

public void setMan(ImageSprite man) {
this.man = man;
}

public ImageSprite getSpirit() {
return spirit;
}

public void setSpirit(ImageSprite spirit) {
this.spirit = spirit;
}
}

Just make sure you instantiate the ConsoleFrame before the ScriptEngineManager or the System.out/err redirection will not work. Also, the example is PulpCore based but there is no PulpCore dependency in the ConsoleFrame code.

And now a trivial script:

demo.setPaused(true)
println(demo.man)
println(demo.man.x)
demo.man.x.set(200)
println(demo.man.x)
demo.setPaused(false)

Putting an instance in the scripting engine like this scriptEngine.put("demo", demoInstance) makes it available with that name, members that are public or have getters/setters are directly accessible from JavaScript.

And one somewhat important caveat, the Swing code runs in it’s own thread and so does the scripting engine, changing the game state from a script can lead to inconsistencies at times if your code is not thread safe (and likely it is not – usually games are coded single-threaded), to avoid problems first pause the game loop, run the script and make your changes and then resume the loop. For PulpCore you can do this by calling Scene2D.setPaused()

More details and documentation on scripting Java classes at http://www.mozilla.org/rhino/, especially this https://developer.mozilla.org/en/Scripting_Java

Download the source code.