package com.qiwu.chatbotbackend.gameDesign; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.entity.ConfigTermText; import com.qiwu.chatbotbackend.entity.Premise; import com.qiwu.chatbotbackend.entity.UserInfo; import java.io.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.qiwu.chatbotbackend.Config.Config.*; import static com.qiwu.chatbotbackend.actiongenerate.utils.ConfigTermUtils.textReplace; public class PlotConstructor2 extends ElementConstructor { JSONArray plots = null; HashMap> adjList = new HashMap>(); private HashMap plotIndex = new HashMap(); HashMap visited = new HashMap(); public HashMap getPlotIndex() { return plotIndex; } static Map replaceMap = new LinkedHashMap(){ { } }; public PlotConstructor2(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { super(); this.helper = helper; this.botId = botId; this.botAccount = botAccount; this.exceptRelation = exceptRelation; this.keywordMap = keywordMap; this.POS = POS; replaceMap.put("\r\n", ""); replaceMap.put("\n", ""); replaceMap.put("\t", ""); replaceMap.put("\\|", ""); replaceMap.put("~", "~"); } public void construct(JSONObject jsonObject, UserInfo userinfo) { try { addGameStartPlot(jsonObject, keywordMap); JSONArray plots = jsonObject.getJSONArray("plots"); String start = (String) jsonObject.get("start"), startCondition; JSONObject returnMessage = null; this.plots = plots; constructAdjList(plots); if (plotIndex.containsKey(start)) { //String taskLineName = "任务线_" + plotIndex.get(start).get("place") + "进度"; String taskLineName = String.format(TASK_LINE, plotIndex.get(start).get("place")); conditionDescription.put(taskLineName, taskLineName); if(jsonObject.get("firstUnknownText") == null) varInitialMap.put("unknownText", "你说啥?"); else varInitialMap.put("unknownText", (String)jsonObject.get("firstUnknownText")); varInitialMap.put("game_step", String.format(GAME_STEP_FORMAT, botAccount, (String) plotIndex.get(start).get("id"))); conditionDescription.put("unknownText", UNKNOWN_TEXT_DESCRIPTION); conditionDescription.put("game_step", GAME_STEP_DESCRIPTION); BFSGenerate4(plotIndex.get(start), userinfo, jsonObject); varInitialMap.put(start, "1"); ListeningConstructor.cc(botAccount, jsonObject, plotIndex, configTermTextList); } else { System.out.println(START_PLOT_NOT_EXIST); operationStatus = 0; message = START_PLOT_NOT_EXIST; return; } } catch(Exception e){ operationStatus = 0; message = PLOT_GENERATION_ERROR; e.printStackTrace(); return; } } /** * 根据id构造邻接表,将剧情数据变成树状结构 * @param plots */ public void constructAdjList(JSONArray plots) { int length = plots.size(), branchSize; String id = "", nextPlotId = "", nextPlotText; JSONObject plot = null; JSONArray branch = null; for (int i = 0; i < length; i++) { plot = plots.getJSONObject(i); id = (String) plot.get("id"); plot.put("index", i); if (adjList.get(id) == null) { adjList.put(id, new ArrayList<>()); } //如果npc是离线的,就过滤掉剧情文本中的变量槽 varSlotFilt(plot, keywordMap); //添加branch中的下一个plot branch = plot.getJSONArray("branch"); branchSize = branch.size(); for (int j = 0; j < branchSize; j++) { nextPlotId = (String) branch.getJSONObject(j).get("nextPlotId"); //过滤特殊字符 branch.getJSONObject(j).put("curPremise", premiseTextFilt(branch.getJSONObject(j).getJSONArray("curPremise"))); branch.getJSONObject(j).put("hisPremise", premiseTextFilt(branch.getJSONObject(j).getJSONArray("hisPremise"))); //将剧情和相应文本相对应 //plotTextIndex.put(nextPlotId, nextPlotText); //在邻接表中放入当前剧情的下一步剧情 adjList.get(id).add(nextPlotId); } //剧情文本特殊字符的过滤 plot.put("plotText", textReplace(plot.getString("plotText"), replaceMap)); plotIndex.put(id, plot); } } /** * 将条件文本中的一些特殊字符过滤调 * @param premiseList 条件列表 * @return */ JSONArray premiseTextFilt(JSONArray premiseList){ JSONObject premise = null; int size = premiseList.size(); for(int i = 0;i < size;i++){ premise = premiseList.getJSONObject(i); premise.put("keyword", textReplace(premise.getString("keyword"), replaceMap)); //premise.put("keyword", premise.getString("keyword").replace("\r\n", "").replace("\n", "").replace("\r", "")); premiseList.set(i, premise); } return premiseList; } /** * 如果剧情文本中出现变量槽,那么需要判断这个剧情的npc是不是在线模式,如果不是在线模式,就需要把变量槽过滤掉 * @param plot */ public static void varSlotFilt(JSONObject plot, Map keywordMap){ String VARIABLE_SEARCH_PATTERN = "【(.*?)@(.*?)(\\$\\{.*?})", npcName, middleText = "", varSlot = ""; //不加 】,直接替换npcName到变量槽的文本 //System.out.println(plot.getString("id")); Pattern replacePattern = Pattern.compile(VARIABLE_SEARCH_PATTERN); Matcher m = replacePattern.matcher(plot.getString("plotText")); while (m.find()) { npcName = m.group(1); //onlineModeTalkers, 在CharecterConstructor中定义,q前面加一个逗号是为了防止出现子串匹配的问题 //System.out.println("npcName" + npcName); //System.out.println("varInitialMap.get(\"onlineModeTalkers\")" + varInitialMap.get("onlineModeTalkers")); if(keywordMap.get("onlineModeTalkers").indexOf("," + npcName + ",") == -1) { varSlot = m.group(3); middleText = m.group(2); plot.put("plotText", plot.getString("plotText").replace(npcName + "@" + middleText + varSlot, npcName + "@" + middleText)); } } } /** * * 剧情生成中包括3个剧情标识: * TaskLine 某地点剧情进度 * TaskCondition 某地点剧情进度用到的condition * TaskReply 某地点剧情用到的文本 * 剧情(id)的状态:null标识未激活,1、 2表示激活 * 将所有剧情根据地点分为多条剧情线,每一条剧情线都有一个计数器,记录当前地点的剧情到了第几步。 * 加上剧情计数器, null时未激活,大于等于1时表示已激活 * @param root * @param userinfo */ public void BFSGenerate4(JSONObject root, UserInfo userinfo, JSONObject jsonObject) { String id, rootId = (String) root.get("id"), adjId, nextId, conditionName = DEFAULT_CONDITION, nextUnknownText, curUnknownText, nextCondition, location, nextLocation, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition, reply; String hint, gameStep, nextGameStep; JSONObject node = null, branchNode = null; Boolean curAutoJump, nextAutoJump = false, prevAutoJump, moveWithPlot = false; StringBuffer skipText = new StringBuffer(), extraUK = new StringBuffer(), extraHP = new StringBuffer(), extraFT = new StringBuffer(), arriveUK = new StringBuffer(); JSONArray branch = null; Boolean preferQA = false; int branchSize; List curPremiseList, historyPremiseList; //设置初始化unknown文本 root.put("nextUnknownText", varInitialMap.get("unknownText")); root.put("parentId", "null"); //当前剧情是否自动跳转的标识 root.put("autoJump", false); //上一步剧情是否自动跳转的标识 root.put("prevAutoJump", false); jsonObject.put("plotStartText", ((String)jsonObject.get("plotStartText")).replace("\n", "").replace(",", ",")); if(root.get("conditionName") != null && !root.get("conditionName").equals("")) conditionName = (String)root.get("conditionName"); else{ //如果剧情是无条件剧情,就设置默认condition conditionName = DEFAULT_CONDITION; root.put("conditionName", conditionName); } //根据地点生成变量名,标志地点的任务进度,condition和回答 String startPlace = root.getString("place"); String startTaskLine = String.format(TASK_LINE, startPlace); String startTaskCondition = String.format(TASK_CONDITION, startPlace); String startTaskReply = String.format(TASK_REPLY, startPlace); //在配置文件中设置初始值 varInitialMap.put("site", startPlace); varInitialMap.put(startTaskLine, String.format(GAME_STEP_FORMAT, botAccount, rootId)); varInitialMap.put(startTaskCondition, ""); varInitialMap.put(startTaskReply, ""); //添加变量的描述 conditionDescription.put(startTaskLine, startTaskLine); conditionDescription.put(startTaskCondition,startTaskCondition); conditionDescription.put(startTaskReply, startTaskReply); //generateStartGame(root, jsonObject, startPlace, conditionName); Queue queue = new LinkedList(); queue.add(root); //System.out.println(root.toJSONString()); while (!queue.isEmpty()) { node = queue.remove(); //剧情id id = (String) node.get("id"); location = ((String) node.get("place")).split("\\+")[0]; conditionName = (String) node.get("conditionName"); //当前剧情是否自动跳转 curAutoJump = node.getBoolean("autoJump"); prevAutoJump = node.getBoolean("prevAutoJump"); curUnknownText = (String) node.get("unknownText"); //preferQA = node.getBoolean("remain"); //剧情状态的名字,任务线xxx的进度 taskLineName = String.format(TASK_LINE, location); conditionDescription.put(id, String.format(PLOT_STATUS, id)); varInitialMap.put(id ,""); //本任务线的最后一个condition和本任务线的最后一个回答 branch = node.getJSONArray("branch"); branchSize = branch.size(); //遍历剧情分支 for (int i = 0; i < branchSize; i++) { skipText.setLength(0); branchNode = branch.getJSONObject(i); //reply = branchNode.getString("reply"); Map updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class); nextId = branchNode.getString("nextPlotId"); preferQA = branchNode.getBoolean("remain"); //是否将玩家移动到下个剧情所在地点 moveWithPlot = branchNode.getBoolean("moveWithPlot"); //如果下一部剧情不存在,就新建一个终止结点,id名为当前id+"_end",终止节点剧情文本为当前剧情的unknown文本 if(nextId == null || nextId.equals("") || !plotIndex.containsKey(nextId)){ nextId = id + "_end"; createEndNode(node, id, nextId, curUnknownText); } //如果选了合并剧情/自动跳转,那么一定会把玩家地点切换到下个剧情的地点 if(moveWithPlot == null || curAutoJump) moveWithPlot = true; //下一步剧情的unknown文本 nextUnknownText = plotIndex.get(nextId).getString("unknownText"); //下一步剧情的自动跳转 nextAutoJump = plotIndex.get(nextId).getBoolean("autoJump"); reply = plotIndex.get(nextId).getString("plotText"); if(reply.equals("")) reply = curUnknownText; //如果存在下一剧情,就将下一步剧情的condition设为要激活的conditin,把地点更新为下一步剧情的地点,并更新任务线进度 nextCondition = plotIndex.get(nextId).getString("conditionName"); if(nextCondition.equals("")) //condition为空,则设置默认condition nextCondition = DEFAULT_CONDITION; nextLocation = plotIndex.get(nextId).getString("place"); //需要更新 下个剧情发生地点 任务线进度 nTaskLineName = String.format(TASK_LINE, nextLocation); ////需要更新 下个剧情发生地点最后一个condition lastTaskCondition = String.format(TASK_CONDITION, nextLocation); lastTaskReply = String.format(TASK_REPLY, nextLocation); //剧情点qa标识 gameStep = String.format(GAME_STEP_FORMAT, botAccount, id); nextGameStep = String.format(GAME_STEP_FORMAT, botAccount,nextId); /** * 额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情 * 如果某个地点的剧情已经到结尾啦,那么有两种解决方法: * 1: 将剧情停留在最后一步剧情 * 2. 设一个专门的剧情表示剧情的结尾 */ //现在暂时放开下一步剧情未发生过的限制条件 //extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1 + "," + nextId + "::match-Include=null"; /** * 剧情分支触发的系统前置条件 * 该地点的任务线进度=玩家剧情进度 * 玩家处于剧情地点 * 剧情已被激活 */ appendPremise(extraHP, taskLineName, "match", "Include", gameStep); appendPremise(extraHP, "site", "match", "Include", location); appendPremise(extraHP, id, "match", "Include", "1"); /** * 剧情分支触发后的变量更新操作 * 下个剧情发生地点 任务线进度 * 下个剧情发生地点最后一个condition * 当前剧情状态加一 * 下一步剧情设为1, 激活 * 无匹配次数清零 * */ appendKnowledge(extraUK, nTaskLineName, nextGameStep); appendKnowledge(extraUK, lastTaskCondition, nextCondition); appendKnowledge(extraUK, lastTaskReply, reply); appendKnowledge(extraUK, id, "+1"); appendKnowledge(extraUK, nextId, "1"); appendKnowledge(extraUK, UNKNOWN_COUNTER_NAME, "0"); //如果剧情结束了,那么qa还是留在最后一部剧情 //如果下一步剧情不存在,那么下一步剧情id为当前id加后缀_end,但是用户提交qa的game_step应该还是当前id,没有加上_end if(nextId.endsWith("_end")) { nextGameStep = String.format(GAME_STEP_FORMAT, botAccount,id); } //System.out.println(id); appendFeature(extraFT, "match"); //如果下一步剧情是自动跳转,并且(当前剧情和下一部剧情地点相同或者用户选中了自动切换地点), // 先把本剧情的文本保留到plot_jump_text, 然后系统会在这个配置文件处理完成后,激活下一个(自动跳转)剧情的配置文件 if(doActivatePlot(nextAutoJump, location, nextLocation, moveWithPlot) ){ appendKnowledge(extraUK, "plot_jump_text", "str+" + reply); } /** * 1. 主角是否随剧情移动 * 如果随剧情移动,则更新地点和game_step * 如果不随剧情移动,则不更新地点和game_step,添加中间配置"去XX",设高优先级,并更新状态 * * 2. 当前条件是否为空 * 如果当前条件为空,则提交qa激活并进入下一步剧情 * 如果当前条件不为空,则需要满足条件才能进入下一步剧情 * * 3. 下一部剧情是否为空 * * * 4. 有没有说去XX * * 主角不随剧情移动+当前条件为空+去沙滩 * 1、沙滩无剧情 * 2、沙滩有剧情 * * 5. 地点变化 * 1. 当前所处地点 * 2. 下一步剧情所处地点(包含自动跳转的情况) * 3. 自动跳转完成后的地点 */ /** * 自动跳转前的剧情也要记下来,这里是自动跳转前需要更新的变量(无论是否包含自动跳转都会更新) * 1. 将自动跳转剧情的关联地点最后被激活的condition更新为yaobuyao (其实这一步是非必须的,) * 2. 自动跳转剧情文本保存到beforeJumpTaskReply * 3. 当前剧情和下一步剧情更新状态 */ //如果用户在分支里选了提前激活 if(branchNode.containsKey("activateExtraPlot")) { //激活除了下一步剧情以外的剧情 extraActivatedPlot(extraUK, nextLocation, branchNode.getJSONObject("activateExtraPlot")); } //如果主角的位置随着剧情移动(切换地点)或者下一步剧情地点和当前剧情相同,即如果玩家可以直接到达下一个剧情所在地点,主角地点和game_step要做相应更新, if(moveWithPlot || location.equals(nextLocation)) { appendKnowledge(extraUK, "site", nextLocation); appendKnowledge(extraUK, "game_step", nextGameStep); appendKnowledge(extraUK,"unknownText", nextUnknownText); //extraUK += "-<-site:" + nextLocation + "-<-game_step:" + nextGameStep; //如果当前剧情所在地喝下一步剧情所在地不一样,那么unknown文本 //只有到达下一步剧情所在地时才会更新 } else { if(!location.equals(nextLocation)){ //System.out.println(id + "报异常" + curUnknownText); if(curUnknownText.equals("")) { //如果没有unknown,就提示他到下一个地点 hint = String.format(LOCATION_HINT, nextLocation); //hint = "请到" + nextLocation; //如果当前地点和下一步剧情地点不同,要提示 }else { //如果有unknown,就提示unknown文本 hint = curUnknownText; } //下一部剧情在不同地点时,为了防止到配置文件重复执行,需要加一个标志表示下一步剧情是否已经发生过 // activate_by 下一个地点的剧情是由当前剧情激活的 //_activate_ready 下一个地点的剧情等待被激活 appendKnowledge(extraUK, nextLocation + "_activate_by", id); appendKnowledge(extraUK, nextLocation + "_activate_ready", "1"); // 如果不能直接到达所在地点,说明剧情1-1和1-2直接存在一个中间结点,这些更新操作会放在中间结点执行(动态生成,方法名:arriveActivatePlot2 这个中间结点会被当做一个监听剧情来处理) arriveActivatePlot2(jsonObject, id, nextId, nextLocation); //回答改为提示文本 reply = hint; } } //System.out.println(branchNode); //取出作者设定的剧情条件 curPremiseList = JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), Premise.class); historyPremiseList = JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), Premise.class); //是否将当前识别到的数据加入到已知数据列表 if((Boolean)branchNode.get("includeCurInfo")){ appendFeature(extraFT, "includeCurInfo"); } //如果分支中存在额外操作,在将这些额外操作(提交表单、激活、存档、读档等)添加到配置文件 if(branchNode.get("extraFeature") != null){ appendFeature(extraFT, branchNode.getString("extraFeature")); } //如果符合激活下一个剧情配置文件的操作 if(doActivatePlot(nextAutoJump, location, nextLocation, moveWithPlot) ){ //在配置文件中添加激活的操作 appendFeature(extraFT, "activate:after"); //激活下一步剧情id nextCondition = "plot_" + nextId; } //生成配置文件 configTermText = new ConfigTermText( curPremiseList, historyPremiseList, updateKnowledge, "", extraHP.toString(), extraUK.toString(), extraFT.toString(), reply, nextCondition, "1" ); configTermText.setConfigName("plot_" + id, false); //当剧情没有条件限制时的操作(条件剧情) 需要顺便激活qa、地图、物品的查询配置文件, 额外要求当前剧情不是自动跳转(当前剧情不是合并剧情) if (curPremiseList.size() == 0 && historyPremiseList.size() == 0 && !curAutoJump){ if(preferQA != null && preferQA) { ConfigTermText termText1, termText2, tmpTermText; tmpTermText = configTermText; termText1 = createTermExtra1(configTermText); termText2 = createTermExtra2(configTermText); configTermText = alterTerm(configTermText); configTermTextList.add(termText1); configTermTextList.add(termText2); } else { Boolean activateFlag = false; //有activate意味着下一步剧情是合并剧情 if(extraFT.indexOf("activate") != -1) activateFlag = true; unconditionalPlotProcess(configTermText, nextCondition, activateFlag); } } if (branchNode.getBoolean("higherPriority") != null && branchNode.getBoolean("higherPriority")) configTermText.setAuxiliaryPriority("3"); configTermTextList.add(configTermText); //将子结点加入队列 adjId = nextId; plotEnQueue(queue, id, adjId, nextUnknownText, curAutoJump); if(branchNode.getJSONObject("activateExtraPlot") != null){ for(String activateId:branchNode.getJSONObject("activateExtraPlot").keySet()){ plotEnQueue(queue, id, activateId, nextUnknownText, curAutoJump); } } extraFT.setLength(0); extraHP.setLength(0); extraUK.setLength(0); skipText.setLength(0); arriveUK.setLength(0); } } /** * ---------------------------------------------------------------------------------------------------- * 剧情不设条件时的处理 * 1. 如果qa返回大于90则回答common_answer+ 剧情回答,并进入下一步剧情,这里的下一步condition是从激活之前保存的临时变量中读取出来的 * 2. 如果qa返回小于90则只回答剧情文本 * 3. 如果qa返回not_found则只回答剧情文本 * 4. 无论哪种情况都会跳下一步剧情 */ unknownTypeConfigTermGenerate("sleeping", "queryskip1","qa_status::match-Include=OK,qa_score::number-Smaller=98", "match", "{临时变量reply-2}", "process-nextStep:var={临时变量condition-2}"); unknownTypeConfigTermGenerate("sleeping", "queryskip2","qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=98", "match", "{临时变量reply-2}", "process-nextStep:var={临时变量condition-2}"); unknownTypeConfigTermGenerate("sleeping", "queryskip3","qa_status::match-Include=not_found", "match", "{临时变量reply-2}", "process-nextStep:var={临时变量condition-2}"); /** * ---------------------------------------------------------------------------------------------------- * 待激活列表,用于qa问答 */ //处于激活状态,其他的属于待激活状态,jStatus这一条不设为1,而是0 unknownTypeConfigTermGenerate("waiting", "unknownStart","", "activate,post::gameQA(" + QA_URL + ")", "{unknownText-2}", ""); unknownTypeConfigTermGenerate("sleeping", "unknown1","qa_status::match-Include=not_found", "match,return-0", "{unknownText-2}", ""); unknownTypeConfigTermGenerate("sleeping", "unknown2","qa_status::match-Include=not_found,unknownText::match-Include=null", "match,return-0", UNKNOWN_TEXT, ""); unknownTypeConfigTermGenerate("sleeping", "unknown3","qa_status::match-Include=OK,qa_score::number-Smaller=98,unknownText::match-Include=null", "match,return-0", UNKNOWN_TEXT, ""); unknownTypeConfigTermGenerate("sleeping", "unknown4","qa_status::match-Include=OK,qa_score::number-Smaller=98", "match,return-0", "{unknownText-2}", ""); //由于剧情跳转时地点可能发生变化, qa问答的句子可能因为npc不再同一位置而被过滤掉,所以将common_answer的字符串合并放在postprocessing中 unknownTypeConfigTermGenerate("sleeping", "common_answer","qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=98", "match,return-0", "", ""); //--------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------------- /** * ---------------------------------------------------------------------------------------------------- * 用于存档 */ configTermText = new ConfigTermText( "save_game::match-Include=+要:存档", " ", "match,return-0,gameBackup", "{archiveOperation-2}" ," ", "" ); configTermText.setAuxiliaryPriority("4"); configTermTextList.add(configTermText); } public void unknownTypeConfigTermGenerate(String configStatus, String configName, String historyPremise, String feature, String reply, String updateKnowledge){ configTermText = new ConfigTermText( " ", historyPremise, feature, reply ," ", UNKNOWN_COUNTER_NAME + ":+1" ); configTermText.setStatus(configStatus); configTermText.setConfigName(configName,false); configTermText.setAuxiliaryPriority("0"); if(!updateKnowledge.equals("")) configTermText.setUpdateKnowledge(configTermText.getUpdateKnowledge() + "-<-" + updateKnowledge); if(configStatus.equals("waiting")){ configTermText.setNextStep("unknown4,unknown3,unknown2,unknown1,common_answer"); } configTermTextList.add(configTermText); } /** * 新建一个剧情结点 * @param node * @param id * @param nextId * @param nextUnknownText */ public void createEndNode(JSONObject node, String id, String nextId, String nextUnknownText){ String condition = (String) node.get("conditionName"); String location = ((String) node.get("place")).split("\\+")[0]; String nextCondition = condition; String nextLocation = location; String nTaskLineName = String.format(TASK_LINE, nextCondition); JSONObject endNode = new JSONObject(); endNode.put("place", location); endNode.put("conditionName", condition); endNode.put("id", nextId); endNode.put("plotText", nextUnknownText); endNode.put("autoJump", false); endNode.put("includeCurInfo", true); endNode.put("updateKnowledge", new ArrayList()); endNode.put("unknownText", ""); plotIndex.put(nextId, endNode); visited.put(nextId, true); } /** * 从配置文件中获取游戏开始时 游戏选择 的剧情, 即选择开始或者重新开始或者根据不同地点读档 * @param gameElements * @param keywordMap */ void addGameStartPlot(JSONObject gameElements, Map keywordMap){ File file = null; FileReader fr = null; BufferedReader br = null; try { file = new File("gameconfig.txt"); fr = new FileReader(file); br = new BufferedReader(fr); String jsonStr = br.readLine(); jsonStr = jsonStr.replace("startAutoJump", gameElements.getString("startAutoJump")); jsonStr = jsonStr.replace("firstUnknownText", gameElements.getString("firstUnknownText")); jsonStr = jsonStr.replace("plotStartText", gameElements.getString("plotStartText")); jsonStr = jsonStr.replace("startId", gameElements.getString("start")); jsonStr = jsonStr.replace("site_list", keywordMap.get("site_list").toString()); //System.out.println("JSONSTR ------------------------------\n" + jsonStr); JSONObject config = JSONObject.parseObject(jsonStr); gameElements.getJSONArray("plots").addAll(config.getJSONArray("gameStart")); gameElements.put("start", "start1"); gameElements.put("firstUnknownText", GAME_START_HINT); br.close(); fr.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * //如果是无条件剧情,那么需要跟着一个激活操作,激活查询qa、地图、物品、npc的配置文件 * *号是一个通配符,只要配置文件前缀相同就会被激活 * @param configTermText * @param nextCondition * @param activateFlag */ public void unconditionalPlotProcess(ConfigTermText configTermText, String nextCondition, Boolean activateFlag){ configTermText.setFeature(configTermText.getFeature() + ",activate,post::gameQA(" + QA_URL + ")"); // //if() if(activateFlag){ configTermText.setNextStep(nextCondition+ ",queryskip*,map*,item*,npc*"); }else { configTermText.setNextStep("queryskip*,map*,item*,npc*"); } //虽然激活了查询相关的配置文件,但返回给引擎的condition还是应该用剧情里的,所以 //将本配置条目中nextStep的值放在“临时变量condition”中,将本配置条目中的回答放在“临时变量reply”中,激活查询配置后,最后返回的condition应该是剧情指定的下一个condition //查询完了之后应该 把这两个临时变量复制到被激活的配置文件中,作为回答返回。 configTermText.setUpdateKnowledge(configTermText.getUpdateKnowledge() + "-<-临时变量condition:"+ nextCondition +"-<-临时变量reply:var={reply-3}"); configTermText.setNextStepStatus("active"); } /** * 在条件文本后面添加一个条件 * @param premiseStr * @param conditionName * @param cmpType * @param operator * @param value */ public void appendPremise(StringBuffer premiseStr, String conditionName, String cmpType, String operator, String value){ int strLen = premiseStr.length(); String split_punt = ""; if(premiseStr.length() != 0) split_punt = ","; premiseStr.append(split_punt); premiseStr.append(conditionName); premiseStr.append("::"); premiseStr.append(cmpType); premiseStr.append("-"); premiseStr.append(operator); premiseStr.append("="); premiseStr.append(value); } public void appendKnowledge(StringBuffer knowledgeStr, String key, String value){ knowledgeStr.append("-<-"); knowledgeStr.append(key); knowledgeStr.append(":"); knowledgeStr.append(value); } public void appendFeature(StringBuffer featureStr, String key){ featureStr.append(","); featureStr.append(key); } /** * 除了激活下一步剧情外,还可以同时激活其他地点的剧情,可以在剧情一开始就把ABC三个地点的剧情都激活,这样就不需要先玩完A,才能玩B * 本方法的主要功能是修改剧情的状态,已知后台会存储剧情一些关于剧情的状态 * * TaskLine 某地点剧情进度 * * TaskCondition 某地点剧情进度用到的condition * * TaskReply 某地点剧情用到的文本 * * 剧情(id)的状态:null标识未激活,1、 2表示激活 * 如果激活1-1,那么就是将剧情1-1的状态变为1,剧情所在地点的剧情进度更新为1-1,condition更新为1-1用到的condition * @param updateKnowledge * @param nextPlotLocation * @param activateExtraPlot 激活id列表 */ public void extraActivatedPlot(StringBuffer updateKnowledge, String nextPlotLocation, Map activateExtraPlot){ JSONObject plot = null; String plotId = "", location = "", lastTaskCondition = "", lastTaskReply = "", plotText = "", conditionName = "", taskLine = ""; StringBuffer newUK = updateKnowledge; Iterator plotIter = activateExtraPlot.keySet().iterator(); while(plotIter.hasNext()){ plotId = plotIter.next(); plotText = (String)activateExtraPlot.get(plotId); plot = plotIndex.get(plotId); conditionName = plot.getString("conditionName"); if(conditionName == null || conditionName.equals("")){ conditionName = DEFAULT_CONDITION; } location = plot.getString("place"); lastTaskCondition = String.format(TASK_CONDITION, location); lastTaskReply = String.format(TASK_REPLY, location); taskLine = String.format(TASK_LINE, location); appendKnowledge(newUK, lastTaskCondition, conditionName); appendKnowledge(newUK, lastTaskReply, plotText); appendKnowledge(newUK, taskLine, String.format(GAME_STEP_FORMAT, botAccount, plotId)); appendKnowledge(newUK, plotId, "1"); } } void plotEnQueue(Queue queue, String parentId, String adjId, String nextUnknownText, Boolean thisAutoJump){ JSONObject adjNode; if (visited.get(adjId) == null && plotIndex.get(adjId) != null) { visited.put(adjId, true); adjNode = plotIndex.get(adjId); adjNode.put("parentId", parentId); adjNode.put("prevAutoJump", thisAutoJump); queue.add(adjNode); } else { conditionDescription.put(adjId, String.format(PLOT_STATUS, adjId)); varInitialMap.put(adjId, ""); } } /** * 如果剧情1-1的地点是在沙滩,剧情1-2的地点实在营地,作者的游戏编辑平台里没有选中切换地点,那么就需要玩家一步一步地从沙滩走到营地(具体方法说“到xx,到营地”),然后才能开始1-2的剧情 * 这个时候就需要一个中间结点,当玩家说到营地的时候,才会执行剧情状态的更新,并且回答1-2的剧情文本 * 这块处理会被当做监听模块的一个剧情处理 */ void arriveActivatePlot2(JSONObject gameElements, String plotId, String nextId, String nextLocation){ JSONObject updateKnowledge = new JSONObject(); JSONArray curPremiseList = new JSONArray(); //curPremiseList.add(curPremise.toString()); JSONArray hisPremiseList = new JSONArray(); //hisPremiseList.add(hisPremise.toString()); //激活下一步剧情的几个条件:1. condition 到沙滩 2. 沙滩_activate_by 沙滩的剧情是有当前剧情激活的 3. 沙滩的剧情处于等待激活的状态 4. 当前地点和沙滩地点相邻或可以直接到达 // 2.3 两个条件是特意加的 curPremiseList.add(new Premise(GOTO_CONDITION, "match", "Include", nextLocation)); hisPremiseList.add(new Premise(nextLocation + "_activate_by", "match", "Include", plotId)); hisPremiseList.add(new Premise(nextLocation + "_activate_ready", "match", "Include", "1")); hisPremiseList.add(new Premise("isNeighbour:" + GOTO_CONDITION, "match", "Include", "1+3+4")); //无匹配次数清零 updateKnowledge.put(UNKNOWN_COUNTER_NAME, "0"); JSONObject listeningConfig = new JSONObject(); listeningConfig.put("curPremise", curPremiseList); listeningConfig.put("hisPremise", hisPremiseList); listeningConfig.put("updateKnowledge", updateKnowledge); listeningConfig.put("nextPlotId", nextId); listeningConfig.put("priority", "1"); //剧情优先级默认为1 if(gameElements.getJSONArray("listeningActions") == null) gameElements.put("listeningActions", new JSONArray()); gameElements.getJSONArray("listeningActions").add(listeningConfig); //放到监听剧情列表 } /** * 判断是否满足激活下一部剧情的条件 * 如果下一步剧情是自动跳转,并且(当前剧情和下一部剧情地点相同或者用户选中了自动切换地点),就为真 * @param nextAutoJump * @param location * @param nextLocation * @param moveWithPlot * @return */ Boolean doActivatePlot(Boolean nextAutoJump, String location, String nextLocation, Boolean moveWithPlot) { return nextAutoJump && (location.equals(nextLocation) || moveWithPlot); } // public void premiseTextFilt(JSONArray premiseList){ // int size = premiseList.size(); // JSONObject premise = null; // // for(int i = 0;i < size;i++){ // premise = premiseList.getJSONObject(i); // // premise.put("keyword", textReplace(premise.getString("keyword"), replaceMap)); // } // } /** * @param term 原始的配置数据 * @return 生成的用于QA的配置 */ private ConfigTermText alterTerm(ConfigTermText term) { ConfigTermText newTerm = (ConfigTermText)term.clone(); newTerm.setUpdateKnowledge(""); String stemStr = newTerm.getConfigName(); String feature = newTerm.getFeature(); feature = feature + ",activate,post::gameQA(" + QA_URL + ")"; newTerm.setFeature(feature); newTerm.setNextStep(stemStr+"_qa1,"+stemStr+"_qa2"); return newTerm; } private ConfigTermText createTermExtra1(ConfigTermText term) { String hPremise = "qa_score::number-Bigger=90"; String featureStr = "match,activate,return-0"; String nextStr = "map*,item*,npc*"; String knowledgeStr = UNKNOWN_COUNTER_NAME+":+1"; String configName = term.getConfigName()+"_qa1"; ConfigTermText newTerm = new ConfigTermText(" ", hPremise, featureStr, "", nextStr, knowledgeStr); newTerm.setConfigName(configName, false); newTerm.setStatus("sleeping"); return newTerm; } private ConfigTermText createTermExtra2(ConfigTermText term) { String hPremise = "qa_score::number-Smaller=90"; String featureStr = "match,activate"; String nextStr = "map*,item*,npc*"; String configName = term.getConfigName()+"_qa2"; if(term.getFeature().indexOf("activate") != -1) { nextStr = term.getNextStep() + "," + nextStr; } ConfigTermText newTerm = (ConfigTermText)term.clone(); newTerm.setHisPremise(hPremise); newTerm.setConfigName(configName, false); newTerm.setFeature(featureStr); newTerm.setNextStep(nextStr); newTerm.setStatus("sleeping"); return newTerm; } }