Search code examples
scripting

How do I hook into a game and write a script to manipulate it?


I know this is a pretty open question but I was wondering how people go about writing scripts that will "play" a game, or manipulate it in some way. I had been thinking that I'd try to get a working AI to play a game for fun, but don't even really know where to start. Are there any good resources to learn this? What are good languages to use? Once I have the language, how do I get my script hooked into the game? I was thinking of just trying simple flash games, if that helps.

Thanks a bunch!


Solution

  • You can do this quite simply in Java 6.

    1. expose your objects/functions in your Java app into the scripting environment For example you can expose your character or the game world into the scripting environment and allow the script to control it.

    2. invoke script functions/methods from Java environment Allow the script to customize behaviours, add new actions, etc. Another use of this is to override the default build in game rules and load your own house rules. Another use is as a macro facility. Typically this would be part of the main game loop

    3. use the script as a data/level file For example, in a game likes SpaceHulk where it is mission based, you can use a script to define a game specific DSL, and us this DSL to define new missions. When the game starts up, it evaluates the data file and create a model of the game.

    To integrate a scripting engine into Java, simply do this

       ScriptEngineManager mgr = new ScriptEngineManager();
       ScriptEngine jsEngine = mgr.getEngineByExtension("js");
       jsEngine.eval("print('Hello world!');
    

    To expose an object into the script environment

       jsEngine.put("avatar", avatarObject);
       //An avatar object is now available in myscript.js
       jsEngine.eval(new FileReader("myscript.js");
    

    To invoke a function in the script

       jsEngine.eval("function hello(name) ... ");
       Invocable inv = (Invocable)jsEngine;
       inv.invokeFunction("hello", "Fred");
    

    One of the problem with scripting is that, the script has access to your entire application. You can restrict what the script can 'see' by setting a classloader when you create the ScriptEngineManager instance. Java 6 comes with a bundled JavaScript engine. However I prefer Groovy and loading Groovy basically mean changing 'js' in getEngineByExtension() to 'groovy'.

    I know that a lot of people say that Java is not fast for games, but if you are writing turn based games or social games like Farmville then I think it is more than adequate.

    For C/C++ based games, I think the preferred script engine is Lua. I've not used it so I cannot comment on it.