6.游戏特别离不开脚本(3)-JS脚本操作java(2)(直接解析JS公式,并非完整JS文件或者函数)
在游戏中可以考虑数据由javabean保存,逻辑方法由JS提供。
public class Bean4JS { private int id; private String name; private int age; public Bean4JS(int id, String name, int age) { super(); this.id = id; this.name = name; this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public boolean isAdult() { if (this.age >= 18) { return true; } return false; } }
import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class JsUseBean { public static void main(String[] args) { Bean4JS bean = new Bean4JS(0, "adware", 19); ScriptEngineManager eManager = new ScriptEngineManager(); ScriptEngine engine = eManager.getEngineByName("JavaScript"); engine.put("bean", bean); try { //这种方式调用js属于直接解析js公式 System.out.println("he is adult?" + engine.eval(getIsAdultScript1())); System.out.println("he is adult?" + engine.eval(getIsAdultScript2())); //改变bean的某一个属性 engine.eval(getSetSmallerAgeScript()); System.out.println(bean.getAge()); System.out.println("he is adult?" + engine.eval(getIsAdultScript1())); } catch (ScriptException e) { e.printStackTrace(); } } private static String getIsAdultScript1() { return "var age = bean.getAge();" + "if(age >= 18){flag = true} else {flag = false}"; } private static String getIsAdultScript2() { //return "var flag = bean.isAdult();"; //这样是没有返回结果的 return "flag = bean.isAdult();"; } private static String getSetSmallerAgeScript() { return "bean.setAge(17)"; } }
运行结果:
he is adult?true he is adult?true 17 he is adult?false
理想要的效果又进一步了