Scripting in Java Games

Having a scripting engine can be invaluable to a game developer but developing one is complex quite time consuming. I have seen various scripting language implementations (including Lisp :) ), everybody seems to forget that Java comes with a perfectly good JavaScript engine ( Rhino) that can be embedded into your game with very few lines of code.

ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("JavaScript");
//add any variables that you want accessible from the scripting engine
scriptEngine.put("gameWorld", this);

There are many uses to scripting, often games keep the entity logic in scripts that get called from the game loop. I use the scripting mostly to tweak and tune Box2D related variables without having to go through the edit/compile/restart cycle.

Here is a little example to give you an idea.

gameWorld.pause()
boidsIt = gameWorld.boids.iterator();
while(boidsIt.hasNext()) {
boid = boidsIt.next();
boid.body.setLinearDamping(10);
boid.body.setAngularDamping(20);
}
gameWorld.resume()

I added a simple interactive editor/console and here how a dev session for my Astroboids game looks like. And yes, I made some progress with my game, this is an actual screen shot of the game running.

And a side note, there are other scripting engines available (BeanShell, Groovy, etc), but they require additional jars, the JavaScript Rhino engine comes bundled with Java 6.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>