From 572086f9ce358f00ea68ded03a0688acae900070 Mon Sep 17 00:00:00 2001 From: hxw Date: Tue, 18 Dec 2018 15:23:03 +0800 Subject: [PATCH] “添加自动跳转 --- src/entity/Condition.java | 3 ++- src/entity/JConfig.java | 28 +++++++++++++++++++++------- src/gameDesign/CharacterConstructor.java | 95 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------- src/gameDesign/ElementConstructor.java | 15 +++++++++++++-- src/gameDesign/GameUtil.java | 14 ++------------ src/gameDesign/ItemConstructor.java | 76 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------- src/gameDesign/MapConstructor.java | 95 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------- src/gameDesign/PlotConstructor.java | 82 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------ src/processing/ChatCacheController.java | 15 +++++++++++++++ src/processing/FormsPoster.java | 27 +++++++++++++++++---------- src/processing/LogWriter.java | 4 ++-- src/processing/QuestionMatcher.java | 136 +--------------------------------------------------------------------------------------------------------------------------------------- src/processing/ResponseFilter.java | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------- src/processing/UserInfoController.java | 8 ++++++-- src/processing/WorldController.java | 137 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------ src/servlet/GameDesignServlet.java | 6 ++++-- src/servlet/GetAnswerServlet.java | 38 ++++++++++++++++++++++++++++++++------ src/task/utils/BasicBotUtil.java | 126 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/task/utils/GameBotUtil.java | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 19 files changed, 782 insertions(+), 278 deletions(-) create mode 100644 src/task/utils/BasicBotUtil.java create mode 100644 src/task/utils/GameBotUtil.java diff --git a/src/entity/Condition.java b/src/entity/Condition.java index 6e59e99..bc78ed4 100644 --- a/src/entity/Condition.java +++ b/src/entity/Condition.java @@ -2,6 +2,7 @@ package com.qiwu.chatbotbackend.entity; import java.util.HashMap; import java.util.HashSet; +import java.util.LinkedHashMap; /** @@ -15,7 +16,7 @@ public class Condition { public HashSet keywordSet = new HashSet(); public HashMap> historyPremise = new HashMap>(); public HashMap> currentPremise = new HashMap>(); - public HashMap updateKnowledge = new HashMap(); + public HashMap updateKnowledge = new LinkedHashMap(); public String[] answer = {"",}; public String nextStep = ""; public HashMap featureMap = new HashMap(); diff --git a/src/entity/JConfig.java b/src/entity/JConfig.java index d20ddea..93a5122 100644 --- a/src/entity/JConfig.java +++ b/src/entity/JConfig.java @@ -251,16 +251,30 @@ public class JConfig implements Cloneable{ StringBuffer sb = new StringBuffer(); String varName = "", varValue = "", knowledgeStr; Iterator iit = knowledge.keySet().iterator(); + Boolean delayUpdateFollowerLocation = false; + String delayUpdateFollowerLocationValue = "", delayUpdateFollowerLocationKey = ""; while (iit.hasNext()) { varName = iit.next(); varValue = knowledge.get(varName); - sb.append("-<-" + varName + ":" + varValue); + + if(varValue.startsWith("updateFollowerLocation")){ + delayUpdateFollowerLocation = true; + delayUpdateFollowerLocationKey = varName; + delayUpdateFollowerLocationValue = varValue; + continue; + } + sb.append("-<-").append(varName).append(":").append(varValue); + } if (!extraKL.equals("")) { sb.append("-<-" + extraKL); } + if(delayUpdateFollowerLocation){ + sb.append("-<-").append(delayUpdateFollowerLocationKey).append(":").append(delayUpdateFollowerLocationValue); + } + if (sb.length() > 0) knowledgeStr = "updateKnowledge" + sb.toString(); else @@ -449,11 +463,11 @@ public class JConfig implements Cloneable{ JConfig jConfig2 = (JConfig) jConfig.clone(); - if(jConfig.getHisPremise().equals(" ")) - jConfig.setHisPremise("临时变量condition::match-Include=+null"); - else - jConfig.setHisPremise(jConfig.getjHisPremise() + ",临时变量condition::match-Include=+null"); - jConfig.setConfigName(name, true); +// if(jConfig.getHisPremise().equals(" ")) +// jConfig.setHisPremise("临时变量condition::match-Include=+null"); +// else +// jConfig.setHisPremise(jConfig.getjHisPremise() + ",临时变量condition::match-Include=+null"); +// jConfig.setConfigName(name, true); if(jConfig2.getUpdateKnowledge().equals("")) jConfig2.setUpdateKnowledge("process-nextStep:var={临时变量condition-2}"); @@ -462,7 +476,7 @@ public class JConfig implements Cloneable{ jConfig2.setConfigName(name, true); - jConfigList.add(jConfig); + //jConfigList.add(jConfig); jConfigList.add(jConfig2); } diff --git a/src/gameDesign/CharacterConstructor.java b/src/gameDesign/CharacterConstructor.java index e46a303..7d0d39a 100644 --- a/src/gameDesign/CharacterConstructor.java +++ b/src/gameDesign/CharacterConstructor.java @@ -5,6 +5,7 @@ import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.entity.JConfig; import com.qiwu.chatbotbackend.entity.UserInfo; +import org.apache.commons.lang.StringUtils; import java.util.*; @@ -21,7 +22,7 @@ public class CharacterConstructor extends ElementConstructor { } public void construct(JSONObject gameElements, UserInfo userinfo) { - String category, name, className, description, attrName, attrValue; + String category, name, className, description, attrValue,botName = (String)gameElements.get("botName"); try { @@ -30,13 +31,14 @@ public class CharacterConstructor extends ElementConstructor { JSONArray allNPC = gameElements.getJSONArray("npc"); Map attribute = null; - Iterator attrIter = null; HashSet classSet = new HashSet(); keywordMap.putIfAbsent("npc_wenzainali", new StringBuffer()); keywordMap.putIfAbsent("npc_shishenme", new StringBuffer()); keywordMap.putIfAbsent("npc_know_exist_what", new StringBuffer()); keywordMap.putIfAbsent("npc_nums", new StringBuffer()); + keywordMap.putIfAbsent("npc_want_know_zenmezuo", new StringBuffer()); + keywordMap.putIfAbsent("talker_zhiwen", new StringBuffer()); //与物品属性查询相关的所有condition String attrRelateConditions[] = {"nums", "shishenme"}; @@ -46,42 +48,65 @@ public class CharacterConstructor extends ElementConstructor { String locationRelateConditions[] = {"wenzainali"}; + //与说话的人相关的condition + String talkerRelateConditions[] = {"zhiwen"}; - //在condition的三元组中添加与NPC相关的关键词 - StringBuffer classKeywords = new StringBuffer(); + //如何找到×××××× ,这样的condition + String findRelateConditions[] = {"want_know_zenmezuo"}; + String findPattern = keywordMap.get("find_pattern").toString(); + + + + String classPattern = keywordMap.get("npc_class_pattern").toString(); for (JSONObject character : allNPC.toJavaList(JSONObject.class)) { name = (String) character.get("name"); + List nameList = new ArrayList(); + nameList.add(name); //添加词性 - if(!name.equals("")) - POS.append("=" + name + "|人名\r\n"); className = (String) character.get("class"); - if(!className.equals("")) - POS.append("=" + className + "|人名\r\n"); + appendPOS(POS, name, "人名"); + appendPOS(POS, className, "人名"); + + keywordMap.get("npc_want_know_zenmezuo").append(findPattern.replace("name", name)); + keywordMap.get("npc_" + locationRelateConditions[0]).append(pattern1.replace("name", name)); + + //添加别名 + if(character.containsKey("nickname")){ + for(String nickname:JSONArray.parseArray(character.getJSONArray("nickname").toJSONString(), String.class)){ + if(!nickname.equals("")) { + appendPOS(POS, nickname, "人名"); + nameList.add(nickname); + keywordMap.get("npc_want_know_zenmezuo").append(findPattern.replace("name", nickname)); + keywordMap.get("npc_" + locationRelateConditions[0]).append(pattern1.replace("name", nickname)); + } + } + } + //添加类名称 if (!classSet.contains(className)) { classSet.add(className); - classKeywords.append("+周围:" + className + "+附近:" + className); + keywordMap.get("npc_know_exist_what").append(classPattern.replace("name", className)); } attribute = gameElements.toJavaObject(character.getJSONObject("attr"), Map.class); - attrIter = attribute.keySet().iterator(); - keywordMap.get("npc_" + locationRelateConditions[0]).append(pattern1.replace("name", name)); + for(String attrName:attribute.keySet()){ + + + appendPOS(POS, attrName, "名词"); + + for(String NPCName:nameList) { - while (attrIter.hasNext()) { - attrName = attrIter.next(); - if(!attrName.equals("")) - POS.append("=" + attrName + "|名词\r\n"); - attrValue = attribute.get(attrName); - for(String condition: attrRelateConditions){ - keywordMap.get("npc_" + condition).append("+" + attrName + ":" + attrValue); + for (String condition : attrRelateConditions) { + keywordMap.get("npc_" + condition).append("+").append(NPCName).append(":").append(attrName); + } } } @@ -109,7 +134,8 @@ public class CharacterConstructor extends ElementConstructor { for(String conditionName: attrRelateConditions){ jConfig = new JConfig( conditionName + "::match-Include=" + keywordMap.get("npc_" + conditionName), " ", - "match,return-0", "【{" + PlotConstructor.ASSISTANT + "-2}】" + "{npc_query-2}", "yaobuyao", "npc_query:queryAttrByNPCName:" + conditionName + "match,return-0", "【{" + PlotConstructor.ASSISTANT + "-2}】" + "{npc_query-2}", "yaobuyao", + "npc_query:queryAttrByNPCName:" + conditionName ); JConfig.activateCopy(jConfig, jConfigList, "npc"); } @@ -118,12 +144,39 @@ public class CharacterConstructor extends ElementConstructor { for (String conditionName : classRelateConditions) { jConfig = new JConfig( - conditionName + "::match-Include=" + classKeywords, " ", - "match,return-0", "【{" + PlotConstructor.ASSISTANT + "-2}】" + "{npc_query-2}", "yaobuyao", "npc_query:queryAroundNpcByClassName:" + conditionName + conditionName + "::match-Include=" + keywordMap.get("npc_" + conditionName), " ", + "match,return-0", "【{" + PlotConstructor.ASSISTANT + "-2}】" + "{npc_query-2}", "yaobuyao", + "npc_query:queryAroundNpcByClassName:" + conditionName ); JConfig.activateCopy(jConfig, jConfigList, "npc"); //jConfigList.add(jConfig); } + + //根据类名查询周围所有实例 + for (String conditionName : findRelateConditions) { + jConfig = new JConfig( + conditionName + "::match-Include=" + keywordMap.get("npc_" + conditionName).toString(), " ", + "match,return-0", + "【{" + PlotConstructor.ASSISTANT + "-2}】" +"{npc_query-2}", + " ", + "npc_query:queryFindNPCWay:" + conditionName + ); + JConfig.activateCopy(jConfig, jConfigList, "npc"); + } + + //查询说话的人 + for (String conditionName : talkerRelateConditions) { + jConfig = new JConfig( + conditionName + "::match-Include=" + keywordMap.get("talker_" + conditionName).toString().replace("botname", botName), " ", + "match,return-0", + "{npc_query-2}", + " ", + "npc_query:queryLastTalker:" + ); + JConfig.activateCopy(jConfig, jConfigList, "npc"); + } + + }catch (Exception e){ operationStatus = 0; message = "NPC接口处理出现异常"; diff --git a/src/gameDesign/ElementConstructor.java b/src/gameDesign/ElementConstructor.java index a2403a5..8bff6ba 100644 --- a/src/gameDesign/ElementConstructor.java +++ b/src/gameDesign/ElementConstructor.java @@ -83,7 +83,7 @@ public class ElementConstructor { } - public void parseKeyword(JSONObject config, Map> relationKeywords, HashSet exceptRelation){ + public void parseKeyword(JSONObject config, Map> relationKeywords, HashSet exceptRelation, String botName){ String conditionName, pair[]; for(Map premise:JSONArray.parseArray(config.getJSONArray("currentPremiseList").toJSONString(), Map.class)){ conditionName = (String) premise.get("actionName"); @@ -97,7 +97,7 @@ public class ElementConstructor { relationKeywords.put(conditionName + "_tail", new HashSet()); } - premise.put("keywords", ((String)premise.get("keywords")).replace("qiwu", "#visitorname")); + premise.put("keywords", ((String)premise.get("keywords")).replace("qiwu", "#visitorname").replace(botName, "#botname")); for (String keyword : ((String) premise.get("keywords")).split("\\+")) { @@ -138,4 +138,15 @@ public class ElementConstructor { } + + public void appendPOS(StringBuffer POS, String name, String tag){ + if(!name.equals("")) { + POS.append("="); + POS.append(name); + POS.append("|"); + POS.append(tag); + POS.append("\n"); + } + } + } diff --git a/src/gameDesign/GameUtil.java b/src/gameDesign/GameUtil.java index 09ef829..cb04909 100644 --- a/src/gameDesign/GameUtil.java +++ b/src/gameDesign/GameUtil.java @@ -21,20 +21,10 @@ public class GameUtil { } public void gamePreprocessing(LogWriter logWriter){ - //将要去的地点的别名替换为真名 - String conditionList[] = {"yaobuyao", "want_know_zenmezuo"}; - for(String conditionName: conditionList) { + } - if (!curInfoPoint.get(conditionName).equals("") && !curInfoPoint.get(conditionName).equals("unknown")) { - String info = curInfoPoint.get(conditionName); - String destination = info.split(":")[1]; - String site = historyInfoPoint.get("site"); - String newInfo = info.replace(destination, worldController.findLocationName(gameEnv, destination, site)); + public void gamePostprocessing(LogWriter logWriter){ - logWriter.record(conditionName + ": 将’" + info + "‘替换为‘" + newInfo + "'", 1); - curInfoPoint.put(conditionName, newInfo); - } - } } } diff --git a/src/gameDesign/ItemConstructor.java b/src/gameDesign/ItemConstructor.java index c6e2546..7b8f713 100644 --- a/src/gameDesign/ItemConstructor.java +++ b/src/gameDesign/ItemConstructor.java @@ -5,6 +5,7 @@ import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.entity.JConfig; import com.qiwu.chatbotbackend.entity.UserInfo; +import org.apache.commons.lang.StringUtils; import java.util.*; @@ -38,11 +39,14 @@ public class ItemConstructor extends ElementConstructor { keywordMap.putIfAbsent("item_shishenme", new StringBuffer()); keywordMap.putIfAbsent("item_know_exist_what", new StringBuffer()); keywordMap.putIfAbsent("item_nums", new StringBuffer()); + keywordMap.putIfAbsent("item_want_know_zenmezuo", new StringBuffer()); //与物品属性查询相关的所有condition String attrRelateConditions[] = {"nums", "shishenme"}; + String ownRelateConditions[] = {"rencheng"}; + //与物品类查询相关的所有condition String classRelateConditions[] = {"know_exist_what" }; @@ -54,36 +58,50 @@ public class ItemConstructor extends ElementConstructor { StringBuffer classKeywords = new StringBuffer(); + String classPattern = keywordMap.get("item_class_pattern").toString(); for (JSONObject good : goods.toJavaList(JSONObject.class)) { name = (String) good.get("name"); + List nameList = new ArrayList(); + nameList.add(name); + //添加词性 - if(!name.equals("")) - POS.append("=" + name + "|名词\r\n"); className = (String) good.get("class"); - if(!className.equals("")) - POS.append("=" + className + "|名词\r\n"); - + appendPOS(POS, name, "名词"); + appendPOS(POS, className, "名词"); + keywordMap.get("item_want_know_zenmezuo").append(findPattern.replace("name", name)); + keywordMap.get("item_" + locationRelateConditions[0]).append(pattern1.replace("name", name)); + if(good.containsKey("nickname")){ + for(String nickname:JSONArray.parseArray(good.getJSONArray("nickname").toJSONString(), String.class)){ + if(!nickname.equals("")) { + appendPOS(POS, nickname, "名词"); + nameList.add(nickname); + keywordMap.get("item_want_know_zenmezuo").append(findPattern.replace("name", nickname)); + keywordMap.get("item_" + locationRelateConditions[0]).append(pattern1.replace("name", nickname)); + } + } + } - keywordMap.get("item_" + locationRelateConditions[0]).append(pattern1.replace("name", name)); - //添加所有物品类别 + //添加类名称 if (!classSet.contains(className)) { classSet.add(className); - //添加周围有什么士兵等关于类别的关键词 - classKeywords.append("+周围:" + className + "+附近:" + className); + keywordMap.get("item_know_exist_what").append(classPattern.replace("name", className)); } - attribute = gameElements.toJavaObject(good.getJSONObject("attr"), Map.class); + attribute = gameElements.toJavaObject(good.getJSONObject("attr"), Map.class); for(String attrName: attribute.keySet()){ - if(!attrName.equals("")) - POS.append("=" + attrName + "|名词\r\n"); - attrValue = attribute.get(attrName); - for(String condition: attrRelateConditions){ - keywordMap.get("item_" + condition).append("+" + name + ":" + attrName); + + appendPOS(POS, attrName, "名词"); + + for(String itemName:nameList) { + + for (String condition : attrRelateConditions) { + keywordMap.get("item_" + condition).append("+" + itemName + ":" + attrName); + } } } @@ -101,7 +119,6 @@ public class ItemConstructor extends ElementConstructor { "goods_query:queryLocationByConditionName:" + conditionName ); JConfig.activateCopy(jConfig, jConfigList, "item"); - //jConfigList.add(jConfig); jConfig = new JConfig( conditionName + "::match-Include=" + keywordMap.get("item_" + conditionName).toString(), " ", "match,return-0", @@ -113,7 +130,6 @@ public class ItemConstructor extends ElementConstructor { } - //根据根据物品名字和属性查询属性值 for (String conditionName : attrRelateConditions) { jConfig = new JConfig( @@ -138,9 +154,35 @@ public class ItemConstructor extends ElementConstructor { ); JConfig.activateCopy(jConfig, jConfigList, "item"); } + + //根据类名查询周围所有实例 + for (String conditionName : ownRelateConditions) { + jConfig = new JConfig( + conditionName + "::match-Include=" + keywordMap.get("item_" + conditionName).toString(), " ", + "match,return-0", + "【{" + PlotConstructor.ASSISTANT + "-2}】" +"{goods_query-2}", + " ", + "goods_query:queryPlayerItems:" + conditionName + ); + JConfig.activateCopy(jConfig, jConfigList, "item"); + } + + //根据类名查询周围所有实例 + for (String conditionName : findRelateConditions) { + jConfig = new JConfig( + conditionName + "::match-Include=" + keywordMap.get("item_" + conditionName).toString(), " ", + "match,return-0", + "【{" + PlotConstructor.ASSISTANT + "-2}】" +"{goods_query-2}", + " ", + "goods_query:queryFindItemWay:" + conditionName + ); + JConfig.activateCopy(jConfig, jConfigList, "item"); + } + } catch(Exception e){ operationStatus = 0; message = "物品处理出现异常"; + e.printStackTrace(); return; } diff --git a/src/gameDesign/MapConstructor.java b/src/gameDesign/MapConstructor.java index 53066a5..1caa81a 100644 --- a/src/gameDesign/MapConstructor.java +++ b/src/gameDesign/MapConstructor.java @@ -138,6 +138,12 @@ public class MapConstructor extends ElementConstructor { script.put("WE_HAVE", "我们有[物品列表]"); if(!script.containsKey("GET_NPC_ATTR")) script.put("GET_NPC_ATTR", "[人名]的[属性名]是[属性值]"); + if(!script.containsKey("INNER_PEOPLE")) + script.put("INNER_PEOPLE", "里面有[人物列表]"); + if(!script.containsKey("WHO_YOU_ARE")) + script.put("WHO_YOU_ARE", "我是[人名]"); + if(!script.containsKey("TASK_DESCRIPTION")) + script.put("TASK_DESCRIPTION", "我们的任务是[任务描述]"); @@ -158,14 +164,17 @@ public class MapConstructor extends ElementConstructor { 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(); - generateSurroundPlace(); + generateWantToThere(floyd.pathMatirx, floyd.preTable, gameElements, keywordMap); + generateWhereCanIgo(floyd.pathMatirx, floyd.preTable, gameElements, keywordMap); + generateWhereIam(gameElements, userName, keywordMap); + generateHowToThere(floyd.pathMatirx, floyd.preTable, gameElements, keywordMap); + generateSurroundingItem(keywordMap); + generateSurroundingPeople(keywordMap); + generateSurroundThings(keywordMap); + generateSurroundPlace(keywordMap); + generateWeHave(keywordMap); + generateInnerPeople(keywordMap); + generateTaskDescription(keywordMap); } catch(Exception e){ @@ -182,7 +191,7 @@ public class MapConstructor extends ElementConstructor { /** * 生成‘我在哪里’所需要的配置文件 */ - public void generateWhereIam(JSONObject gameElements, String botAccount) { + public void generateWhereIam(JSONObject gameElements, String botAccount, Map keywordMap) { String conditionNameList[] = {"zainali", "wenzainali"}; String conditionKeywords = ""; @@ -210,7 +219,7 @@ public class MapConstructor extends ElementConstructor { /** * 生成‘怎么去哪里’所需要的配置文件 */ - public void generateHowToThere(int[][] pathMatirx, int[][] preTable, JSONObject gameElements) { + public void generateHowToThere(int[][] pathMatirx, int[][] preTable, JSONObject gameElements, Map keywordMap) { String conditionName = "want_know_zenmezuo"; StringBuffer placeKeywords = new StringBuffer(); @@ -281,7 +290,7 @@ public class MapConstructor extends ElementConstructor { /** * 生成‘我能去哪里’所需要的配置文件 */ - public void generateWhereCanIgo(int[][] pathMatirx, int[][] preTable, JSONObject gameElements) { + public void generateWhereCanIgo(int[][] pathMatirx, int[][] preTable, JSONObject gameElements, Map keywordMap) { String conditionName = "choose_gowhere"; String conditionKeywords = keywordMap.get("map_" + conditionName).toString(); @@ -302,7 +311,7 @@ public class MapConstructor extends ElementConstructor { /** * 生成‘我要去那里’所需要的配置文件 */ - public void generateWantToThere(int[][] pathMatirx, int[][] preTable, JSONObject gameElements) { + public void generateWantToThere(int[][] pathMatirx, int[][] preTable, JSONObject gameElements, Map keywordMap) { String placeA, placeB, descriptionB, text, pathNode, lastTaskCondition, lastTaskReply; String conditionName = "yaobuyao"; String conditionKeywords = "地点"; @@ -387,7 +396,7 @@ public class MapConstructor extends ElementConstructor { } - public void generateSurroundingPeople(){ + public void generateSurroundingPeople(Map keywordMap){ String conditionName = "know_exist_what"; String conditionKeywords = keywordMap.get("people_" + conditionName).toString(); @@ -399,7 +408,7 @@ public class MapConstructor extends ElementConstructor { } - public void generateSurroundingItem(){ + public void generateSurroundingItem(Map keywordMap){ String conditionName = "know_exist_what"; String conditionKeywords = keywordMap.get("item_" + conditionName).toString(); @@ -412,7 +421,7 @@ public class MapConstructor extends ElementConstructor { } - public void generateSurroundThings(){ + public void generateSurroundThings(Map keywordMap){ String conditionName = "know_exist_what_mohu"; String conditionKeywords = keywordMap.get("things_" + conditionName).toString(); @@ -424,13 +433,65 @@ public class MapConstructor extends ElementConstructor { } - public void generateSurroundPlace(){ + public void generateSurroundPlace(Map keywordMap){ String conditionName = "know_exist_what"; String conditionKeywords = keywordMap.get("place_" + conditionName).toString(); jConfig = new JConfig( conditionName + "::match-Include=" + conditionKeywords, " ", - "match,return-0", "【{" + PlotConstructor.ASSISTANT + "-2}】" + "{map_reply-2}", " ", "map_reply:queryCanGoBySite:" + "match,return-0", "【{" + PlotConstructor.ASSISTANT + "-2}】" + "{map_reply-2}", " ", "map_reply:queryAroundPlace:" + ); + jConfig.setNextStepStatus("return-0"); + JConfig.activateCopy(jConfig, jConfigList, "map"); + + } + + public void generateWeHave(Map keywordMap){ + String conditionName = "know_exist_what_mohu"; + String conditionKeywords = keywordMap.get("we_have_" + conditionName).toString(); + + jConfig = new JConfig( + conditionName + "::match-Include=" + conditionKeywords, " ", + "match,return-0", "【{" + PlotConstructor.ASSISTANT + "-2}】" + "{goods_reply-2}", " ", "goods_reply:queryPlayerItems:" + ); + jConfig.setNextStepStatus("return-0"); + JConfig.activateCopy(jConfig, jConfigList, "map"); + + } + + public void generateInnerPeople(Map keywordMap){ + + + //与里面有谁相关的condition + String innerNPCRelateConditions[] = {"shishui"}; + + keywordMap.putIfAbsent("inner_shishui", new StringBuffer()); + String conditionName = "shishui"; + String conditionKeywords = keywordMap.get("inner_" + conditionName).toString(); + + + jConfig = new JConfig( + conditionName + "::match-Include=" + conditionKeywords, " ", + "match,return-0", "【{" + PlotConstructor.ASSISTANT + "-2}】" + "{map_reply-2}", " ", "map_reply:queryInnerNpcBySite:" + ); + jConfig.setNextStepStatus("return-0"); + JConfig.activateCopy(jConfig, jConfigList, "map"); + + } + + public void generateTaskDescription(Map keywordMap){ + + + //与里面有谁相关的condition + String innerNPCRelateConditions[] = {}; + + keywordMap.putIfAbsent("task_shishenme", new StringBuffer()); + String conditionName = "shishenme"; + String conditionKeywords = keywordMap.get("task_" + conditionName).toString(); + + jConfig = new JConfig( + conditionName + "::match-Include=" + conditionKeywords, " ", + "match,return-0", "【{" + PlotConstructor.ASSISTANT + "-2}】" + "{map_reply-2}", " ", "map_reply:queryTaskDescription:" ); jConfig.setNextStepStatus("return-0"); JConfig.activateCopy(jConfig, jConfigList, "map"); diff --git a/src/gameDesign/PlotConstructor.java b/src/gameDesign/PlotConstructor.java index 45963cd..fb19096 100644 --- a/src/gameDesign/PlotConstructor.java +++ b/src/gameDesign/PlotConstructor.java @@ -18,6 +18,9 @@ import static com.qiwu.chatbotbackend.processing.FormsPoster.QA_URL; public class PlotConstructor extends ElementConstructor { public static String ASSISTANT = "globalVariable_默认_智能助手"; + public static String TASK_DESCRIPTION = "globalVariable_默认_任务"; + + public static String TALKER_PATTERN = "【%s】"; String GAME_STEP_FORMAT = "%s_plot_%s"; JSONArray plots = null; @@ -76,12 +79,18 @@ public class PlotConstructor extends ElementConstructor { varInitialMap.put(start, "1"); + + + } else { System.out.println("start剧情不存在"); operationStatus = 0; message = "开始剧情不存在,请到剧情列表设置"; return; } + + + } catch(Exception e){ operationStatus = 0; message = "地图接口处理出现异常"; @@ -131,9 +140,10 @@ public class PlotConstructor extends ElementConstructor { */ public void BFSGenerate4(JSONObject root, UserInfo userinfo, JSONObject jsonObject) { String id, rootId = (String) root.get("id"), adjId, nextId, parentId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName = "yaobuyao", - nextUnknownText, curUnknownText, nextCondition, location, nextLocation, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition, reply; - boolean newBranch, manyParent; + nextUnknownText, curUnknownText, nextCondition, location, nextLocation, jumpLocation, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition, reply; + boolean newBranch, manyParent, autoJump; JSONObject node = null, branchNode = null, adjNode = null; + StringBuffer skipText = new StringBuffer(); JSONArray branch = null; @@ -192,12 +202,14 @@ public class PlotConstructor extends ElementConstructor { id = (String) node.get("id"); parentId = (String) node.get("parentId"); location = ((String) node.get("place")).split("\\+")[0]; + jumpLocation = location; conditionName = (String) node.get("conditionName"); curUnknownText = (String) node.get("nextUnknownText"); taskLineName = "任务线_" + location + "进度"; conditionDescription.put(id, "剧情" + id + "状态"); varInitialMap.put(id ,""); nextUnknownText = ""; + skipText = new StringBuffer(); //本任务线的最后一个condition和本任务线的最后一个回答 @@ -220,14 +232,44 @@ public class PlotConstructor extends ElementConstructor { //当两次出现unknown时给用户一下候选项 keywordOptions = ""; + String jumpNextNextId, jumpNextNextLocation; + for (int i = 0; i < branchSize; i++) { branchNode = branch.getJSONObject(i); + Map updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class); + + //自动跳转到下一个剧情,因为有可能存在多步自动跳转,所以要用一个while来处理 + while(branchNode.get("autoJump") != null && (boolean)branchNode.get("autoJump") && branchNode.get("nextPlotId") != null && !branchNode.get("nextPlotId").equals("")){ + nextId = (String)branchNode.get("nextPlotId"); + JSONObject jumpNextNode = id2j.get(nextId); + JSONObject jumpBranchNode = jumpNextNode.getJSONArray("branch").getJSONObject(0); + + skipText.append((String)jumpBranchNode.get("reply")); + Map newUpdateKnowledge = jumpBranchNode.getJSONObject("updateKnowledge"); + updateKnowledge.putAll(newUpdateKnowledge); + + + jumpNextNextId = (String)jumpBranchNode.get("nextPlotId"); + + if(jumpNextNextId != null && !jumpNextNextId.equals("")){ + jumpNextNextLocation = (String)id2j.get(jumpNextNextId).get("place"); + + jumpLocation = jumpNextNextLocation; + updateKnowledge.put("site", jumpNextNextLocation); + updateKnowledge.put("npc_update", "updateFollowerLocation:" + jumpNextNextLocation); + + } + + branchNode.put("autoJump", jumpBranchNode.get("autoJump")); + branchNode.put("nextPlotId", jumpNextNextId); + + } nextId = (String) branchNode.get("nextPlotId"); reply = (String)branchNode.get("reply"); - Map updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class); + if(updateKnowledge.containsKey("unknownText")) nextUnknownText = updateKnowledge.get("unknownText"); else @@ -290,6 +332,11 @@ public class PlotConstructor extends ElementConstructor { * 主角不随剧情移动+当前条件为空+去沙滩 * 1、沙滩无剧情 * 2、沙滩有剧情 + * + * 5. 地点变化 + * 1. 当前所处地点 + * 2. 下一步剧情所处地点(包含自动跳转的情况) + * 3. 自动跳转完成后的地点 */ //如果主角的位置随着剧情移动 @@ -297,7 +344,9 @@ public class PlotConstructor extends ElementConstructor { extraUK += "-<-site:" + nextLocation + "-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextId); }else { - if(!location.equals(nextLocation)){ + + //如果在剧情中存在自动跳转的情况,那么应该比较自动跳转完成后的地点喝下一步剧情的地点是否相同 + if(!jumpLocation.equals(nextLocation)){ if(curUnknownText.equals("")) reply = "请到" + nextLocation; //如果当前地点和下一步剧情地点不同,要提示 @@ -313,7 +362,7 @@ public class PlotConstructor extends ElementConstructor { "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, + "match", (String)branchNode.get("reply") + skipText , (String) nextCondition, "-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextId) + "-<-unknownText:" + nextUnknownText + "-<-site:" + nextLocation + "-<-npc_update:updateFollowerLocation:"+ nextLocation ); @@ -342,7 +391,7 @@ public class PlotConstructor extends ElementConstructor { JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class), updateKnowledge, "", extraHP, extraUK, - "match", reply, (String) nextCondition, "1" + "match", reply + skipText, (String) nextCondition, "1" ); @@ -378,22 +427,6 @@ public class PlotConstructor extends ElementConstructor { } - - - //对于unknown的特殊处理 - //对于unknown的特殊处理 -// if (curUnknownText.equals("")) { -// jConfig = new JConfig( -// conditionName + "::match-Include=unknown", -// "任务线_" + location + "进度::match-Include=" + parentId, -// "match,return-0,post::gameQA(" + CHITCHAT_URL + ")", -// " ", -// " ", -// "" -// ); -// jConfigList.add(jConfig); -// } - } @@ -417,7 +450,7 @@ public class PlotConstructor extends ElementConstructor { jConfig = new JConfig( - " ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match", "{common_answer-2}, {临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" + " ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" ); jConfig.setStatus("sleeping"); jConfig.setConfigName("queryskip2",false); @@ -486,8 +519,9 @@ public class PlotConstructor extends ElementConstructor { jConfigList.add(jConfig); + //由于剧情跳转时地点可能发生变化, qa问答的句子可能因为npc不再同一位置而被过滤掉,所以将common_answer的字符串合并放在postprocessing中 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", "" ," ", "" ); jConfig.setStatus("sleeping"); jConfig.setConfigName("common_answer",false); diff --git a/src/processing/ChatCacheController.java b/src/processing/ChatCacheController.java index 1bc456b..3b5f86d 100644 --- a/src/processing/ChatCacheController.java +++ b/src/processing/ChatCacheController.java @@ -308,6 +308,21 @@ public class ChatCacheController { return false; } + public static synchronized boolean deleteUnuseChatCache(String chatKey, ServletContext context) throws Exception { + try { + System.out.println("移除----------------------------"); + HashMap chatCacheHashMap = (HashMap)context.getAttribute("chatCache"); + chatCacheHashMap.remove(chatKey); + + } catch(Exception e){ + e.printStackTrace(); + return false; + } + + return true; + } + + } diff --git a/src/processing/FormsPoster.java b/src/processing/FormsPoster.java index 27ea26f..c577522 100644 --- a/src/processing/FormsPoster.java +++ b/src/processing/FormsPoster.java @@ -193,27 +193,34 @@ public class FormsPoster { System.out.println(jobj.toJSONString()); if((Integer)jobj.get("post_status") == 1){ if(jobj.getJSONArray("qa_candidates") != null && jobj.get("qa_status").equals("OK")){ - historyInfoPoint.put("common_answer", "未找到匹配"); + historyInfoPoint.put("common_answer", ""); historyInfoPoint.put("qa_score", "0"); historyInfoPoint.put("qa_status", "OK"); List candidates = JSON.toJavaObject(jobj.getJSONArray("qa_candidates"), List.class); for(JSONArray pair:candidates){ - List textscore = JSON.toJavaObject(pair, List.class); + List textscore = JSON.toJavaObject(pair, List.class); Pattern findTalker = Pattern.compile(TALKER); - Matcher m = findTalker.matcher(textscore.get(0)); - if(m.find()) { - npc = m.group(1); - if (worldController.worldOperation(gameEnv, "npc_query", "queryLocationByNPCName:" + npc, curInfoPoint, historyInfoPoint).equals( - userInfo.varInitialMap.get("FIND_NPC_LOCATION").replace("[人名]", npc).replace("[地点]", historyInfoPoint.get("site")))){ - historyInfoPoint.put("common_answer", textscore.get(0)); + + + if((Integer)textscore.get(1) > 90) { + Matcher m = findTalker.matcher((String)textscore.get(0)); + if (m.find()) { + npc = m.group(1); + + if ((ResponseFilter.sameLocation((String)textscore.get(0), curInfoPoint, historyInfoPoint, gameEnv, worldController, historyInfoPoint.get("site"), logWriter) == 1)) { + historyInfoPoint.put("common_answer", (String)textscore.get(0)); + historyInfoPoint.put("qa_score", String.valueOf(textscore.get(1))); + break; + } + } else { + logWriter.record(textscore + "没找到npc名字", 1); + historyInfoPoint.put("common_answer", ResponseFilter.appendTalker((String)textscore.get(0), curInfoPoint, historyInfoPoint, gameEnv, worldController)); historyInfoPoint.put("qa_score", String.valueOf(textscore.get(1))); break; } - }else{ - logWriter.record(textscore + "没找到npc名字",1 ); } diff --git a/src/processing/LogWriter.java b/src/processing/LogWriter.java index 5e49529..d75c98f 100644 --- a/src/processing/LogWriter.java +++ b/src/processing/LogWriter.java @@ -13,7 +13,7 @@ public class LogWriter { String PRINT_PATTERN = "[%s] %s" + "----------------------------------------------------------------------------
"; - Map colerMap = new HashMap(){ + Map colorMap = new HashMap(){ { put(0, "black"); put(1, "gray"); @@ -48,7 +48,7 @@ public class LogWriter { public void record(String text, int level){ ldt = LocalDateTime.now(); - recorder.println(String.format(PRINT_PATTERN, colerMap.get(level), ldt.format(dtf), text)); + recorder.println(String.format(PRINT_PATTERN, colorMap.get(level), ldt.format(dtf), text)); } public void writeln(){ recorder.println("
"); diff --git a/src/processing/QuestionMatcher.java b/src/processing/QuestionMatcher.java index 6509c55..5ffd347 100644 --- a/src/processing/QuestionMatcher.java +++ b/src/processing/QuestionMatcher.java @@ -54,117 +54,7 @@ public class QuestionMatcher { this.worldController = new WorldController(logWriter, userinfo); } - /** - public void updateDB(QuestionKeyWord qkw) throws SQLException { - SqlHelper helper = new SqlHelper(); - String result = helper.queryActionByKey(qkw.getChatKey()); - if(result != "empty") - //待添加 - //qkw.setActionName(result+"+"+qkw.getActionName()); - helper.updateAction(qkw); - else - helper.insertAction(qkw); - helper.destroy(); - } -*/ - - public boolean infoPointPreprocessing(Map receiveParameters, Map curInfoPoint, Map historyInfoPoint, UserInfo userinfo, ServletContext context) throws IOException { - - String return_str = "", k, botType = ""; - String receiveParameterStr = ""; - boolean debugFlag = false; - - HashSet skipSet = new HashSet() { - { - add("chat_key"); - add("action_name"); - add("bot_name"); - add("emptySet"); - add("query_text"); - } - }; - - - //输出所有actionName的值 - Iterator iit = receiveParameters.keySet().iterator(); - receiveParameterStr+= "-----------------------------------------识别数据列表-------------------------------------------
"; - while (iit.hasNext()) { - k = iit.next(); - // - receiveParameterStr += k + ": "; - curInfoPoint.put(k, receiveParameters.get(k)[0]); - - if (k.equals("debug_mode") || k.equals("debug_rule")) - debugFlag = true; - - String values[] = receiveParameters.get(k); - -// for (String v : values) { -// receiveParameterStr += v + " "; -// } - receiveParameterStr += values[0] + " " + "
"; - - - if (values[0].equals(":")) { - curInfoPoint.put(k, ""); - } - } - logWriter.record(receiveParameterStr, 0); - System.out.println(receiveParameterStr.toString()); - - //如果引擎什么信息都没识别到,那就将上一轮的nextStep(也就是当前轮的actionName)设为unknown - iit = curInfoPoint.keySet().iterator(); - boolean unknown_flag = true; - while (iit.hasNext()) { - k = iit.next(); - String values = curInfoPoint.get(k); - if (skipSet.contains(k)) - continue; - if (!values.equals("")) { - unknown_flag = false; - break; - } - } - - String currentAction = ""; - if (historyInfoPoint.containsKey("currentAction")) - currentAction = historyInfoPoint.get("currentAction"); - else if (userinfo.extraInfo.containsKey("activeAction")) { - currentAction = userinfo.extraInfo.get("activeAction"); - historyInfoPoint.put("currentAction", currentAction); - } else - currentAction = " "; - - - curInfoPoint.put("emptySet", " "); - if (historyInfoPoint.get("activeList") == null) { - historyInfoPoint.put("activeList", currentAction); - } - - if (unknown_flag && !currentAction.equals("")) { - String i = "unknown"; - curInfoPoint.put(currentAction, i); - } - - logWriter.record("historyInfoPoint:" + historyInfoPoint.toString(), 1); - - - - //根据bot类型做预处理 - if(userinfo.varInitialMap.get("botType") != null) - botType = userinfo.varInitialMap.get("botType"); - - switch (botType){ - case "game": - GameUtil util = new GameUtil(gameEnv, worldController,curInfoPoint, historyInfoPoint); - util.gamePreprocessing(logWriter); - break; - } - - - return debugFlag; - } /** @@ -217,30 +107,6 @@ public class QuestionMatcher { logWriter.record(userinfo.id2config.get(condition.id), 1); } } - /* - if (condition.status.equals("waiting") && conditionSatisfy(condition)) { - - - if (condition.featureMap.get("instantPost") != null) { - - - } - //Post后还是可以激活 - - 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 if ((condition.priority > bestMatch.priority) || (condition.priority == bestMatch.priority && condition.auxiliaryPriority > bestMatch.auxiliaryPriority)) - } else if ((condition.auxiliaryPriority > bestMatch.auxiliaryPriority) || (condition.auxiliaryPriority == bestMatch.auxiliaryPriority && condition.priority > bestMatch.priority)) { - bestMatch = condition; - logWriter.record("匹配更新为:\"" + userinfo.id2config.get(condition.id) + "\"", 2); - logWriter.writeln(); - } - } - */ } } @@ -270,7 +136,7 @@ public class QuestionMatcher { 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.substring(0,3))){ + || bestMatch.nextStep.contains(String.valueOf(condition.id)) || (!condition.configName.equals("") && bestMatch.nextStep.contains(condition.configName.substring(0,3)))){ //激活优先级先比较,但是如果激活的是无条件的就直接判断名字。 if(conditionSatisfy(condition)){ if (condition.featureMap.get("activate") != null && !condition.featureMap.containsKey("post")) { diff --git a/src/processing/ResponseFilter.java b/src/processing/ResponseFilter.java index 054cc69..6659d90 100644 --- a/src/processing/ResponseFilter.java +++ b/src/processing/ResponseFilter.java @@ -21,7 +21,7 @@ public class ResponseFilter { String botType = userInfo.varInitialMap.get("botType"), npc, finalUnknownText; - if(botType == null){ + if(botType == null || botType.equals("")){ return reply; }else if (botType.equals("game")){ @@ -31,11 +31,16 @@ public class ResponseFilter { reply = MyFunc.randStr(reply.split("~")); + if(reply.endsWith("开始游戏或者继续游戏")){ + return reply; + } + if(reply.startsWith("【" + historyInfoPoint.get(PlotConstructor.ASSISTANT)+ "】") ){ return reply; - }else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter)){ + }else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1){ return reply; - + }else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0){ + return appendTalker(reply,curInfoPoint, historyInfoPoint, gameEnv, worldController); } if(userInfo.varInitialMap.get("unknownTextList") != null){ @@ -43,9 +48,11 @@ public class ResponseFilter { for(String ans:userInfo.varInitialMap.get("unknownTextList").split("~")){ if(ans.equals("")) continue; - if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter)){ + if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1){ unknownList.add(ans); //return ans; + }else if(sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0){ + unknownList.add(appendTalker(ans,curInfoPoint, historyInfoPoint, gameEnv, worldController)); } } if(unknownList.size() > 0){ @@ -61,9 +68,11 @@ public class ResponseFilter { for(String ans:finalUnknownText.split("~")){ if(ans.equals("")) continue; - if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter)){ + if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1){ finalUnknownList.add(ans); //return ans; + }else if(sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0){ + finalUnknownList.add(appendTalker(ans,curInfoPoint, historyInfoPoint, gameEnv, worldController)); } } if(finalUnknownList.size() > 0){ @@ -78,22 +87,62 @@ public class ResponseFilter { return "找不到匹配文本"; } - static Boolean sameLocation(String reply, Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController, String site, LogWriter logWriter){ - String npc; + + + static Matcher findTalker(String reply){ Pattern findTalker = Pattern.compile(TALKER); Matcher m = findTalker.matcher(reply); + + return m; + } + /** + * 查看回答文本的说话这是否在当前地点 + * 0:没有说话者 + * 1:说话者在当前地点 + * 2:说话者不在当前地点 + * @param reply + * @param curInfoPoint + * @param historyInfoPoint + * @param gameEnv + * @param worldController + * @param site + * @param logWriter + * @return + */ + static Integer sameLocation(String reply, Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController, String site, LogWriter logWriter){ + String npc, location; + + Matcher m = findTalker(reply); + int flag = 1; 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 ); + location = worldController.worldOperation(gameEnv, "npc_query", "queryLocationByNPCName:" + npc, curInfoPoint, historyInfoPoint); + if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){ + logWriter.record("\"" + reply + "\":匹配", 1); + flag = 1; + }else { + logWriter.record("\"" + reply + "\":" + npc +"不在" + site + ",跳过",1 ); + flag = 2; } }else{ - logWriter.record(reply + "没有npc名,直接选中",1 ); - return true; + logWriter.record("\"" + reply + "\":没有npc名",1 ); + flag = 0; } + return flag; - return false; } + + static String appendTalker(String reply, Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController){ + + List npcList = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site")); + String npc = ""; + if(npcList.size() != 0) + npc = MyFunc.randStr(npcList); + else + npc = historyInfoPoint.get(PlotConstructor.ASSISTANT); + + return "【" + npc + "】" + reply; + + } + } diff --git a/src/processing/UserInfoController.java b/src/processing/UserInfoController.java index 12016d6..4eada2a 100644 --- a/src/processing/UserInfoController.java +++ b/src/processing/UserInfoController.java @@ -86,11 +86,15 @@ public class UserInfoController { public static Condition buildCondition(Condition condition, String line) { - String feature, url, element[], pair[], next[], cur_premises[], history_premises[], premises[], features[], firstCnditionName; + String feature, url, element[], pair[], next[], cur_premises[], history_premises[], premises[], features[], firstCnditionName,text[]; try { - line = line.split("---")[0]; + + text = line.split("---"); + line = text[0]; + if(text.length > 1 && text[1].startsWith("<-")) + line += "---" + text[1]; element = line.replace("\n", "").split("\\|=\\>\\|"); premises = element[0].split("\\|"); diff --git a/src/processing/WorldController.java b/src/processing/WorldController.java index 6d60616..e15273d 100644 --- a/src/processing/WorldController.java +++ b/src/processing/WorldController.java @@ -3,10 +3,12 @@ package com.qiwu.chatbotbackend.processing; import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.gameDesign.PlotConstructor; import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.regex.Matcher; public class WorldController { public LogWriter logWriter = null; @@ -28,6 +30,7 @@ public class WorldController { String location = "", value = ""; if(valuePair[0].startsWith("query")){ //查询专用 + String ItemName = ""; if(varName.startsWith("goods_")) { switch (valuePair[0]) { @@ -72,22 +75,54 @@ public class WorldController { case "queryLocationByConditionName": // - String NPCName = currentInfoPoint.get(valuePair[1]).split(":")[1]; - returnStr = gameEnv.queryGoodsAttrByGoodsName(NPCName, "可被询问"); + ItemName = currentInfoPoint.get(valuePair[1]).split(":")[1]; + returnStr = gameEnv.queryGoodsAttrByGoodsName(ItemName, "可被询问"); if(returnStr == null || returnStr.equals("否")){ returnStr = "没找到"; } else if(returnStr.equals("是")){ - location = gameEnv.queryGoodsAttrByGoodsName(NPCName, "location"); + location = gameEnv.queryGoodsAttrByGoodsName(ItemName, "location"); if(location == null){ returnStr = "没找到"; }else{ - returnStr = userInfo.varInitialMap.get("FIND_ITEM_LOCATION").replace("[物品名]", NPCName).replace("[地点]", location); + returnStr = userInfo.varInitialMap.get("FIND_ITEM_LOCATION").replace("[物品名]", ItemName).replace("[地点]", location); } } break; + case "queryPlayerItems": + String player = gameEnv.queryPlayerName(); + textList = gameEnv.queryGoodsByNpcName(player); + if(textList == null || textList.size() == 0) + returnStr = "什么都没有"; + else { + for (String site : textList) + returnStr += "、" + site; + + returnStr = userInfo.varInitialMap.get("WE_HAVE").replace("[物品列表]", returnStr.substring(1)); + } + + break; + + + case "queryFindItemWay": + // + ItemName = currentInfoPoint.get(valuePair[1]).split(":")[1]; + returnStr = gameEnv.queryGoodsAttrByGoodsName(ItemName, "可被询问"); + if(returnStr == null || returnStr.equals("否")){ + returnStr = "没找到"; + } else if(returnStr.equals("是")){ + location = gameEnv.queryGoodsAttrByGoodsName(ItemName, "location"); + if(location == null){ + returnStr = "没找到"; + }else{ + returnStr = userInfo.varInitialMap.get("FIND_ITEM_WAY").replace("[物品名]", ItemName).replace("[地点]", location); + } + } + + break; default: } }else if(varName.startsWith("npc_")) { + String NPCName = ""; switch(valuePair[0]){ case "queryNpcIntro": //operationFlag = gameEnv.queryNpcIntro(valuePair[1], namePair[2]); @@ -112,6 +147,7 @@ public class WorldController { case "queryLocationByNPCName": // + location = gameEnv.queryNpcAttrByNpcName(valuePair[1], "location"); if(location == null){ returnStr = "没找到"; @@ -122,7 +158,10 @@ public class WorldController { break; case "queryLocationByConditionName": // - String NPCName = currentInfoPoint.get(valuePair[1]).split(":")[1]; + NPCName = currentInfoPoint.get(valuePair[1]).split(":")[1]; + NPCName = gameEnv.getNpcNameByNickname(historyInfoPoint.get("site"), NPCName); + + System.out.println(NPCName); returnStr = gameEnv.queryNpcAttrByNpcName(NPCName, "可被询问"); if(returnStr == null || returnStr.equals("否")){ returnStr = "没找到"; @@ -136,6 +175,35 @@ public class WorldController { } break; + case "queryFindNPCWay": + + // + NPCName = currentInfoPoint.get(valuePair[1]).split(":")[1]; + returnStr = gameEnv.queryNpcAttrByNpcName(NPCName, "可被询问"); + if(returnStr == null || returnStr.equals("否")){ + returnStr = "没找到"; + } else if(returnStr.equals("是")){ + location = gameEnv.queryNpcAttrByNpcName(NPCName, "location"); + if(location == null){ + returnStr = "没找到"; + }else{ + returnStr = userInfo.varInitialMap.get("FIND_NPC_WAY").replace("[人名]", NPCName).replace("[地点]", location); + } + } + + break; + + case "queryLastTalker": + String lastTalker = "没找到npc名字"; + Matcher m = ResponseFilter.findTalker(historyInfoPoint.get("lastReply")); + while(m.find()){ + lastTalker = m.group(1); + } + + returnStr = String.format(PlotConstructor.TALKER_PATTERN, lastTalker) + userInfo.varInitialMap.get("WHO_YOU_ARE").replace("[人名]", lastTalker); + break; + + default: } @@ -290,10 +358,66 @@ public class WorldController { } } break; + case "queryAroundPlace": + if(userInfo.varInitialMap.containsKey("AROUND_PLACE")) { + format = userInfo.varInitialMap.get("AROUND_PLACE"); + }else { + format = "周围有[地点列表]"; + } + + + sites = gameEnv.queryCanGoBySite(historyInfoPoint.get("site")); + if(sites == null || sites.size() == 0) { + returnStr = "无处可去了"; + } else { + if(sites.size() > 0) { + StringBuffer text = new StringBuffer(); + + for(String site:sites){ + text.append("、" + site); + } + returnStr = format.replace("[地点列表]", text.substring(1)); + } + } + break; + case "queryInnerNpcBySite": + if(userInfo.varInitialMap.containsKey("INNER_PEOPLE")) { + format = userInfo.varInitialMap.get("INNER_PEOPLE"); + }else { + format = "里面有[人物列表]"; + } + + + sites = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site")); + if(sites == null || sites.size() == 0) + returnStr = "什么都没有"; + else { + + StringBuffer text = new StringBuffer(); + + for(String site:sites){ + text.append("、" + site); + } + + returnStr = format.replace("[人物列表]", text.substring(1)); + } + break; + + case "queryTaskDescription": + if(userInfo.varInitialMap.containsKey("TASK_DESCRIPTION")) { + format = userInfo.varInitialMap.get("TASK_DESCRIPTION"); + }else { + format = "我们的任务是[任务描述]"; + } + + + returnStr = format.replace("[任务描述]", userInfo.varInitialMap.get(PlotConstructor.TASK_DESCRIPTION)); + + break; } } - }else if(valuePair[0].startsWith("update")){ + }else if(valuePair[0].startsWith("updateFollowerLocation")){ Boolean flag = true; switch (valuePair[0]) { case "updateFollowerLocation": @@ -307,6 +431,7 @@ public class WorldController { returnStr = "更新失败"; }else{ //增删改统一使用 + logWriter.record("更新环境--varName:" + varName + "valuePair:" + valuePair[0] + ":" + valuePair[1], 1); gameEnv.CUD(varName, valuePair[0], valuePair[1]); } diff --git a/src/servlet/GameDesignServlet.java b/src/servlet/GameDesignServlet.java index 8385f04..027cb87 100644 --- a/src/servlet/GameDesignServlet.java +++ b/src/servlet/GameDesignServlet.java @@ -54,7 +54,7 @@ public class GameDesignServlet extends HttpServlet { Integer botId, projectId, dataId, returnStatus = 1; - String botAccount = null, userName, moduleName2, returnMessage = "Success"; + String botAccount = null, userName, botName, moduleName2, returnMessage = "Success"; ServletContext context = this.getServletContext(); JSONObject json = null, root = null; Boolean flag; @@ -83,6 +83,7 @@ public class GameDesignServlet extends HttpServlet { botId = (Integer)gameElements.get("botId"); botAccount = (String) gameElements.get("botAccount"); userName = (String)gameElements.get("userName"); + botName = (String)gameElements.get("botName"); @@ -159,7 +160,7 @@ public class GameDesignServlet extends HttpServlet { List jsonList = new ArrayList(); for(JConfig jConfig: constructor.getjConfigList()){ json = jConfig.toJson(constructor.getConditionDescription()); - constructor.parseKeyword(json, additionalKeywords, exceptRelation); + constructor.parseKeyword(json, additionalKeywords, exceptRelation, botName); jsonList.add(json); } @@ -180,6 +181,7 @@ public class GameDesignServlet extends HttpServlet { if(returnStatus == 1) { StringReader sr = new StringReader(mergedConfigText.toString()); BufferedReader br = new BufferedReader(sr); + //System.out.println(mergedConfigText.toString()); UserInfoController.buildUserInfo(br, userinfo, true); context.setAttribute(botAccount, userinfo); ConditionTableController.writeConfigText(botAccount, userinfo); diff --git a/src/servlet/GetAnswerServlet.java b/src/servlet/GetAnswerServlet.java index 2f02975..153b9dc 100644 --- a/src/servlet/GetAnswerServlet.java +++ b/src/servlet/GetAnswerServlet.java @@ -3,6 +3,8 @@ package com.qiwu.chatbotbackend.servlet; import com.qiwu.chatbotbackend.entity.*; import com.qiwu.chatbotbackend.gameDesign.PlotConstructor; import com.qiwu.chatbotbackend.processing.*; +import com.qiwu.chatbotbackend.task.utils.BasicBotUtil; +import com.qiwu.chatbotbackend.task.utils.GameBotUtil; import javax.servlet.ServletContext; import javax.servlet.ServletException; @@ -32,10 +34,14 @@ public class GetAnswerServlet extends HttpServlet { Map curInfoPoint = new HashMap(); Map historyInfoPoint = null; Solution bestMatch = null; + BasicBotUtil botUtil = null; Condition ansCondition = null; - String ansJ = "", return_str = "", state = "", chatKey = ""; + boolean debugFlag = false; + String ansJ = "", return_str = "", state = "", chatKey = "", botType = ""; String botName = receiveParamters.get("bot_name")[0]; + OutputStream out = response.getOutputStream(); + ServletContext context = this.getServletContext(); //如果有client_id,会用@分隔 if(!receiveParamters.get("chat_key")[0].startsWith("@")) @@ -44,10 +50,6 @@ public class GetAnswerServlet extends HttpServlet { chatKey = receiveParamters.get("chat_key")[0]; receiveParamters.get("chat_key")[0] = chatKey; - OutputStream out = response.getOutputStream(); - ServletContext context = this.getServletContext(); - boolean debugFlag = false; - LogWriter logWriter = new LogWriter(LOG_PATH, chatKey); @@ -58,12 +60,15 @@ public class GetAnswerServlet extends HttpServlet { //userinfo = process.userInfoQuery(chatKey,context); //从servlet根据用户名查询用户信息 userinfo = uiController.userInfoQuery(request.getParameter("bot_name"), context); + } catch (SQLException e) { state = NAME_MISSING_ERROR; e.printStackTrace(); } + + if(userinfo != null) { //获得用户历史信息 ChatCache chatCache = null; @@ -84,10 +89,26 @@ public class GetAnswerServlet extends HttpServlet { if(!chatCache.isReloading()) { historyInfoPoint = chatCache.getInfoPoint(); + if(userinfo.varInitialMap.get("botType") != null) + botType = userinfo.varInitialMap.get("botType"); + + + switch(botType){ + case "game": + WorldController worldController = new WorldController(logWriter,userinfo); + botUtil = new GameBotUtil(curInfoPoint, historyInfoPoint, userinfo, logWriter, worldController, chatCache.getGameEnv()); + break; + default: + botUtil = new BasicBotUtil(curInfoPoint, historyInfoPoint, userinfo, logWriter); + break; + } + + //针对不同游戏类型对信息点做预处理 + debugFlag = botUtil.preprocessing(receiveParamters, context); + //信息点预处理 QuestionMatcher matcher = new QuestionMatcher(curInfoPoint, historyInfoPoint, logWriter, userinfo, context, chatCache.getGameEnv()); - debugFlag = matcher.infoPointPreprocessing(receiveParamters, curInfoPoint, historyInfoPoint, userinfo, context); /*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/ @@ -130,6 +151,11 @@ public class GetAnswerServlet extends HttpServlet { context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); } + //针对不同游戏类型做后处理 + botUtil.postprocessing(chatKey, context, bestMatch); + + + } else { diff --git a/src/task/utils/BasicBotUtil.java b/src/task/utils/BasicBotUtil.java new file mode 100644 index 0000000..984c815 --- /dev/null +++ b/src/task/utils/BasicBotUtil.java @@ -0,0 +1,126 @@ +package com.qiwu.chatbotbackend.task.utils; + +import com.qiwu.chatbotbackend.entity.Solution; +import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.gameDesign.GameUtil; +import com.qiwu.chatbotbackend.processing.LogWriter; +import com.qiwu.chatbotbackend.processing.WorldController; + +import javax.servlet.ServletContext; +import java.io.IOException; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; + +public class BasicBotUtil { + Map curInfoPoint = null; + Map historyInfoPoint = null; + UserInfo userinfo = null; + LogWriter logWriter = null; + + + public BasicBotUtil(){}; + public BasicBotUtil(Map curInfoPoint, Map historyInfoPoint, UserInfo userinfo, LogWriter logWriter){ + this.curInfoPoint = curInfoPoint; + this.historyInfoPoint = historyInfoPoint; + this.userinfo = userinfo; + this.logWriter = logWriter; + } + + public boolean preprocessing(Map receiveParameters, ServletContext context) throws IOException { + return infoPointPreprocessing(receiveParameters, context); + + + + } + + + public boolean infoPointPreprocessing(Map receiveParameters, ServletContext context) throws IOException { + + String return_str = "", k, botType = ""; + String receiveParameterStr = ""; + boolean debugFlag = false; + + HashSet skipSet = new HashSet() { + { + add("chat_key"); + add("action_name"); + add("bot_name"); + add("emptySet"); + add("query_text"); + } + }; + + + //输出所有actionName的值 + Iterator iit = receiveParameters.keySet().iterator(); + receiveParameterStr+= "-----------------------------------------识别数据列表-------------------------------------------
"; + while (iit.hasNext()) { + k = iit.next(); + // + receiveParameterStr += k + ": "; + curInfoPoint.put(k, receiveParameters.get(k)[0]); + + if (k.equals("debug_mode") || k.equals("debug_rule")) + debugFlag = true; + + String values[] = receiveParameters.get(k); + +// for (String v : values) { +// receiveParameterStr += v + " "; +// } + receiveParameterStr += values[0] + " " + "
"; + + + if (values[0].equals(":")) { + curInfoPoint.put(k, ""); + } + } + logWriter.record(receiveParameterStr, 0); + System.out.println(receiveParameterStr.toString()); + + //如果引擎什么信息都没识别到,那就将上一轮的nextStep(也就是当前轮的actionName)设为unknown + iit = curInfoPoint.keySet().iterator(); + boolean unknown_flag = true; + while (iit.hasNext()) { + k = iit.next(); + String values = curInfoPoint.get(k); + if (skipSet.contains(k)) + continue; + if (!values.equals("")) { + unknown_flag = false; + break; + } + } + + String currentAction = ""; + if (historyInfoPoint.containsKey("currentAction")) + currentAction = historyInfoPoint.get("currentAction"); + else if (userinfo.extraInfo.containsKey("activeAction")) { + currentAction = userinfo.extraInfo.get("activeAction"); + historyInfoPoint.put("currentAction", currentAction); + } else + currentAction = " "; + + + curInfoPoint.put("emptySet", " "); + if (historyInfoPoint.get("activeList") == null) { + historyInfoPoint.put("activeList", currentAction); + } + + if (unknown_flag && !currentAction.equals("")) { + String i = "unknown"; + curInfoPoint.put(currentAction, i); + } + + logWriter.record("historyInfoPoint:" + historyInfoPoint.toString(), 1); + + + + return debugFlag; + } + + public boolean postprocessing(String chatKey, ServletContext context, Solution bestMatch){ + return true; + } +} diff --git a/src/task/utils/GameBotUtil.java b/src/task/utils/GameBotUtil.java new file mode 100644 index 0000000..4dbd448 --- /dev/null +++ b/src/task/utils/GameBotUtil.java @@ -0,0 +1,78 @@ +package com.qiwu.chatbotbackend.task.utils; + +import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; +import com.qiwu.chatbotbackend.entity.Solution; +import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.processing.ChatCacheController; +import com.qiwu.chatbotbackend.processing.LogWriter; +import com.qiwu.chatbotbackend.processing.WorldController; + +import javax.servlet.ServletContext; +import java.io.IOException; +import java.util.Map; + +public class GameBotUtil extends BasicBotUtil{ + + WorldController worldController = null; + GameEnv gameEnv = null; + + + public GameBotUtil(Map curInfoPoint, Map historyInfoPoint, UserInfo userinfo, LogWriter logWriter, WorldController worldController, GameEnv gameEnv){ + this.curInfoPoint = curInfoPoint; + this.historyInfoPoint = historyInfoPoint; + this.userinfo = userinfo; + this.logWriter = logWriter; + this.worldController = worldController; + this.gameEnv = gameEnv; + + } + + @Override + public boolean preprocessing(Map receiveParameters, ServletContext context) throws IOException { + Boolean debugFlag = infoPointPreprocessing(receiveParameters, context); + + //将要去的地点的别名替换为真名 + String conditionList[] = {"yaobuyao", "want_know_zenmezuo"}; + + for(String conditionName: conditionList) { + + if (!curInfoPoint.get(conditionName).equals("") && !curInfoPoint.get(conditionName).equals("unknown")) { + String info = curInfoPoint.get(conditionName); + String destination = info.split(":")[1]; + String site = historyInfoPoint.get("site"); + String newInfo = info.replace(destination, worldController.findLocationName(gameEnv, destination, site)); + + logWriter.record(conditionName + ": 将’" + info + "‘替换为‘" + newInfo + "'", 1); + curInfoPoint.put(conditionName, newInfo); + } + } + + String activeList[] = historyInfoPoint.get("activeList").split("\\|"); + if(activeList.length == 0){ + historyInfoPoint.put("临时变量condition", "yaobuyao"); + }else { + historyInfoPoint.put("临时变量condition", activeList[activeList.length-1]); + } + + + return debugFlag; + + } + + public boolean postprocessing(String chatKey, ServletContext context, Solution bestMatch){ + if(userinfo.varInitialMap.get("botType") != null && userinfo.varInitialMap.get("botType").equals("game") && bestMatch.getAnswer().endsWith("开始游戏或者继续游戏")){ + try { + ChatCacheController.deleteUnuseChatCache(chatKey, context); + } catch (Exception e) { + e.printStackTrace(); + } + } + String common_answer = historyInfoPoint.get("common_answer"); + if(common_answer != null && !common_answer.equals("") && !common_answer.equals("no answer")){ + bestMatch.setAnswer(common_answer + ", " + bestMatch.getAnswer()); + historyInfoPoint.put("common_answer", ""); + } + + return true; + } +} -- libgit2 0.27.1