diff --git a/src/entity/ChatCache.java b/src/entity/ChatCache.java index 60bfd6e..e5188ef 100644 --- a/src/entity/ChatCache.java +++ b/src/entity/ChatCache.java @@ -1,14 +1,22 @@ package com.qiwu.chatbotbackend.entity; +import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ExecutionException; import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; +import com.qiwu.chatbotbackend.processing.ChatCacheController; +import org.springframework.beans.factory.DisposableBean; -public class ChatCache { +import javax.annotation.PreDestroy; + +public class ChatCache implements DisposableBean { + + + private String chatKey = "不知道"; private Map infoPoint = null; private GameEnv gameEnv = null; @@ -22,7 +30,9 @@ public class ChatCache { this.reloading = reloading; } + public String getChatKey() { return chatKey; } + public void setChatKey(String chatKey) { this.chatKey = chatKey; } public Map getInfoPoint() { return infoPoint; @@ -40,11 +50,20 @@ public class ChatCache { this.gameEnv = gameEnv; } - public ChatCache(GameEnv gameEnv, Map infoPoint){ + public ChatCache(String chatKey, GameEnv gameEnv, Map infoPoint){ + this.chatKey = chatKey; this.gameEnv = gameEnv; this.infoPoint = infoPoint; } + + + @Override + public void destroy() throws IOException { + //System.out.println("销毁:" + chatKey); + //ChatCacheController.saveChatCache(chatKey, this); + } + public ChatCache(UserInfo userInfo) throws Exception { try { gameEnv = new GameEnv(userInfo.botAccount); diff --git a/src/entity/JConfig.java b/src/entity/JConfig.java index 32dfda9..ce48592 100644 --- a/src/entity/JConfig.java +++ b/src/entity/JConfig.java @@ -10,6 +10,8 @@ import java.util.Map; public class JConfig implements Cloneable{ + static int iterNum = 0; + private int id = 0; private String jCurPremise = ""; private String jHisPremise = ""; @@ -51,8 +53,14 @@ public class JConfig implements Cloneable{ private String nextStep = ""; - public void setConfigName(String configName) { - this.configName = configName; + public void setConfigName(String configName, Boolean append) { + + if(append) { + iterNum++; + this.configName = configName + iterNum; + }else{ + this.configName = configName; + } } public String getConfigName() { @@ -65,7 +73,7 @@ public class JConfig implements Cloneable{ return curPremise; } - private String auxiliaryPriority = "0"; + private String auxiliaryPriority = "1"; private String status = "waiting"; @@ -178,6 +186,7 @@ public class JConfig implements Cloneable{ put("return-1", "back"); put("return-0", "stay"); put("activate", "activate"); + put("activate:after", "activate:after"); } }; static int querySkipCount = 10; @@ -266,6 +275,7 @@ public class JConfig implements Cloneable{ String pair1[] = premise.split("=", 2); String key = pair1[0]; + String keywords = pair1[1]; String pair2[] = key.split("::"); String conditionName = pair2[0]; @@ -367,6 +377,8 @@ public class JConfig implements Cloneable{ nextStepStatus = "return-0"; }else if(feat.equals("activate")){ nextStepStatus = "activate"; + }else if(feat.equals("activate:after")){ + nextStepStatus = "activate:after"; } } @@ -431,18 +443,28 @@ public class JConfig implements Cloneable{ } - public static JConfig activateCopy(JConfig jConfig){ + public static void activateCopy(JConfig jConfig, List jConfigList){ + + jConfig.setReply(jConfig.getReply() + "{临时变量reply-2}"); + JConfig jConfig2 = (JConfig) jConfig.clone(); - jConfig2.setReply(jConfig2.getReply() + ",{临时变量2-2}"); - jConfig2.setUpdateKnowledge(jConfig2.getUpdateKnowledge() + "-<-process-nextStep:var={临时变量1-2}"); - jConfig2.setStatus("sleeping"); - jConfig2.setConfigName("queryskip" + String.valueOf(querySkipCount)); - querySkipCount++; - jConfig2.setjStatus(1); - jConfig2.setAuxiliaryPriority("2"); + if(jConfig.getHisPremise().equals(" ")) + jConfig.setHisPremise("临时变量condition::match-Include=+null"); + else + jConfig.setHisPremise(jConfig.getjHisPremise() + ",临时变量condition::match-Include=+null"); + jConfig.setConfigName("map", true); + + if(jConfig2.getUpdateKnowledge().equals("")) + jConfig2.setUpdateKnowledge("process-nextStep:var={临时变量condition-2}"); + else + jConfig2.setUpdateKnowledge(jConfig2.getUpdateKnowledge() + "-<-process-nextStep:var={临时变量condition-2}"); + jConfig2.setConfigName("map", true); + + + jConfigList.add(jConfig); + jConfigList.add(jConfig2); - return jConfig2; } diff --git a/src/gameDesign/GlobalVariableConstructor.java b/src/gameDesign/GlobalVariableConstructor.java index 4cb1caa..1413d19 100644 --- a/src/gameDesign/GlobalVariableConstructor.java +++ b/src/gameDesign/GlobalVariableConstructor.java @@ -41,6 +41,8 @@ public class GlobalVariableConstructor extends ElementConstructor { } } + varInitialMap.put("botType", "game"); + JSONObject script = gameElements.getJSONObject("speechcraft"); for(String key:script.keySet()){ diff --git a/src/gameDesign/MapConstructor.java b/src/gameDesign/MapConstructor.java index 8d5ffa7..f9ad37d 100644 --- a/src/gameDesign/MapConstructor.java +++ b/src/gameDesign/MapConstructor.java @@ -48,6 +48,7 @@ public class MapConstructor extends ElementConstructor { keywordSet.append(jobj.get("name")); POS.append("=" + jobj.get("name") + "|地名\r\n"); if(jobj.containsKey("nickname")){ + for(String nickname:JSONArray.parseArray(locations.getJSONObject(i).getJSONArray("nickname").toJSONString(), String.class)){ if(!nickname.equals("")) { keywordSet.append("+" + nickname); @@ -390,6 +391,7 @@ public class MapConstructor extends ElementConstructor { } + public void generateSurroundThings(){ String conditionName = "know_exist_what_mohu"; String conditionKeywords = "有什么:周围+有什么:附近"; diff --git a/src/gameDesign/MapConstructor2.java b/src/gameDesign/MapConstructor2.java new file mode 100644 index 0000000..bccaeda --- /dev/null +++ b/src/gameDesign/MapConstructor2.java @@ -0,0 +1,418 @@ +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.JConfig; +import com.qiwu.chatbotbackend.entity.UserInfo; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; + +public class MapConstructor2 extends ElementConstructor { + + int[][] matrix; + int locationNum; + HashMap id2j = new HashMap(); + Map question2keyword = new HashMap(); + JSONArray locations = null; + + Map script = null; //话术模板 + + + public MapConstructor2(SqlHelper helper, int botId, int skipCount, String botAccount, HashSet exceptRelation, StringBuffer POS) { + super(); + this.helper = helper; + this.botId = botId; + this.botAccount = botAccount; + this.exceptRelation = exceptRelation; + this.skipCount = skipCount; + this.POS = POS; + } + + + public void constructGreph(JSONArray locations) { + + JSONObject jobj = null; + int locationId, index; + + //ArrayList> matrix= new ArrayList>(); + //ArrayList vec1d = new ArrayList(); + locationNum = locations.size(); + StringBuffer keywordSet = null; + + for (int i = 0; i < locationNum; i++) { + jobj = locations.getJSONObject(i); + jobj.put("index", i); + + keywordSet = new StringBuffer(); + keywordSet.append(jobj.get("name")); + POS.append("=" + jobj.get("name") + "|地名\r\n"); + if(jobj.containsKey("nickname")){ + + for(String nickname:JSONArray.parseArray(locations.getJSONObject(i).getJSONArray("nickname").toJSONString(), String.class)){ + if(!nickname.equals("")) { + keywordSet.append("+" + nickname); + POS.append("=" + nickname + "|地名\r\n"); + } + } + } + jobj.put("name", keywordSet.toString()); + + locationId = (Integer) jobj.get("id"); + id2j.put(locationId, jobj); + } + + //邻接矩阵初始化 + matrix = new int[locationNum][locationNum]; + for (int i = 0; i < locationNum; i++) { + for (int j = 0; j < locationNum; j++) { + matrix[i][j] = Integer.MAX_VALUE; + } + } + + for (int i = 0; i < locationNum; i++) { + List neighbours = JSONArray.parseArray(locations.getJSONObject(i).getJSONArray("neighbours").toJSONString(), Integer.class); + for (int neighbourId : neighbours) { + JSONObject neighbourObject = id2j.get(neighbourId); + System.out.println(neighbourObject); + index = (Integer) neighbourObject.get("index"); + matrix[i][index] = 1; + matrix[index][i] = 1; + } + } + } + + + public void construct(JSONObject gameElements, UserInfo userinfo) { + + try { + + + + + conditionDescription.put("site", "当前地点"); + + JSONObject map = gameElements.getJSONObject("map"); + Map question2keyword = JSONObject.toJavaObject(map.getJSONObject("question"), Map.class); + script = JSONObject.toJavaObject(gameElements.getJSONObject("speechcraft"), Map.class); + + if(!script.containsKey("PATH_AT")) + script.put("PATH_AT", "你已经在%s"); + if(!script.containsKey("WHERE_I_AM")) + script.put("WHERE_I_AM", "在%s"); + if(!script.containsKey("PATH_ADJOINT")) + script.put("PATH_ADJOINT", "就在附近哦"); + if(!script.containsKey("PATH_EXIST")) + script.put("PATH_EXIST", "通过%s可以到达目的地"); + if(!script.containsKey("PATH_NOT_EXIST")) + script.put("PATH_NOT_EXIST", "不可到达"); + if(!script.containsKey("CAN_GO_SITES")) + script.put("CAN_GO_SITES", "你可以去%s"); + if(!script.containsKey("CAN_GO_NOWHERE")) + script.put("CAN_GO_NOWHERE", "没什么地方可去的,继续玩吧"); + if(!script.containsKey("SITE_NOT_ACTIVE")) + script.put("SITE_NOT_ACTIVE", "你来到了%s\""); + if(!script.containsKey("SITE_NOT_ADJOINT")) + script.put("SITE_NOT_ADJOINT", "通过%s可以到达目的地"); + if(!script.containsKey("AROUND_PEOPLE")) + script.put("AROUND_PEOPLE", "周围有%s"); + if(!script.containsKey("AROUND_ITEMS")) + script.put("AROUND_ITEMS", "周围有%s"); + if(!script.containsKey("AROUND_THINGS")) + script.put("AROUND_THINGS", "周围有%s"); + + + + if(script == null){ + throw new Exception("话术不存在"); + } + JSONArray locations = map.getJSONArray("locations"); + String userName = (String) gameElements.get("userName"); + this.locations = locations; + this.question2keyword = question2keyword; + //通过邻接表构造邻接矩阵 + constructGreph(locations); + + //用弗洛伊德算法求最短路径 + Floyd floyd = new Floyd(); + floyd.findShortestPath(matrix, locationNum); + floyd.printPath(matrix, locationNum); + generateWantToThere(floyd.pathMatirx, floyd.preTable, gameElements); + generateWhereCanIgo(floyd.pathMatirx, floyd.preTable, gameElements); + generateWhereIam(gameElements, userName); + generateHowToThere(floyd.pathMatirx, floyd.preTable, gameElements); + generateSurroundingItem(); + generateSurroundingPeople(); + generateSurroundThings(); + + + + + } catch(Exception e){ + operationStatus = 0; + e.printStackTrace(); + message = "地图处理出现异常:"; + message += e.getMessage(); + return; + } + + } + + /** + * 生成‘我在哪里’所需要的配置文件 + */ + public void generateWhereIam(JSONObject gameElements, String botAccount) { + String conditionName = "rencheng"; + + String nickname = "qiwu"; + + String conditionKeywords = nickname + ":哪里+" + nickname + ":哪+现在:哪里+现在:哪"; + jConfig = new JConfig( + conditionName + "::match-Include=" + conditionKeywords, " ", + "match", "【{智能助手-2}】" + String.format(script.get("WHERE_I_AM"), "{site-2}") , "yaobuyao", "" + ); + jConfig.setNextStepStatus("return-0"); + jConfig.setAuxiliaryPriority("1"); + JConfig.activateCopy(jConfig, jConfigList); + + + } + + + + + + /** + * 生成‘怎么去哪里’所需要的配置文件 + */ + public void generateHowToThere(int[][] pathMatirx, int[][] preTable, JSONObject gameElements) { + String conditionName = "want_know_zenmezuo"; + String conditionKeywords = "去:地点"; + StringBuffer placeKeywords = new StringBuffer(); + + String placeA, placeB, descriptionB, text, pathNode; + + + for (int i = 0; i < locationNum; i++) { + placeA = (String) locations.getJSONObject(i).get("name"); + placeKeywords.append("+" + placeA); + + + } + + for (int j = 0; j < locationNum; j++) { + + placeB = (String) locations.getJSONObject(j).get("name"); + + + jConfig = new JConfig( + conditionName + "::match-Include=" + placeKeywords + + ",isNeighbour:"+ conditionName + "::match-Include=0", + "site::match-Include=" + placeB , + "match,return-0", + "【{智能助手-2}】" + String.format(script.get("PATH_AT"), "{site-2}"), + " ", + "" + ); + jConfig.setNextStepStatus("return-0"); + jConfig.setAuxiliaryPriority("1"); + JConfig.activateCopy(jConfig, jConfigList); + + + + + + jConfig = new JConfig( + conditionName + "::match-Include=" + placeKeywords + + ",isNeighbour:"+ conditionName + "::match-Include=1", + "site::match-Include=" + placeB , + "match,return-0", + "【{智能助手-2}】" + String.format(script.get("PATH_ADJOINT"), "{site-2}"), + " ", + "" + ); + jConfig.setNextStepStatus("return-0"); + jConfig.setAuxiliaryPriority("1"); + JConfig.activateCopy(jConfig, jConfigList); + + + + + jConfig = new JConfig( + conditionName + "::match-Include=" + placeKeywords + + ",isNeighbour:"+ conditionName + "::match-Include=2", + "site::match-Include=" + placeB , + "match,return-0", + "【{智能助手-2}】{map_reply-2}", + " ", + "map_reply:queryHowToPathBySite:" + conditionName + ); + jConfig.setNextStepStatus("return-0"); + jConfig.setAuxiliaryPriority("1"); + JConfig.activateCopy(jConfig, jConfigList); + + + } + + } + + + /** + * 生成‘我能去哪里’所需要的配置文件 + */ + public void generateWhereCanIgo(int[][] pathMatirx, int[][] preTable, JSONObject gameElements) { + String conditionKeywords = "去:哪里+能去:哪+能去:哪里+能去:哪儿"; + String conditionName = "choose_gowhere"; + String placeA, placeB, pathNode; + + for (int i = 0; i < locationNum; i++) { + placeA = (String) locations.getJSONObject(i).get("name"); + pathNode = ""; + + for (int j = 0; j < locationNum; j++) { + if (pathMatirx[i][j] == 1) { + placeB = (String) locations.getJSONObject(j).get("name"); + pathNode += "、" + placeB; + } + } + + jConfig = new JConfig( + conditionName + "::match-Include=" + conditionKeywords, "site::match-Include=" + placeA, + "match,return-0", "【{智能助手-2}】{map_reply-2}", " ", "map_reply:queryCanGoBySite:" + ); + jConfig.setNextStepStatus("return-0"); + jConfig.setAuxiliaryPriority("1"); + JConfig.activateCopy(jConfig, jConfigList); + } + } + + + /** + * 生成‘我要去那里’所需要的配置文件 + */ + public void generateWantToThere(int[][] pathMatirx, int[][] preTable, JSONObject gameElements) { + String placeA, placeB, descriptionB, text, pathNode, lastTaskCondition, lastTaskReply; + String conditionName = "yaobuyao"; + String conditionKeywords = "地点"; + String start = (String)gameElements.get("start"); + String placeKeywords; + + + for (int i = 0; i < locationNum; i++) { + placeA = (String) locations.getJSONObject(i).get("name"); + + /** + * 添加初始化变量 + */ + String placeAMain = placeA.split("\\+")[0]; + if(!varInitialMap.containsKey("任务线" + placeAMain + "最后一个condition")) { + varInitialMap.put("任务线" + placeAMain + "最后一个condition", "yaobuyao"); + varInitialMap.put("任务线" + placeAMain + "最后的回答", "你来到了" + placeAMain + ",现在什么都没有, 请继续之前的剧情,接着往下玩吧!"); + conditionDescription.put("任务线" + placeAMain + "最后一个condition", "任务线" + placeAMain + "最后一个condition"); + conditionDescription.put("任务线" + placeAMain + "最后的回答", "任务线" + placeAMain + "最后的回答"); + } + + + for (int j = 0; j < locationNum; j++) { + placeB = (String) locations.getJSONObject(j).get("name"); + String placeBMain = placeB.split("\\+")[0]; + descriptionB = (String) locations.getJSONObject(j).get("description"); + placeKeywords = conditionKeywords.replace("地点", placeB); + lastTaskCondition = "任务线" + placeBMain + "最后一个condition"; + lastTaskReply = "任务线" + placeBMain + "最后的回答"; + + + jConfig = new JConfig( + conditionName + "::match-Include=" + placeKeywords + + ",isNeighbour:"+ conditionName + "::match-Include=0", + "site::match-Include=" + placeA , + "match,return-0", + "【{智能助手-2}】" + String.format(script.get("PATH_AT"), placeBMain), + " ", + "" + ); + jConfig.setConfigName("map",true); + jConfigList.add(jConfig); + + + + jConfig = new JConfig( + conditionName + "::match-Include=" + placeKeywords + "," + ",isNeighbour:"+ conditionName + "::match-Include=1", + + "site::match-Include=" + placeA, + "match, reutrn-0,activate", "{" + lastTaskReply + "-2}", "plot_"+placeBMain + "_*","" + + ); + jConfig.setConfigName("map",true); + jConfigList.add(jConfig); + + //上一个配置文件激活时的默认选项 + jConfig = new JConfig( + " ", " ", "", "{" + lastTaskReply + "-2}" ," ", "process-nextStep:var={" + lastTaskCondition +"-2}-<-site:" + placeBMain + ); + jConfig.setStatus("sleeping"); + jConfig.setConfigName("plot_"+placeBMain + "_doudi",false); + jConfig.setjStatus(1); + jConfigList.add(jConfig); + + + + jConfig = new JConfig( + conditionName + "::match-Include=" + placeKeywords + + ",isNeighbour:"+ conditionName + "::match-Include=2", + "site::match-Include=" + placeA , + "match,return-0", + "【{智能助手-2}】{map_reply-2}", + " ", + "map_reply:queryToDoPathBySite:" + conditionName + ); + jConfig.setConfigName("map",true); + jConfigList.add(jConfig); + + } + } + + } + + public void generateSurroundingPeople(){ + String conditionName = "know_exist_what"; + String conditionKeywords = "周围:人+附近:人"; + + jConfig = new JConfig( + conditionName + "::match-Include=" + conditionKeywords, " ", + "match,return-0", "【{智能助手-2}】{map_query-2}。", "yaobuyao", "map_query:queryAroundNpcBySite:" + ); + JConfig.activateCopy(jConfig, jConfigList); + + } + + public void generateSurroundingItem(){ + String conditionName = "know_exist_what"; + String conditionKeywords = "周围:物品+周围:东西+附近:物品+附近:东西"; + + jConfig = new JConfig( + conditionName + "::match-Include=" + conditionKeywords, " ", + "match,return-0", "【{智能助手-2}】{map_query-2}。", "yaobuyao", "map_query:queryAroundGoodsBySite:" + ); + JConfig.activateCopy(jConfig, jConfigList); + + } + + + public void generateSurroundThings(){ + String conditionName = "know_exist_what_mohu"; + String conditionKeywords = "有什么:周围+有什么:附近"; + + jConfig = new JConfig( + conditionName + "::match-Include=" + conditionKeywords, " ", + "match,return-0", "【{智能助手-2}】{map_query-2}。", "yaobuyao", "map_query:queryAroundAllBySite:" + ); + JConfig.activateCopy(jConfig, jConfigList); + + } + + +} \ No newline at end of file diff --git a/src/gameDesign/PlotConstructor.java b/src/gameDesign/PlotConstructor.java index 19594b5..c13b2eb 100644 --- a/src/gameDesign/PlotConstructor.java +++ b/src/gameDesign/PlotConstructor.java @@ -22,6 +22,11 @@ public class PlotConstructor extends ElementConstructor { private HashMap id2j = new HashMap(); HashMap visited = new HashMap(); + + public static String TASK_LINE = "任务线_%s进度"; + public static String TASK_CONDITION = "任务线%s最后一个condition"; + public static String TASK_REPLY = "任务线%s最后的回答"; + public HashMap getId2j() { return id2j; } @@ -50,7 +55,12 @@ public class PlotConstructor extends ElementConstructor { String taskLineName = "任务线_" + id2j.get(start).get("place") + "进度"; conditionDescription.put(taskLineName, taskLineName); - varInitialMap.put("unknownText", "你说啥?"); + 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) id2j.get(start).get("id"))); conditionDescription.put("unknownText", "对于无法识别的问题做出的回答"); conditionDescription.put("game_step", "QA问答游戏进度"); @@ -120,7 +130,6 @@ public class PlotConstructor extends ElementConstructor { boolean newBranch, manyParent; JSONObject node = null, branchNode = null, adjNode = null; JSONArray branch = null; - String taskLine = "任务线_%s进度"; List adjNodeList = null; @@ -151,9 +160,9 @@ public class PlotConstructor extends ElementConstructor { (String)jsonObject.get("plotStartText"), conditionName, "任务线" + startPlace + "最后一个condition:" + conditionName + "-<-" + root.get("id") + ":+1" + - "-<-任务线" + startPlace + "最后的回答:" + (String)jsonObject.get("plotStartText") + "-<-" + String.format(taskLine, startPlace) + ":" + root.get("id") + "-<-任务线" + startPlace + "最后的回答:" + (String)jsonObject.get("plotStartText") + "-<-" + String.format(TASK_LINE, startPlace) + ":" + root.get("id") ); - jConfig.setAuxiliaryPriority("1"); + jConfig.setAuxiliaryPriority("2"); jConfigList.add(jConfig); jConfig = new JConfig( @@ -164,7 +173,7 @@ public class PlotConstructor extends ElementConstructor { "start_options", "" ); - jConfig.setAuxiliaryPriority("1"); + jConfig.setAuxiliaryPriority("2"); jConfigList.add(jConfig); @@ -214,7 +223,7 @@ public class PlotConstructor extends ElementConstructor { nextId = (String) branchNode.get("nextPlotId"); reply = (String)branchNode.get("reply"); Map updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class); - if(updateKnowledge.containsKey("unkonwnText")) + if(updateKnowledge.containsKey("unknownText")) nextUnknownText = updateKnowledge.get("unknownText"); else nextUnknownText = "unknown"; @@ -230,10 +239,13 @@ public class PlotConstructor extends ElementConstructor { } else { //如果不存在下一剧情,就将condition设为空,任务线进度不变 + nextId = id; nTaskLineName = taskLineName; nextLocation = location; nextCondition = "yaobuyao"; - continue; + branchNode.put("reply", curUnknownText); + reply = curUnknownText; + branchNode.put("moveWithPlot", false); } lastTaskCondition = "任务线" + nextLocation + "最后一个condition"; @@ -241,18 +253,68 @@ public class PlotConstructor extends ElementConstructor { //额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情 - extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1 + "," + nextId + "::match-Include=null"; + extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1; + if(!id.equals(nextId)){ + extraHP += "," + nextId + "::match-Include=null"; + } extraUK = nTaskLineName + ":" + nextId + "-<-" + lastTaskCondition + ":" + nextCondition + "-<-" + lastTaskReply + ":" + (String)branchNode.get("reply") + - "-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1" + "-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextId); - + "-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1" ; + + + /** + * 1. 主角是否随剧情移动 + * 如果随剧情移动,则更新地点和game_step + * 如果不随剧情移动,则不更新地点和game_step,添加中间配置"去XX",设高优先级,并更新状态 + * + * 2. 当前条件是否为空 + * 如果当前条件为空,则提交qa激活并进入下一步剧情 + * 如果当前条件不为空,则需要满足条件才能进入下一步剧情 + * + * 3. 下一部剧情是否为空 + * 如果下一部剧情为空,剧情编号、任务线、地点、不变,condition改为yaobuyao,reply改为当前unknown文本,主角不随剧情移动 + * + * 4. 有没有说去XX + * + * 主角不随剧情移动+当前条件为空+去沙滩 + * 1、沙滩无剧情 + * 2、沙滩有剧情 + */ + + //如果主角的位置随着剧情移动 if(!branchNode.containsKey("moveWithPlot") || (Boolean)branchNode.get("moveWithPlot")) { - extraUK += "-<-site:" + nextLocation; + extraUK += "-<-site:" + nextLocation + "-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextId); }else { if(!location.equals(nextLocation)){ + if(curUnknownText.equals("")) + reply = "请到" + nextLocation; //如果当前地点和下一步剧情地点不同,要提示 - reply = "请到" + nextLocation + "开始下一步剧情"; + else + reply = curUnknownText; + + + + //如果下一步剧情和当前剧情的地点是不一样的,那么在玩家没有到达下一个地点是剧情还是停留在当前剧情,只有到达目的地后,下一步剧情才会发生变化 + + + jConfig = new JConfig( + "yaobuyao::match-Keyword=+" + nextLocation, + "game_step::match-Include=" + String.format(GAME_STEP_FORMAT, botAccount, id) + "," + id + "::number-BiggerOrEqual=" + 1 + + "," + nextId + "::number-BiggerOrEqual=" + 1, + "match", (String)branchNode.get("reply"), (String) nextCondition, + "-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextId) + + "-<-unknownText:" + nextUnknownText + "-<-site:" + nextLocation + ); + jConfig.setStatus("sleeping"); + jConfig.setConfigName("plot_" + nextLocation + "_" + id,false); + jConfig.setjStatus(1); + + jConfigList.add(jConfig); + + //必须在上一个jConfig添加完之后 + //extraUK = extraUK.replace("-<-" + nextId + ":" + "+1", ""); + } } @@ -264,13 +326,15 @@ public class PlotConstructor extends ElementConstructor { JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class), updateKnowledge, "", extraHP, extraUK, - "match", reply, (String) nextCondition, "0" + "match", reply, (String) nextCondition, "1" ); + + //没有当前条件的限制, if (curPremiseList.size() == 0){ jConfig.setFeature(jConfig.getFeature() + ",activate,post::gameQA(http://simqa.sz.chewrobot.com:28081/game)"); - jConfig.setNextStep("queryskip1,queryskip2,queryskip3"); - jConfig.setUpdateKnowledge(jConfig.getUpdateKnowledge() + "-<-临时变量1:"+ nextCondition +"-<-临时变量2:var={reply-3}"); + jConfig.setNextStep("queryskip*,map*"); + jConfig.setUpdateKnowledge(jConfig.getUpdateKnowledge() + "-<-临时变量condition:"+ nextCondition +"-<-临时变量reply:var={reply-3}"); jConfig.setNextStepStatus("active"); } @@ -329,28 +393,31 @@ public class PlotConstructor extends ElementConstructor { */ jConfig = new JConfig( - " ", "qa_status::match-Include=ok,qa_score::number-Smaller=90", "match", "{临时变量2-2}", " ", "process-nextStep:var={临时变量1-2}" + " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" ); jConfig.setStatus("sleeping"); - jConfig.setConfigName("queryskip1"); + jConfig.setConfigName("queryskip1",false); jConfig.setjStatus(1); + jConfig.setAuxiliaryPriority("0"); jConfigList.add(jConfig); jConfig = new JConfig( - " ", "qa_status::match-Include=ok,qa_score::number-BiggerOrEqual=90", "match", "{common_answer-2}, {临时变量2-2}", " ", "process-nextStep:var={临时变量1-2}" + " ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match", "{common_answer-2}, {临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" ); jConfig.setStatus("sleeping"); - jConfig.setConfigName("queryskip2"); + jConfig.setConfigName("queryskip2",false); jConfig.setjStatus(1); + jConfig.setAuxiliaryPriority("0"); jConfigList.add(jConfig); jConfig = new JConfig( - " ", "qa_status::match-Include=not_found", "match", "{临时变量2-2}", " ", "process-nextStep:var={临时变量1-2}" + " ", "qa_status::match-Include=not_found", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" ); jConfig.setStatus("sleeping"); - jConfig.setConfigName("queryskip3"); + jConfig.setConfigName("queryskip3",false); jConfig.setjStatus(1); + jConfig.setAuxiliaryPriority("0"); jConfigList.add(jConfig); @@ -365,8 +432,9 @@ public class PlotConstructor extends ElementConstructor { " ", "qa_status::match-Include=not_found", "match,return-0", "{unknownText-2}", " ", "" ); jConfig.setStatus("sleeping"); - jConfig.setConfigName("unknown1"); + jConfig.setConfigName("unknown1",false); jConfig.setjStatus(1); + jConfig.setAuxiliaryPriority("0"); jConfigList.add(jConfig); @@ -376,37 +444,41 @@ public class PlotConstructor extends ElementConstructor { " ", "" ); jConfig.setStatus("sleeping"); - jConfig.setConfigName("unknown2"); + jConfig.setConfigName("unknown2",false); jConfig.setjStatus(1); + jConfig.setAuxiliaryPriority("0"); jConfigList.add(jConfig); jConfig = new JConfig( - " ", "qa_status::match-Include=ok,qa_score::number-Smaller=90,unknownText::match-Include=null", "match,return-0", + " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90,unknownText::match-Include=null", "match,return-0", "不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧", " ", "" ); jConfig.setStatus("sleeping"); - jConfig.setConfigName("unknown3"); + jConfig.setConfigName("unknown3",false); jConfig.setjStatus(1); + jConfig.setAuxiliaryPriority("0"); jConfigList.add(jConfig); jConfig = new JConfig( - " ", "qa_status::match-Include=ok,qa_score::number-Smaller=90", "match,return-0", "{unknownText-2}", " ", "" + " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match,return-0", "{unknownText-2}", " ", "" ); jConfig.setStatus("sleeping"); - jConfig.setConfigName("unknown4"); + jConfig.setConfigName("unknown4",false); jConfig.setjStatus(1); + jConfig.setAuxiliaryPriority("0"); jConfigList.add(jConfig); jConfig = new JConfig( - " ", "qa_status::match-Include=ok,qa_score::number-BiggerOrEqual=90", "match,return-0", "{common_answer-2}" ," ", "" + " ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match,return-0", "{common_answer-2}" ," ", "" ); jConfig.setStatus("sleeping"); - jConfig.setConfigName("common_answer"); + jConfig.setConfigName("common_answer",false); jConfig.setjStatus(1); + jConfig.setAuxiliaryPriority("0"); jConfigList.add(jConfig); //--------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------------- diff --git a/src/processing/ChatCacheController.java b/src/processing/ChatCacheController.java index c4c35a8..1bc456b 100644 --- a/src/processing/ChatCacheController.java +++ b/src/processing/ChatCacheController.java @@ -129,27 +129,26 @@ public class ChatCacheController { ChatCache chatCache = null; GameEnv gameEnv = null; Map infoPoint = null; - String key = chatKey.split("-")[0]; String fileDir = System.getProperty("user.dir") + "/ChatCache"; String line, pair[]; Map infoPoints = new HashMap(); try { - File file = new File(String.format(ENV_PATH, key)); + File file = new File(String.format(ENV_PATH, chatKey)); if (file.exists()){ - gameEnv = (GameEnv) ObjectFileUtil.readObjectFromFile(String.format(ENV_PATH, key)); + gameEnv = (GameEnv) ObjectFileUtil.readObjectFromFile(String.format(ENV_PATH, chatKey)); }else{ throw new IOException("环境存档不存在"); } - file = new File(String.format(INFO_PATH, key)); + file = new File(String.format(INFO_PATH, chatKey)); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String jsonStr = br.readLine(); infoPoint = (Map)JSON.parseObject(jsonStr); - // context.setAttribute(userName, ); - chatCache = new ChatCache(gameEnv, infoPoint); + + chatCache = new ChatCache(chatKey, gameEnv, infoPoint); chatCache.setReloading(true); br.close(); @@ -281,26 +280,34 @@ public class ChatCacheController { context.setAttribute("chatCache", keyCacheMap); } -// public static synchronized String saveChatCache(String chatKey, ChatCache chatCache){ -// -// -// if(chatCache == null){ -// return "chat_key不存在或者已失效"; -// }else { -// String jChatCache = JSON.toJSONString(chatCache); -// System.out.println(jChatCache); -// -// -// -// chatCache = JSON.parseObject(jChatCache,ChatCache.class); -// System.out.println(chatCache.getInfoPoint().size()); -// -// return "成功"; -// } -// -// -// -// } + + public static synchronized boolean findChatCache(String chatKey, ServletContext context) throws Exception { + ChatCache chatCache = null; + GameEnv gameEnv = null; + Map infoPoint = null; + + String fileDir = System.getProperty("user.dir") + "/ChatCache"; + String line, pair[]; + Map infoPoints = new HashMap(); + try { + if (context.getAttribute("chatCache") != null) { + if (((HashMap)context.getAttribute("chatCache")).get(chatKey) != null){ + return true; + } + } + File file = new File(String.format(ENV_PATH, chatKey)); + if (file.exists()){ + return true; + } + + + } catch(Exception e){ + e.printStackTrace(); + return false; + } + + return false; + } } diff --git a/src/processing/FormsPoster.java b/src/processing/FormsPoster.java index 76de8b9..3399da7 100644 --- a/src/processing/FormsPoster.java +++ b/src/processing/FormsPoster.java @@ -59,7 +59,7 @@ public class FormsPoster { key = k_iter.next(); if (historyInfoPoint.get(key) != "") //infoMap.put(key + "_his", historyInfoPoint.get(key)); - if (key.equals("game_step")) + if (key.equals("game_step") || key.equals("qa_threshold")) pairList.add(new BasicNameValuePair(key, historyInfoPoint.get(key))); else if(skipSet.contains(key)){} else @@ -81,14 +81,17 @@ public class FormsPoster { historyInfoPoint.put("process", (String) jobj.get(keyName)); } else if (keyName.equals("solution")) { ans.setAnswer((String) jobj.get(keyName)); - } else if (keyName.equals("status")){ + } else if (keyName.equals("status") || keyName.equals("qa_candidates")){ continue; } else{ historyInfoPoint.put(keyName, jobj.getString(keyName)); } } }else { - ans.setAnswer("提交表单出现异常"); + if(URL.equals("http://simqa.sz.chewrobot.com:28081/game")) + ans.setAnswer("qa_threshold, game_step, query_text 看看少了哪个"); + else + ans.setAnswer("提交表单出现异常"); } @@ -169,7 +172,7 @@ public class FormsPoster { String key, keyName; Iterator k_iter = null; List pairList = new ArrayList(); - String threshold = "0.9"; + String threshold = "50"; if (historyInfoPoint.get("qa_threshold") != null) threshold = historyInfoPoint.get("qa_threshold"); @@ -199,7 +202,7 @@ public class FormsPoster { Matcher m = findTalker.matcher(textscore.get(0)); if(m.find()) { npc = m.group(1); - if (worldController.worldOperation(gameEnv, "NPC_query", "queryLocationByNPCName:", curInfoPoint, historyInfoPoint).equals(site)){ + if (worldController.worldOperation(gameEnv, "NPC_query", "queryLocationByNPCName:" + npc, curInfoPoint, historyInfoPoint).equals(site)){ historyInfoPoint.put("common_answer", textscore.get(0)); historyInfoPoint.put("qa_score", textscore.get(1)); break; diff --git a/src/processing/QuestionMatcher.java b/src/processing/QuestionMatcher.java index 6e56d07..6ed89db 100644 --- a/src/processing/QuestionMatcher.java +++ b/src/processing/QuestionMatcher.java @@ -99,15 +99,14 @@ public class QuestionMatcher { String values[] = receiveParameters.get(k); - for (String v : values) { - receiveParameterStr += v + " "; - } - receiveParameterStr += "
"; +// for (String v : values) { +// receiveParameterStr += v + " "; +// } + receiveParameterStr += values[0] + " " + "
"; + if (values[0].equals(":")) { curInfoPoint.put(k, ""); } - if(! historyInfoPoint.containsKey(k)) - historyInfoPoint.put(k, ""); } logWriter.record(receiveParameterStr, 0); @@ -183,6 +182,26 @@ public class QuestionMatcher { for (Condition condition : conditionList) { + if (condition.status.equals("waiting")){ + if ((condition.auxiliaryPriority > bestMatch.auxiliaryPriority) || (condition.auxiliaryPriority == bestMatch.auxiliaryPriority && condition.priority > bestMatch.priority)){ + if(conditionSatisfy(condition)){ + if (condition.featureMap.get("activate") != null && !condition.featureMap.containsKey("post")) { + //有post这个feature的配置条目会在最后激活它的待激活列表,这里就不激活了。 + bestMatch = condition; + logWriter.record("匹配更新为:\"" + userinfo.id2config.get(condition.id) + "\"", 2); + logWriter.writeln(); + + activateCondition(activatedQueue, curInfoPoint.get("bot_name"), condition.priority, condition.auxiliaryPriority, condition.nextStep, context); + }else { + bestMatch = condition; + logWriter.record("匹配更新为:\"" + userinfo.id2config.get(condition.id) + "\"", 2); + logWriter.writeln(); + } + } + + } + } + /* if (condition.status.equals("waiting") && conditionSatisfy(condition)) { @@ -205,6 +224,7 @@ public class QuestionMatcher { logWriter.writeln(); } } + */ } } @@ -238,7 +258,8 @@ public class QuestionMatcher { bestMatch = condition; activateCondition(activatedQueue, curInfoPoint.get("bot_name"), condition.priority, condition.auxiliaryPriority, condition.nextStep, context); //} else if ((condition.activePriority > bestMatch.activePriority) || (condition.activePriority == bestMatch.activePriority && condition.auxiliaryPriority > bestMatch.auxiliaryPriority)) { - } else if ((condition.auxiliaryPriority > bestMatch.auxiliaryPriority) || (condition.auxiliaryPriority == bestMatch.auxiliaryPriority && condition.activePriority > bestMatch.activePriority)) { + } else if ((condition.auxiliaryPriority > bestMatch.auxiliaryPriority) || (condition.auxiliaryPriority == bestMatch.auxiliaryPriority && condition.activePriority > bestMatch.activePriority) || + bestMatch.nextStep.contains(String.valueOf(condition.id)) || bestMatch.nextStep.contains(condition.configName)) { bestMatch = condition; logWriter.record("匹配更新为:\"" + userinfo.id2config.get(condition.id) + "\"", 2); logWriter.writeln(); @@ -273,7 +294,7 @@ public class QuestionMatcher { comparePair = premiseStr.split("::"); actionName = comparePair[0]; cmpType = comparePair[1]; - keyword = getKeyword(curInfoPoint, actionName); + keyword = getKeyword(curInfoPoint, historyInfoPoint, false, actionName); if (keyword == null) { flag = false; @@ -298,7 +319,8 @@ public class QuestionMatcher { comparePair = premiseStr.split("::"); cmpType = comparePair[1]; actionName = comparePair[0]; - keyword = getKeyword(historyInfoPoint, actionName); + //如果featureMap中包含includeCurInfo,则已知信息中包含啦当前对话中识别的所有信息 + keyword = getKeyword(historyInfoPoint, curInfoPoint, condition.featureMap.containsKey("includeCurInfo"), actionName); if (keyword == null) { flag = false; @@ -325,12 +347,12 @@ public class QuestionMatcher { } - public String getKeyword(Map infoPoint, String actionName){ + public String getKeyword(Map infoPoint, Map infoPoint2, Boolean chooseLater, String actionName){ String keyword = ""; String nameSeries[] = actionName.split("_"); if(actionName.startsWith("npc_")){ if(nameSeries.length == 4){ - String keywrod = gameEnv.queryNpcAttrByNpcName(nameSeries[3], nameSeries[4]); + keyword = gameEnv.queryNpcAttrByNpcName(nameSeries[3], nameSeries[4]); } }else if (actionName.startsWith("goods_")) { @@ -340,7 +362,7 @@ public class QuestionMatcher { } }else if(actionName.startsWith("isNeighbour")){ String opPair[] = actionName.split(":"); - if(!curInfoPoint.containsKey(opPair[1]) || curInfoPoint.get(opPair[1]).equals("unknown")){ + if(!curInfoPoint.containsKey(opPair[1]) || curInfoPoint.get(opPair[1]).equals("unknown") || curInfoPoint.get(opPair[1]).equals("")){ keyword = "not_exist"; }else { logWriter.record("isNeighbour(" + historyInfoPoint.get("site") + "," + curInfoPoint.get(opPair[1]).split(":")[1] + ")", 1); @@ -348,6 +370,15 @@ public class QuestionMatcher { logWriter.record("返回:" + keyword, 1); } }else { + + /** + * 如果chooseLater为真,则先提取infoPint2中的关键字,如果infoPoint2中不存在,再提取infoPoint中的关键字 + */ + if(chooseLater){ + keyword = infoPoint2.get(actionName); + if(keyword != null && !keyword.equals("")) + return keyword; + } keyword = infoPoint.get(actionName); } @@ -473,9 +504,9 @@ public class QuestionMatcher { } if(cmpType.equals("curVarCmp") && curInfoPoint.get(conditionName2) != null && !curInfoPoint.get(conditionName2).equals("")) { - conditionValue2 = getKeyword(curInfoPoint, conditionName2); + conditionValue2 = getKeyword(curInfoPoint, historyInfoPoint, false, conditionName2); }else if (cmpType.equals("hisVarCmp") && historyInfoPoint.get(conditionName2) != null && !historyInfoPoint.get(conditionName2).equals("")){ - conditionValue2 = getKeyword(historyInfoPoint, conditionName2); + conditionValue2 = getKeyword(historyInfoPoint, curInfoPoint, false, conditionName2); }else { flag = false; } @@ -703,8 +734,7 @@ public class QuestionMatcher { //如果一条配置文件有多个答案,则随 // 机选择一个答案 - int randNum = (int) (Math.random() * ansCondition.answer.length); - ans.setAnswer(ansCondition.answer[randNum]); + //System.out.println(ans.getAnswer()); //post关键字 @@ -749,7 +779,7 @@ public class QuestionMatcher { else ans.setNext("nextStep= "); //激活 - } else if (ansCondition.featureMap.containsKey("activate")) { + } else if (ansCondition.featureMap.containsKey("activate") || ansCondition.featureMap.containsKey("activate:after")) { String activeList[] = historyInfoPoint.get("activeList").split("\\|"); if (activeList.length == 1) ans.setNext("nextStep=" + activeList[activeList.length - 1]); @@ -769,10 +799,10 @@ public class QuestionMatcher { try { - + int randNum = (int) (Math.random() * ansCondition.answer.length); + reply = ansCondition.answer[randNum]; //用正则表达式将回答中的变量模板{conditionName-2}替换成后台存储的变量值 String keyword; - reply = ans.getAnswer(); Matcher m = replacePattern.matcher(reply); while (m.find()) { variable = m.group(1).substring(1, m.group(1).length() - 3); @@ -792,6 +822,12 @@ public class QuestionMatcher { reply = reply.replace("{" + variable + "-2}", historyInfoPoint.get(variable)); } } + + reply = ResponseFilter.filt(curInfoPoint,historyInfoPoint,gameEnv,worldController, reply, userinfo, ansCondition, logWriter); + + + + ans.setAnswer(reply); } catch (Exception e) { @@ -850,6 +886,9 @@ public class QuestionMatcher { }else if (keyword2 != null && !keyword1.equals("")) historyInfoPoint.put(actionName, keyword1); } + historyInfoPoint.put("临时变量reply", ""); + historyInfoPoint.put("临时变量condition", ""); + historyInfoPoint.put("临时变量3", ""); @@ -1096,7 +1135,8 @@ public class QuestionMatcher { keyword = historyInfoPoint.get(variableName); //如果变量名开头为NPC或者item,就专门交给world处理 - if(variableName.startsWith("npc_") || variableName.startsWith("goods_") || variableName.startsWith("map_")){ + if((userinfo.varInitialMap.get("botType") != null && userinfo.varInitialMap.get("botType").equals("game")) && + (variableName.startsWith("npc_") || variableName.startsWith("goods_") || variableName.startsWith("map_"))){ try { returnStr = worldController.worldOperation(gameEnv, variableName, updateValue, curInfoPoint, historyInfoPoint); updateValue = returnStr; @@ -1198,7 +1238,8 @@ public class QuestionMatcher { } else if (updateValue.endsWith("nextStep-3}")) { updateValue = condition.nextStep; } else if (updateValue.endsWith("reply-3}")) { - updateValue = condition.answer[0]; + int randNum = (int) (Math.random() * condition.answer.length); + updateValue = condition.answer[randNum]; } if (variableName.startsWith("process-nextStep")) { condition.nextStep = updateValue; @@ -1232,6 +1273,7 @@ public class QuestionMatcher { String configStr = ""; Integer configId; Condition newCondition, originCondition; + List originConditionList = new ArrayList(); for (String configIdStr : activateList.split(",")) { try { @@ -1239,10 +1281,31 @@ public class QuestionMatcher { configId = Integer.parseInt(configIdStr); configStr = userinfo.id2config.get(configId); originCondition = userinfo.id2condition.get(configId); + originConditionList.add(originCondition); } else { - originCondition = userinfo.name2condition.get(configIdStr); + if (configIdStr.endsWith("*")) { + String prefix = configIdStr.substring(0, configIdStr.length()-1); + for(String name:userinfo.name2condition.keySet()){ + if (name.startsWith(prefix)){ + originConditionList.add(userinfo.name2condition.get(name)); + } + } + + } else { + originConditionList.add(userinfo.name2condition.get(configIdStr)); + } + + } + } catch (Exception e) { + e.printStackTrace(); + logWriter.record("----------查找待激活condition出现异常:" + configIdStr, 5); + } + } + for (Condition condition: originConditionList){ + originCondition = condition; + try { configId = originCondition.id; @@ -1251,17 +1314,20 @@ public class QuestionMatcher { logWriter.record("------激活-------" + userinfo.id2config.get(configId) + "-------
", 0); - if (activatedMap.containsKey(configId) && newCondition.activePriority > activatedMap.get(configId).activePriority) { - activatedMap.get(configId).activePriority = newCondition.activePriority; + if (activatedMap.containsKey(configId)) { + if(newCondition.auxiliaryPriority > activatedMap.get(configId).auxiliaryPriority) + activatedMap.get(configId).auxiliaryPriority = newCondition.auxiliaryPriority; + if(newCondition.activePriority > activatedMap.get(configId).activePriority) + activatedMap.get(configId).activePriority = newCondition.activePriority; } else if (!activatedMap.containsKey(configId)) { activatedMap.put(configId, newCondition); activatedQueue.add(newCondition); } - - }catch (Exception e){ + }catch (Exception e) { e.printStackTrace(); - logWriter.record("----------激活失败:" + configIdStr, 5); + logWriter.record("----------激活失败:" + condition.configName, 5); } + } diff --git a/src/processing/ResponseFilter.java b/src/processing/ResponseFilter.java new file mode 100644 index 0000000..acaa447 --- /dev/null +++ b/src/processing/ResponseFilter.java @@ -0,0 +1,79 @@ +package com.qiwu.chatbotbackend.processing; + +import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; +import com.qiwu.chatbotbackend.entity.Condition; +import com.qiwu.chatbotbackend.entity.Solution; +import com.qiwu.chatbotbackend.entity.UserInfo; + +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static com.qiwu.chatbotbackend.processing.FormsPoster.TALKER; + +public class ResponseFilter { + + static String filt(Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController, + String reply, UserInfo userInfo, Condition ansCondition, LogWriter logWriter){ + String botType = userInfo.varInitialMap.get("botType"), npc, finalUnknownText; + + + if(botType == null){ + int randNum = (int) (Math.random() * ansCondition.answer.length); + return ansCondition.answer[randNum]; + + }else if (botType.equals("game")){ + + String site = historyInfoPoint.get("site"); + + + String answer[] = reply.split("~"); + int randNum = (int) (Math.random() * answer.length); + reply = answer[randNum]; + if(reply.startsWith("【" + historyInfoPoint.get("智能助手"))){ + return reply; + }else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter)){ + return reply; + + } + + if(userInfo.varInitialMap.get("unknownTextList") != null){ + for(String ans:userInfo.varInitialMap.get("unknownTextList").split("~")){ + if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter)){ + return ans; + } + } + } + + if(userInfo.varInitialMap.get("finalUnknownText") != null){ + finalUnknownText = userInfo.varInitialMap.get("finalUnknownText"); + if (sameLocation(finalUnknownText, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter)){ + return finalUnknownText; + } + } + + } + + + return ""; + } + + static Boolean sameLocation(String reply, Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController, String site, LogWriter logWriter){ + String npc; + Pattern findTalker = Pattern.compile(TALKER); + Matcher m = findTalker.matcher(reply); + if(m.find()) { + npc = m.group(1); + if (worldController.worldOperation(gameEnv, "NPC_query", "queryLocationByNPCName:" + npc, curInfoPoint, historyInfoPoint).equals(site)){ + return true; + }{ + logWriter.record(npc +"不在" + site + "跳过",1 ); + } + }else{ + logWriter.record(reply + "没有npc名,直接选中",1 ); + return true; + } + + return false; + } +} diff --git a/src/servlet/FindCacheServlet.java b/src/servlet/FindCacheServlet.java new file mode 100644 index 0000000..ebbd6a7 --- /dev/null +++ b/src/servlet/FindCacheServlet.java @@ -0,0 +1,51 @@ +package com.qiwu.chatbotbackend.servlet; + +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.processing.ChatCacheController; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; + +@WebServlet(name = "FindCacheServlet", urlPatterns = {"/findCache"}) +public class FindCacheServlet extends HttpServlet { + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + ServletContext context = this.getServletContext(); + + request.setCharacterEncoding("UTF-8"); + + String chatKey = request.getParameter("client_id"); + Boolean exist = false; + + try { + exist = ChatCacheController.findChatCache(chatKey, context); + } catch (Exception e) { + e.printStackTrace(); + } + + JSONObject responseJSONObject = new JSONObject(); + responseJSONObject.put("exist", exist); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/json; charset=utf-8"); + response.setHeader("Access-Control-Allow-Origin", "*"); + + System.out.println("xx:" + responseJSONObject.toJSONString()); + + + + PrintWriter out = response.getWriter(); + out.append(responseJSONObject.toString()); + out.flush(); + + + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + doPost(request, response); + } +} diff --git a/src/servlet/GameDesignServlet.java b/src/servlet/GameDesignServlet.java index 032caef..4a6a614 100644 --- a/src/servlet/GameDesignServlet.java +++ b/src/servlet/GameDesignServlet.java @@ -39,15 +39,6 @@ public class GameDesignServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - Enumeration enum1 = request.getHeaderNames(); - - - while(enum1.hasMoreElements()) { - System.out.println(enum1.nextElement()); - - } - - //所有需要修改的词性 StringBuffer POS = new StringBuffer(); @@ -120,7 +111,7 @@ public class GameDesignServlet extends HttpServlet { switch (moduleName) { case "map": moduleName2 = "地图"; - constructor = new MapConstructor(helper, botId, skipCount, botAccount, exceptRelation, POS); + constructor = new MapConstructor2(helper, botId, skipCount, botAccount, exceptRelation, POS); constructor.construct(gameElements, userinfo); break; case "plots": @@ -270,7 +261,7 @@ public class GameDesignServlet extends HttpServlet { } catch (UnsupportedEncodingException e) { e.printStackTrace(); } - if((Integer)returnMessage.get("status") == 1) { + if((Integer)returnMessage.get("post_status") == 1 && (Integer)returnMessage.get("status") == 1 ) { return "success"; }else { System.out.println(returnMessage.get("parameter")); diff --git a/src/servlet/GetAnswerServlet.java b/src/servlet/GetAnswerServlet.java index a5d1a63..2f02975 100644 --- a/src/servlet/GetAnswerServlet.java +++ b/src/servlet/GetAnswerServlet.java @@ -1,6 +1,7 @@ package com.qiwu.chatbotbackend.servlet; import com.qiwu.chatbotbackend.entity.*; +import com.qiwu.chatbotbackend.gameDesign.PlotConstructor; import com.qiwu.chatbotbackend.processing.*; import javax.servlet.ServletContext; @@ -35,6 +36,8 @@ public class GetAnswerServlet extends HttpServlet { String ansJ = "", return_str = "", state = "", chatKey = ""; String botName = receiveParamters.get("bot_name")[0]; + + //如果有client_id,会用@分隔 if(!receiveParamters.get("chat_key")[0].startsWith("@")) chatKey = receiveParamters.get("chat_key")[0].split("@")[0]; else @@ -97,7 +100,7 @@ public class GetAnswerServlet extends HttpServlet { try { bestMatch = matcher.getSolution(ansCondition, context, userinfo); - if (ansCondition.featureMap.containsKey("activate") && ansCondition.featureMap.containsKey("post")) { + if ((ansCondition.featureMap.containsKey("activate") && ansCondition.featureMap.containsKey("post")) || ansCondition.featureMap.containsKey("activate:after")) { //如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段 bestMatch = matcher.postActivate(ansCondition, context, userinfo); } @@ -113,6 +116,8 @@ public class GetAnswerServlet extends HttpServlet { matcher.appendDebugInfo(bestMatch, context); } + + //if(userinfo.varInitialMap.get("infoTransferTime") != null && userinfo.varInitialMap.get("infoTransferTime").equals("after")) matcher.infoTransfer(bestMatch, context, debugFlag); @@ -129,8 +134,10 @@ public class GetAnswerServlet extends HttpServlet { } else { System.out.println("----------读档中------------"); - String nextStep = chatCache.getInfoPoint().get("currentAction"); - String reply = chatCache.getInfoPoint().get("lastReply"); + String site = chatCache.getInfoPoint().get("site"); + + String nextStep = chatCache.getInfoPoint().get(String.format(PlotConstructor.TASK_CONDITION, site)); + String reply = chatCache.getInfoPoint().get(String.format(PlotConstructor.TASK_REPLY, site)); bestMatch = new Solution(1, "--读取存档--" + reply, "nextStep=" + nextStep); } ansJ = MyFunc.toJson(bestMatch);