Subj : Re: Javascript for scripting a computer game To : smileyhamster From : Igor Bukanov Date : Thu Nov 18 2004 08:32 pm S wrote: .... > What is the best way to implement this? What is the definition of "best"? Best in memory usage/speed/programming simplicity/maintenance easiness? > > I have a prototype working which uses the new and experimental > continuations feature of Rhino. When moveUp() is called, the Java code > to move the entity is called, the script state is saved, then the > Javascript throws an exception which is caught by the game so that the > script ends. The previous state is then reloaded in the next turn. > Using continuations means I have to use interpreted Javascript though. > Is there a better way to do this? For example, when the move function > of the Java object is called, can I call a method on the Context > object which will make the current executing statement return, while > also being resumable? It is not supported directly but if you use continuations and moveUp is JS function, then you can program it like: function moveUp() { // call java code to do things before next move ... waitMove(); // resume point } var escape = new Continuation(); function waitMove() { var returnState = new Continuation(); escape(returnState); } where "escape(returnState)" will return the control to the parent stack frame at the point of "escape" initialization, but since "escape = new Continuation()" is at top level script, then there is no parent and the control will be transfered back to Java code. That Java code can use the resulting object "returnState" to transfer control later to the parent frame of waitMove at "resume point" line. I.e. something like this: Context cx; .... Script script = cx.compileScript(...) Object result = script.eval(cx, scope); for (;;) { if (!result instanceof Function) { break; } Function f = (Function)result; if (!f.getClassName("Continuation")) { break; } // At this point f is "returnState" object // do the move action ... // transfer control back to script result = f.call(cx, scope, scope, Context.emptyArgs); } > > Also, each script can be assigned to multiple entities. For example, > the player entity could create a entity each turn and attach a bullet > script to it (to shoot at things). How can I do this using the least > resources in a fast way? My prototype runs very slowly when I create > new entities on the board but is fast when nothing is being created. > Each time a new bullet entity is made, it runs code like this: See http://www.mozilla.org/rhino/scopes.html and pay attention to the shared scope section. Regards, Igor .