diff --git a/src/entity/ChatCache.java b/src/entity/ChatCache.java index e5188ef..0af9b6d 100644 --- a/src/entity/ChatCache.java +++ b/src/entity/ChatCache.java @@ -69,6 +69,7 @@ public class ChatCache implements DisposableBean { gameEnv = new GameEnv(userInfo.botAccount); }catch (Exception e){ System.out.println("游戏平台初始化失败"); + e.printStackTrace(); } String k; diff --git a/src/entity/JConfig.java b/src/entity/JConfig.java index ce48592..d20ddea 100644 --- a/src/entity/JConfig.java +++ b/src/entity/JConfig.java @@ -443,7 +443,7 @@ public class JConfig implements Cloneable{ } - public static void activateCopy(JConfig jConfig, List jConfigList){ + public static void activateCopy(JConfig jConfig, List jConfigList, String name){ jConfig.setReply(jConfig.getReply() + "{临时变量reply-2}"); @@ -453,13 +453,13 @@ public class JConfig implements Cloneable{ jConfig.setHisPremise("临时变量condition::match-Include=+null"); else jConfig.setHisPremise(jConfig.getjHisPremise() + ",临时变量condition::match-Include=+null"); - jConfig.setConfigName("map", true); + jConfig.setConfigName(name, 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); + jConfig2.setConfigName(name, true); jConfigList.add(jConfig); diff --git a/src/gameDesign/CharacterConstructor.java b/src/gameDesign/CharacterConstructor.java index fc29ae7..e46a303 100644 --- a/src/gameDesign/CharacterConstructor.java +++ b/src/gameDesign/CharacterConstructor.java @@ -10,13 +10,13 @@ import java.util.*; public class CharacterConstructor extends ElementConstructor { - public CharacterConstructor(SqlHelper helper, int botId, int skipCount, String botAccount, HashSet exceptRelation, StringBuffer POS) { + public CharacterConstructor(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { super(); this.helper = helper; this.botId = botId; this.botAccount = botAccount; this.exceptRelation = exceptRelation; - this.skipCount = skipCount; + this.keywordMap = keywordMap; this.POS = POS; } @@ -24,41 +24,45 @@ public class CharacterConstructor extends ElementConstructor { String category, name, className, description, attrName, attrValue; try { + + String pattern1 = keywordMap.get("npc_location_pattern").toString(); + + JSONArray allNPC = gameElements.getJSONArray("npc"); Map attribute = null; Iterator attrIter = null; HashSet classSet = new HashSet(); - //与npc属性相关的所有condition - ArrayList relateConditions = new ArrayList() { - { - add("wenzainali"); - add("shishenme"); - } - }; - //与npc类相关的所有condition - ArrayList classRelateConditions = new ArrayList() { - { - add("know_exist_what"); - } - }; + 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()); + //与物品属性查询相关的所有condition + String attrRelateConditions[] = {"nums", "shishenme"}; - //在condition的三元组中添加与NPC相关的关键词 + //与物品类查询相关的所有condition + String classRelateConditions[] = {"know_exist_what" }; + + String locationRelateConditions[] = {"wenzainali"}; - String conditionValue = "哪里:人称", repValue; - StringBuffer keywords = new StringBuffer(); + + //在condition的三元组中添加与NPC相关的关键词 StringBuffer classKeywords = new StringBuffer(); + for (JSONObject character : allNPC.toJavaList(JSONObject.class)) { name = (String) character.get("name"); + + //添加词性 if(!name.equals("")) POS.append("=" + name + "|人名\r\n"); className = (String) character.get("class"); if(!className.equals("")) POS.append("=" + className + "|人名\r\n"); + //添加类名称 if (!classSet.contains(className)) { classSet.add(className); classKeywords.append("+周围:" + className + "+附近:" + className); @@ -67,46 +71,63 @@ public class CharacterConstructor extends ElementConstructor { attribute = gameElements.toJavaObject(character.getJSONObject("attr"), Map.class); attrIter = attribute.keySet().iterator(); - repValue = conditionValue.replace("人称", name); - keywords.append("+" + repValue); + + keywordMap.get("npc_" + locationRelateConditions[0]).append(pattern1.replace("name", name)); + 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); + } - System.out.println(name); + } } - //根据根据NPC名字和属性查询属性值 - for (String conditionName : relateConditions) { + + //根据根据NPC的名字查询地点 + for (String conditionName : locationRelateConditions) { jConfig = new JConfig( - conditionName + "::match-Include=" + keywords, " ", - "match,return-0", "【{" + PlotConstructor.ASSISTANT + "-2}】" + "{NPC_query-2}", "yaobuyao", "NPC_query:queryAttrByNPCName:" + conditionName + conditionName + "::match-Include=" + keywordMap.get("npc_" + conditionName), " ", + "match,return-0", "【{" + PlotConstructor.ASSISTANT + "-2}】" + "{npc_query-2}", "yaobuyao", "npc_query:queryLocationByConditionName:" + conditionName ); - jConfig.setAuxiliaryPriority("1"); - jConfigList.add(jConfig); - - + JConfig.activateCopy(jConfig, jConfigList, "npc"); + jConfig = new JConfig( + conditionName + "::match-Include=" + keywordMap.get("npc_" + conditionName) + "," + + "zainali::match-Keyword=" + keywordMap.get("map_zainali").toString(), " ", + "match,return-0", "【{" + PlotConstructor.ASSISTANT + "-2}】" + "{npc_query-2}", "yaobuyao", "npc_query:queryLocationByConditionName:" + conditionName + ); + JConfig.activateCopy(jConfig, jConfigList, "npc"); + //jConfigList.add(jConfig); + } + //根据根据NPC名字和属性查询属性值 + 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 + ); + JConfig.activateCopy(jConfig, jConfigList, "npc"); } + //根据根据NPC类别和地点属性查询所有NPC实例 - for (String conditionName : relateConditions) { + 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 + "match,return-0", "【{" + PlotConstructor.ASSISTANT + "-2}】" + "{npc_query-2}", "yaobuyao", "npc_query:queryAroundNpcByClassName:" + conditionName ); - jConfig.setAuxiliaryPriority("1"); - jConfigList.add(jConfig); - + JConfig.activateCopy(jConfig, jConfigList, "npc"); + //jConfigList.add(jConfig); } }catch (Exception e){ operationStatus = 0; message = "NPC接口处理出现异常"; + e.printStackTrace(); return; } } diff --git a/src/gameDesign/ElementConstructor.java b/src/gameDesign/ElementConstructor.java index bf1f0b3..a2403a5 100644 --- a/src/gameDesign/ElementConstructor.java +++ b/src/gameDesign/ElementConstructor.java @@ -16,7 +16,7 @@ public class ElementConstructor { int operationStatus = 1; - int skipCount = 0; + Map keywordMap = null; SqlHelper helper = null; HashSet exceptRelation = null; JConfig jConfig = null; @@ -97,13 +97,20 @@ public class ElementConstructor { relationKeywords.put(conditionName + "_tail", new HashSet()); } + premise.put("keywords", ((String)premise.get("keywords")).replace("qiwu", "#visitorname")); + for (String keyword : ((String) premise.get("keywords")).split("\\+")) { if(keyword.equals("")){ continue; + } else if(keyword.contains(":")){ - pair = keyword.split(":"); + pair = keyword.split(":",2); + + if(pair[1].equals("")) + continue; + relationKeywords.get(conditionName + "_head").add(pair[0]); relationKeywords.get(conditionName + "_tail").add(pair[1]); diff --git a/src/gameDesign/GameUtil.java b/src/gameDesign/GameUtil.java new file mode 100644 index 0000000..09ef829 --- /dev/null +++ b/src/gameDesign/GameUtil.java @@ -0,0 +1,40 @@ +package com.qiwu.chatbotbackend.gameDesign; + +import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; +import com.qiwu.chatbotbackend.processing.LogWriter; +import com.qiwu.chatbotbackend.processing.WorldController; + +import java.util.Map; + +public class GameUtil { + + public GameEnv gameEnv = null; + public Map curInfoPoint = null; + public Map historyInfoPoint = null; + public WorldController worldController = null; + + public GameUtil(GameEnv gameEnv, WorldController worldController, Map curInfoPoint, Map historyInfoPoint) { + this.gameEnv = gameEnv; + this.curInfoPoint = curInfoPoint; + this.historyInfoPoint = historyInfoPoint; + this.worldController = worldController; + } + + 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)); + + logWriter.record(conditionName + ": 将’" + info + "‘替换为‘" + newInfo + "'", 1); + curInfoPoint.put(conditionName, newInfo); + } + } + } +} diff --git a/src/gameDesign/GlobalVariableConstructor.java b/src/gameDesign/GlobalVariableConstructor.java index 92a1314..f8d9ae4 100644 --- a/src/gameDesign/GlobalVariableConstructor.java +++ b/src/gameDesign/GlobalVariableConstructor.java @@ -12,20 +12,20 @@ import java.util.Map; public class GlobalVariableConstructor extends ElementConstructor { - public GlobalVariableConstructor(SqlHelper helper, int botId, int skipCount, String botAccount, HashSet exceptRelation, StringBuffer POS) { + public GlobalVariableConstructor(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { super(); this.helper = helper; this.botId = botId; this.botAccount = botAccount; this.exceptRelation = exceptRelation; - this.skipCount = skipCount; + this.keywordMap = keywordMap; this.POS = POS; } public void construct(JSONObject gameElements, UserInfo userinfo) { try { - String category, name, description, attrName, attrValue; + String category, name, description, attrValue; JSONArray globalVariable = gameElements.getJSONArray("globalVariable"); Map attribute = null; Iterator attrIter = null; @@ -33,9 +33,9 @@ public class GlobalVariableConstructor extends ElementConstructor { for (JSONObject variableList : globalVariable.toJavaList(JSONObject.class)) { category = (String) variableList.get("category"); attribute = gameElements.toJavaObject(variableList.getJSONObject("variables"), Map.class); - attrIter = attribute.keySet().iterator(); - while (attrIter.hasNext()) { - attrName = attrIter.next(); + + + for(String attrName:attribute.keySet()) { attrValue = attribute.get(attrName); varInitialMap.put("globalVariable_" + category + "_" + attrName, attrValue); } @@ -54,6 +54,7 @@ public class GlobalVariableConstructor extends ElementConstructor { }catch (Exception e){ operationStatus = 0; message = "全局变量处理出现异常"; + e.printStackTrace(); return; } } diff --git a/src/gameDesign/ItemConstructor.java b/src/gameDesign/ItemConstructor.java index 082e4f4..c6e2546 100644 --- a/src/gameDesign/ItemConstructor.java +++ b/src/gameDesign/ItemConstructor.java @@ -12,50 +12,63 @@ public class ItemConstructor extends ElementConstructor { - public ItemConstructor(SqlHelper helper, int botId, int skipCount, String botAccount, HashSet exceptRelation, StringBuffer POS) { + public ItemConstructor(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { super(); this.helper = helper; this.botId = botId; this.botAccount = botAccount; this.exceptRelation = exceptRelation; - this.skipCount = skipCount; + this.keywordMap = keywordMap; this.POS = POS; } public void construct(JSONObject gameElements, UserInfo userinfo) { try { - String category, name, className, description, attrName, attrValue; + + String pattern1 = keywordMap.get("item_location_pattern").toString(); + String category, name, className, description, attrValue; JSONArray goods = gameElements.getJSONArray("goods"); Map attribute = null; Iterator attrIter = null; HashSet classSet = new HashSet(); + + keywordMap.putIfAbsent("item_wenzainali", new StringBuffer()); + keywordMap.putIfAbsent("item_shishenme", new StringBuffer()); + keywordMap.putIfAbsent("item_know_exist_what", new StringBuffer()); + keywordMap.putIfAbsent("item_nums", new StringBuffer()); + + //与物品属性查询相关的所有condition - ArrayList attrRelateConditions = new ArrayList() { - { - add("nums"); - add("shishenme"); - } - }; + String attrRelateConditions[] = {"nums", "shishenme"}; + //与物品类查询相关的所有condition - ArrayList classRelateConditions = new ArrayList() { - { - add("know_exist_what"); - } - }; + String classRelateConditions[] = {"know_exist_what" }; + + String locationRelateConditions[] = {"wenzainali"}; + + //如何找到×××××× ,这样的condition + String findRelateConditions[] = {"want_know_zenmezuo"}; + String findPattern = keywordMap.get("find_pattern").toString(); - StringBuffer keywords = new StringBuffer(); StringBuffer classKeywords = new StringBuffer(); + for (JSONObject good : goods.toJavaList(JSONObject.class)) { name = (String) good.get("name"); + + //添加词性 if(!name.equals("")) POS.append("=" + name + "|名词\r\n"); className = (String) good.get("class"); if(!className.equals("")) POS.append("=" + className + "|名词\r\n"); + + + keywordMap.get("item_" + locationRelateConditions[0]).append(pattern1.replace("name", name)); + //添加所有物品类别 if (!classSet.contains(className)) { classSet.add(className); //添加周围有什么士兵等关于类别的关键词 @@ -63,34 +76,58 @@ public class ItemConstructor extends ElementConstructor { } attribute = gameElements.toJavaObject(good.getJSONObject("attr"), Map.class); - attrIter = attribute.keySet().iterator(); - while (attrIter.hasNext()) { - attrName = attrIter.next(); + + for(String attrName: attribute.keySet()){ if(!attrName.equals("")) POS.append("=" + attrName + "|名词\r\n"); attrValue = attribute.get(attrName); - keywords.append("+" + name + ":" + attrName); + for(String condition: attrRelateConditions){ + keywordMap.get("item_" + condition).append("+" + name + ":" + attrName); + } } + } + + //与地点查询相关的condition + for(String conditionName: locationRelateConditions){ + jConfig = new JConfig( + conditionName + "::match-Include=" + keywordMap.get("item_" + conditionName).toString() + "," + + "zainali::match-Keyword=" + keywordMap.get("map_zainali").toString(), " ", + "match,return-0", + "【{" + PlotConstructor.ASSISTANT + "-2}】" +"{goods_query-2}", + " ", + "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", + "【{" + PlotConstructor.ASSISTANT + "-2}】" +"{goods_query-2}", + " ", + "goods_query:queryLocationByConditionName:" + conditionName + ); + JConfig.activateCopy(jConfig, jConfigList, "item"); } + //根据根据物品名字和属性查询属性值 for (String conditionName : attrRelateConditions) { jConfig = new JConfig( - conditionName + "::match-Include=" + keywords, " ", + conditionName + "::match-Include=" + keywordMap.get("item_" + conditionName).toString(), " ", "match,return-0", "【{" + PlotConstructor.ASSISTANT + "-2}】" +"{goods_query-2}", " ", "goods_query:queryAttrByGoodsName:" + conditionName ); - jConfig.setAuxiliaryPriority("1"); - jConfigList.add(jConfig); + JConfig.activateCopy(jConfig, jConfigList, "item"); } - //根据类名和地点查询所有实例 + + //根据类名查询周围所有实例 for (String conditionName : attrRelateConditions) { jConfig = new JConfig( conditionName + "::match-Include=" + classKeywords, " ", @@ -99,8 +136,7 @@ public class ItemConstructor extends ElementConstructor { " ", "goods_query:queryAroundGoodsByClassName:" + conditionName ); - jConfig.setAuxiliaryPriority("1"); - jConfigList.add(jConfig); + JConfig.activateCopy(jConfig, jConfigList, "item"); } } catch(Exception e){ operationStatus = 0; diff --git a/src/gameDesign/MapConstructor.java b/src/gameDesign/MapConstructor.java index 4a7969c..53066a5 100644 --- a/src/gameDesign/MapConstructor.java +++ b/src/gameDesign/MapConstructor.java @@ -6,10 +6,14 @@ import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.entity.JConfig; import com.qiwu.chatbotbackend.entity.UserInfo; -import java.util.*; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; public class MapConstructor extends ElementConstructor { + String nickname = "qiwu"; int[][] matrix; int locationNum; HashMap id2j = new HashMap(); @@ -19,13 +23,14 @@ public class MapConstructor extends ElementConstructor { Map script = null; //话术模板 - public MapConstructor(SqlHelper helper, int botId, int skipCount, String botAccount, HashSet exceptRelation, StringBuffer POS) { + + public MapConstructor(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { super(); this.helper = helper; this.botId = botId; this.botAccount = botAccount; this.exceptRelation = exceptRelation; - this.skipCount = skipCount; + this.keywordMap = keywordMap; this.POS = POS; } @@ -87,9 +92,6 @@ public class MapConstructor extends ElementConstructor { try { - - - conditionDescription.put("site", "当前地点"); JSONObject map = gameElements.getJSONObject("map"); @@ -97,29 +99,48 @@ public class MapConstructor extends ElementConstructor { script = JSONObject.toJavaObject(gameElements.getJSONObject("speechcraft"), Map.class); if(!script.containsKey("PATH_AT")) - script.put("PATH_AT", "你已经在%s"); + script.put("PATH_AT", "你已经在[地点名]了"); if(!script.containsKey("WHERE_I_AM")) - script.put("WHERE_I_AM", "在%s"); + script.put("WHERE_I_AM", "在[地点名]"); if(!script.containsKey("PATH_ADJOINT")) script.put("PATH_ADJOINT", "就在附近哦"); if(!script.containsKey("PATH_EXIST")) - script.put("PATH_EXIST", "通过%s可以到达目的地"); + script.put("PATH_EXIST", "通过[途径]可以到达[目的地]"); if(!script.containsKey("PATH_NOT_EXIST")) script.put("PATH_NOT_EXIST", "不可到达"); if(!script.containsKey("CAN_GO_SITES")) - script.put("CAN_GO_SITES", "你可以去%s"); + script.put("CAN_GO_SITES", "你可以去[可去列表]"); if(!script.containsKey("CAN_GO_NOWHERE")) script.put("CAN_GO_NOWHERE", "没什么地方可去的,继续玩吧"); if(!script.containsKey("SITE_NOT_ACTIVE")) - script.put("SITE_NOT_ACTIVE", "你来到了%s\""); + script.put("SITE_NOT_ACTIVE", "你来到了[地点名]"); if(!script.containsKey("SITE_NOT_ADJOINT")) - script.put("SITE_NOT_ADJOINT", "通过%s可以到达目的地"); + script.put("SITE_NOT_ADJOINT", "通过[途径]可以到达[目的地]"); if(!script.containsKey("AROUND_PEOPLE")) - script.put("AROUND_PEOPLE", "周围有%s"); + script.put("AROUND_PEOPLE", "周围有[人物列表]"); if(!script.containsKey("AROUND_ITEMS")) - script.put("AROUND_ITEMS", "周围有%s"); + script.put("AROUND_ITEMS", "周围有[物品列表]"); if(!script.containsKey("AROUND_THINGS")) - script.put("AROUND_THINGS", "周围有%s"); + script.put("AROUND_THINGS", "周围有[人物物品列表]"); + if(!script.containsKey("FIND_ITEM_LOCATION")) + script.put("FIND_ITEM_LOCATION", "[物品名]在[地点]"); + if(!script.containsKey("FIND_NPC_LOCATION")) + script.put("FIND_NPC_LOCATION", "[人名]在[地点]"); + if(!script.containsKey("AROUND_PLACE")) + script.put("AROUND_PLACE", "周围有[地点列表]"); + if(!script.containsKey("FIND_ITEM_WAY")) + script.put("FIND_ITEM_WAY", "[人名]在[地点]"); + if(!script.containsKey("FIND_NPC_WAY")) + script.put("FIND_NPC_WAY", "[物品名]在[地点]"); + if(!script.containsKey("GET_ITEM_ATTR")) + script.put("GET_ITEM_ATTR", "[物品名]的[属性名]是[属性值]"); + if(!script.containsKey("WE_HAVE")) + script.put("WE_HAVE", "我们有[物品列表]"); + if(!script.containsKey("GET_NPC_ATTR")) + script.put("GET_NPC_ATTR", "[人名]的[属性名]是[属性值]"); + + + @@ -144,14 +165,14 @@ public class MapConstructor extends ElementConstructor { generateSurroundingItem(); generateSurroundingPeople(); generateSurroundThings(); - - + generateSurroundPlace(); } catch(Exception e){ operationStatus = 0; e.printStackTrace(); message = "地图处理出现异常:"; + e.printStackTrace(); message += e.getMessage(); return; } @@ -162,19 +183,22 @@ public class MapConstructor extends ElementConstructor { * 生成‘我在哪里’所需要的配置文件 */ public void generateWhereIam(JSONObject gameElements, String botAccount) { - String conditionName = "rencheng"; + String conditionNameList[] = {"zainali", "wenzainali"}; + String conditionKeywords = ""; - String nickname = "qiwu"; - String conditionKeywords = nickname + ":哪里+" + nickname + ":哪+现在:哪里+现在:哪"; - jConfig = new JConfig( - conditionName + "::match-Include=" + conditionKeywords, " ", - "match", "【{" + PlotConstructor.ASSISTANT + "-2}】" + String.format(script.get("WHERE_I_AM"), "{site-2}"), "yaobuyao", "" - ); - jConfig.setNextStepStatus("return-0"); - jConfig.setAuxiliaryPriority("1"); - jConfigList.add(jConfig); + for(String condition:conditionNameList) { + + conditionKeywords = keywordMap.get("map_" + condition).toString(); + jConfig = new JConfig( + condition + "::match-Include=" + conditionKeywords, " ", + "match", "【{" + PlotConstructor.ASSISTANT + "-2}】" + script.get("WHERE_I_AM").replace("[地点名]", "{site-2}"), "yaobuyao", "" + ); + jConfig.setNextStepStatus("return-0"); + jConfig.setAuxiliaryPriority("1"); + JConfig.activateCopy(jConfig, jConfigList, "map"); + } } @@ -188,7 +212,6 @@ public class MapConstructor extends ElementConstructor { */ 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; @@ -197,63 +220,60 @@ public class MapConstructor extends ElementConstructor { for (int i = 0; i < locationNum; i++) { placeA = (String) locations.getJSONObject(i).get("name"); placeKeywords.append("+" + placeA); - - } - for (int j = 0; j < locationNum; j++) { + for (int j = 0; j < locationNum; j++) { - placeB = (String) locations.getJSONObject(j).get("name"); + 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", - "【{" + PlotConstructor.ASSISTANT + "-2}】" + String.format(script.get("PATH_AT"), "{site-2}"), - " ", - "" - ); - jConfig.setNextStepStatus("return-0"); - jConfig.setAuxiliaryPriority("1"); - jConfigList.add(jConfig); + jConfig = new JConfig( + conditionName + "::match-Include=" + placeKeywords + + ",isNeighbour:"+ conditionName + "::match-Include=0", + "site::match-Include=" + placeB , + "match,return-0", + "【{" + PlotConstructor.ASSISTANT + "-2}】" + script.get("PATH_AT").replace("[地点名]", "{site-2}"), + " ", + "" + ); + jConfig.setNextStepStatus("return-0"); + jConfig.setAuxiliaryPriority("1"); + JConfig.activateCopy(jConfig, jConfigList, "map"); - jConfig = new JConfig( - conditionName + "::match-Include=" + placeKeywords - + ",isNeighbour:"+ conditionName + "::match-Include=1", - "site::match-Include=" + placeB , - "match,return-0", - "【{" + PlotConstructor.ASSISTANT + "-2}】" + String.format(script.get("PATH_ADJOINT"), "{site-2}"), - " ", - "" - ); - jConfig.setNextStepStatus("return-0"); - jConfig.setAuxiliaryPriority("1"); - jConfigList.add(jConfig); + jConfig = new JConfig( + conditionName + "::match-Include=" + placeKeywords + + ",isNeighbour:"+ conditionName + "::match-Include=1+3+4", + "site::match-Include=" + placeB , + "match,return-0", + "【{" + PlotConstructor.ASSISTANT + "-2}】" + script.get("PATH_ADJOINT"), + " ", + "" + ); + jConfig.setNextStepStatus("return-0"); + jConfig.setAuxiliaryPriority("1"); + JConfig.activateCopy(jConfig, jConfigList, "map"); - jConfig = new JConfig( - conditionName + "::match-Include=" + placeKeywords - + ",isNeighbour:"+ conditionName + "::match-Include=2", - "site::match-Include=" + placeB , - "match,return-0", - "【{" + PlotConstructor.ASSISTANT + "-2}】"+"{map_reply-2}", - " ", - "map_reply:queryHowToPathBySite:" + conditionName - ); - jConfig.setNextStepStatus("return-0"); - jConfig.setAuxiliaryPriority("1"); - jConfigList.add(jConfig); - + jConfig = new JConfig( + conditionName + "::match-Include=" + placeKeywords + + ",isNeighbour:"+ conditionName + "::match-Include=2", + "site::match-Include=" + placeB , + "match,return-0", + "【{" + PlotConstructor.ASSISTANT + "-2}】" + "{map_reply-2}", + " ", + "map_reply:queryHowToPathBySite:" + conditionName + ); + jConfig.setNextStepStatus("return-0"); + jConfig.setAuxiliaryPriority("1"); + JConfig.activateCopy(jConfig, jConfigList, "map"); - } + } } @@ -262,29 +282,20 @@ public class MapConstructor extends ElementConstructor { * 生成‘我能去哪里’所需要的配置文件 */ public void generateWhereCanIgo(int[][] pathMatirx, int[][] preTable, JSONObject gameElements) { - String conditionKeywords = "去:哪里+能去:哪+能去:哪里+能去:哪儿"; String conditionName = "choose_gowhere"; + String conditionKeywords = keywordMap.get("map_" + conditionName).toString(); + 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, " ", + "match,return-0", "【{" + PlotConstructor.ASSISTANT + "-2}】" + "{map_reply-2}", " ", "map_reply:queryCanGoBySite:" + ); + jConfig.setNextStepStatus("return-0"); + jConfig.setAuxiliaryPriority("1"); + JConfig.activateCopy(jConfig, jConfigList, "map"); - jConfig = new JConfig( - conditionName + "::match-Include=" + conditionKeywords, "site::match-Include=" + placeA, - "match,return-0", "【{" + PlotConstructor.ASSISTANT + "-2}】"+"{map_reply-2}", " ", "map_reply:queryCanGoBySite:" - ); - jConfig.setNextStepStatus("return-0"); - jConfig.setAuxiliaryPriority("1"); - jConfigList.add(jConfig); - } } @@ -308,7 +319,7 @@ public class MapConstructor extends ElementConstructor { String placeAMain = placeA.split("\\+")[0]; if(!varInitialMap.containsKey("任务线" + placeAMain + "最后一个condition")) { varInitialMap.put("任务线" + placeAMain + "最后一个condition", "yaobuyao"); - varInitialMap.put("任务线" + placeAMain + "最后的回答", "你来到了" + placeAMain + ",现在什么都没有, 请继续之前的剧情,接着往下玩吧!"); + varInitialMap.put("任务线" + placeAMain + "最后的回答", script.get("SITE_NOT_ACTIVE").replace("[地点名]", placeAMain)); conditionDescription.put("任务线" + placeAMain + "最后一个condition", "任务线" + placeAMain + "最后一个condition"); conditionDescription.put("任务线" + placeAMain + "最后的回答", "任务线" + placeAMain + "最后的回答"); } @@ -328,22 +339,33 @@ public class MapConstructor extends ElementConstructor { + ",isNeighbour:"+ conditionName + "::match-Include=0", "site::match-Include=" + placeA , "match,return-0", - "【{" + PlotConstructor.ASSISTANT + "-2}】" + String.format(script.get("PATH_AT"), placeBMain), + "【{" + PlotConstructor.ASSISTANT + "-2}】" + script.get("PATH_AT").replace("[地点名]", placeBMain), " ", "" ); - jConfig.setAuxiliaryPriority("1"); + jConfig.setConfigName("map",true); jConfigList.add(jConfig); - jConfig = new JConfig( - conditionName + "::match-Include=" + placeKeywords + "," + ",isNeighbour:"+ conditionName + "::match-Include=1", + conditionName + "::match-Include=" + placeKeywords + "," + ",isNeighbour:"+ conditionName + "::match-Include=1+3+4", "site::match-Include=" + placeA, - "match, reutrn-0", "{" + lastTaskReply + "-2}", "yaobuyao", "site:" + placeBMain + "-<-process-nextStep:var={" + lastTaskCondition +"-2}" + "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 + + "-<-npc_update:updateFollowerLocation:"+ placeBMain ); - jConfig.setAuxiliaryPriority("1"); + jConfig.setStatus("sleeping"); + jConfig.setConfigName("plot_"+placeBMain + "_doudi",false); + jConfig.setjStatus(1); jConfigList.add(jConfig); @@ -353,11 +375,11 @@ public class MapConstructor extends ElementConstructor { + ",isNeighbour:"+ conditionName + "::match-Include=2", "site::match-Include=" + placeA , "match,return-0", - "【{" + PlotConstructor.ASSISTANT + "-2}】"+"{map_reply-2}", + "【{" + PlotConstructor.ASSISTANT + "-2}】" + "{map_reply-2}", " ", "map_reply:queryToDoPathBySite:" + conditionName ); - jConfig.setAuxiliaryPriority("1"); + jConfig.setConfigName("map",true); jConfigList.add(jConfig); } @@ -367,41 +389,51 @@ public class MapConstructor extends ElementConstructor { public void generateSurroundingPeople(){ String conditionName = "know_exist_what"; - String conditionKeywords = "周围:人+附近:人"; + String conditionKeywords = keywordMap.get("people_" + conditionName).toString(); jConfig = new JConfig( conditionName + "::match-Include=" + conditionKeywords, " ", "match,return-0", "【{" + PlotConstructor.ASSISTANT + "-2}】" + "{map_query-2}。", "yaobuyao", "map_query:queryAroundNpcBySite:" ); - jConfig.setAuxiliaryPriority("1"); - jConfigList.add(jConfig); + JConfig.activateCopy(jConfig, jConfigList, "map"); } public void generateSurroundingItem(){ String conditionName = "know_exist_what"; - String conditionKeywords = "周围:物品+周围:东西+附近:物品+附近:东西"; + String conditionKeywords = keywordMap.get("item_" + conditionName).toString(); jConfig = new JConfig( conditionName + "::match-Include=" + conditionKeywords, " ", "match,return-0", "【{" + PlotConstructor.ASSISTANT + "-2}】" + "{map_query-2}。", "yaobuyao", "map_query:queryAroundGoodsBySite:" ); - jConfig.setAuxiliaryPriority("1"); - jConfigList.add(jConfig); + JConfig.activateCopy(jConfig, jConfigList, "map"); } public void generateSurroundThings(){ String conditionName = "know_exist_what_mohu"; - String conditionKeywords = "有什么:周围+有什么:附近"; + String conditionKeywords = keywordMap.get("things_" + conditionName).toString(); jConfig = new JConfig( conditionName + "::match-Include=" + conditionKeywords, " ", "match,return-0", "【{" + PlotConstructor.ASSISTANT + "-2}】" + "{map_query-2}。", "yaobuyao", "map_query:queryAroundAllBySite:" ); - jConfig.setAuxiliaryPriority("1"); - jConfigList.add(jConfig); + JConfig.activateCopy(jConfig, jConfigList, "map"); + + } + + public void generateSurroundPlace(){ + 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:" + ); + jConfig.setNextStepStatus("return-0"); + JConfig.activateCopy(jConfig, jConfigList, "map"); } diff --git a/src/gameDesign/PlotConstructor.java b/src/gameDesign/PlotConstructor.java index c66040a..45963cd 100644 --- a/src/gameDesign/PlotConstructor.java +++ b/src/gameDesign/PlotConstructor.java @@ -27,6 +27,7 @@ public class PlotConstructor extends ElementConstructor { HashMap visited = new HashMap(); + public static String TASK_LINE = "任务线_%s进度"; public static String TASK_CONDITION = "任务线%s最后一个condition"; public static String TASK_REPLY = "任务线%s最后的回答"; @@ -35,13 +36,13 @@ public class PlotConstructor extends ElementConstructor { return id2j; } - public PlotConstructor(SqlHelper helper, int botId, int skipCount, String botAccount, HashSet exceptRelation, StringBuffer POS) { + public PlotConstructor(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { super(); this.helper = helper; this.botId = botId; this.botAccount = botAccount; this.exceptRelation = exceptRelation; - this.skipCount = skipCount; + this.keywordMap = keywordMap; this.POS = POS; } @@ -256,7 +257,13 @@ public class PlotConstructor extends ElementConstructor { lastTaskReply = "任务线" + nextLocation + "最后的回答"; - //额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情 + /** + * 额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情 + * 如果某个地点的剧情已经到结尾啦,那么有两种解决方法: + * 1: 将剧情停留在最后一步剧情 + * 2. 设一个专门的剧情表示剧情的结尾 + */ + extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1; if(!id.equals(nextId)){ extraHP += "," + nextId + "::match-Include=null"; @@ -342,7 +349,7 @@ public class PlotConstructor extends ElementConstructor { //没有当前条件的限制, if (curPremiseList.size() == 0){ jConfig.setFeature(jConfig.getFeature() + ",activate,post::gameQA(" + QA_URL + ")"); - jConfig.setNextStep("queryskip*,map*"); + jConfig.setNextStep("queryskip*,map*,item*,npc*"); jConfig.setUpdateKnowledge(jConfig.getUpdateKnowledge() + "-<-临时变量condition:"+ nextCondition +"-<-临时变量reply:var={reply-3}"); jConfig.setNextStepStatus("active"); } @@ -350,8 +357,6 @@ public class PlotConstructor extends ElementConstructor { - - jConfigList.add(jConfig); diff --git a/src/processing/FormsPoster.java b/src/processing/FormsPoster.java index 82f9901..27ea26f 100644 --- a/src/processing/FormsPoster.java +++ b/src/processing/FormsPoster.java @@ -6,6 +6,7 @@ import com.alibaba.fastjson.JSONObject; 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 org.apache.http.message.BasicNameValuePair; import java.io.UnsupportedEncodingException; @@ -89,8 +90,7 @@ public class FormsPoster { } } }else { - if(URL.equals(QA_URL - )) + if(URL.equals(QA_URL)) ans.setAnswer("qa_threshold, game_step, query_text 看看少了哪个"); else ans.setAnswer("提交表单出现异常"); @@ -170,7 +170,7 @@ public class FormsPoster { * @param URL * @throws UnsupportedEncodingException */ - public void postGameQA(Map curInfoPoint, Map historyInfoPoint, Solution ans,GameEnv gameEnv, WorldController worldController, String URL) throws UnsupportedEncodingException { + public void postGameQA(Map curInfoPoint, Map historyInfoPoint, Solution ans,GameEnv gameEnv, WorldController worldController, String URL, UserInfo userInfo) throws UnsupportedEncodingException { String key, keyName; Iterator k_iter = null; List pairList = new ArrayList(); @@ -206,7 +206,8 @@ public class FormsPoster { 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(site)){ + 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)); historyInfoPoint.put("qa_score", String.valueOf(textscore.get(1))); break; diff --git a/src/processing/MyFunc.java b/src/processing/MyFunc.java index 7cde103..ca34d56 100644 --- a/src/processing/MyFunc.java +++ b/src/processing/MyFunc.java @@ -191,5 +191,22 @@ public class MyFunc { } + public static String randStr(String strList[]){ + String reply; + int randNum = (int) (Math.random() * strList.length); + reply = strList[randNum]; + + return reply; + } + + public static String randStr(List strList){ + String reply; + + int randNum = (int) (Math.random() * strList.size()); + reply = strList.get(randNum); + + return reply; + } + } \ No newline at end of file diff --git a/src/processing/QuestionMatcher.java b/src/processing/QuestionMatcher.java index 6ed89db..6509c55 100644 --- a/src/processing/QuestionMatcher.java +++ b/src/processing/QuestionMatcher.java @@ -5,6 +5,7 @@ import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; import com.qiwu.chatbotbackend.entity.Solution; import com.qiwu.chatbotbackend.entity.Condition; import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.gameDesign.GameUtil; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; @@ -70,7 +71,7 @@ public class QuestionMatcher { public boolean infoPointPreprocessing(Map receiveParameters, Map curInfoPoint, Map historyInfoPoint, UserInfo userinfo, ServletContext context) throws IOException { - String return_str = "", k; + String return_str = "", k, botType = ""; String receiveParameterStr = ""; boolean debugFlag = false; @@ -94,7 +95,7 @@ public class QuestionMatcher { receiveParameterStr += k + ": "; curInfoPoint.put(k, receiveParameters.get(k)[0]); - if (k.equals("debug_mode")) + if (k.equals("debug_mode") || k.equals("debug_rule")) debugFlag = true; String values[] = receiveParameters.get(k); @@ -104,11 +105,13 @@ public class QuestionMatcher { // } 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(); @@ -146,6 +149,20 @@ public class QuestionMatcher { 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; } @@ -187,18 +204,17 @@ public class QuestionMatcher { 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(); } + bestMatch = condition; + logWriter.record("匹配更新为:\"" + userinfo.id2config.get(condition.id) + "\"", 2); + logWriter.writeln(); + } + }else { + logWriter.record("-----------------------------------优先级不足,跳过", 0); + logWriter.record(userinfo.id2config.get(condition.id), 1); } } /* @@ -252,20 +268,29 @@ public class QuestionMatcher { condition = activatedQueue.remove(); activatedMap.remove(condition.id); - if (conditionSatisfy(condition)) { - if (condition.featureMap.containsKey("activate") && !condition.featureMap.containsKey("post")) { - logWriter.record("匹配更新为:\"" + userinfo.id2config.get(condition.id) + "\"", 2); logWriter.writeln(); - 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) || - bestMatch.nextStep.contains(String.valueOf(condition.id)) || bestMatch.nextStep.contains(condition.configName)) { + + 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))){ + //激活优先级先比较,但是如果激活的是无条件的就直接判断名字。 + if(conditionSatisfy(condition)){ + if (condition.featureMap.get("activate") != null && !condition.featureMap.containsKey("post")) { + activateCondition(activatedQueue, curInfoPoint.get("bot_name"), condition.priority, condition.auxiliaryPriority, condition.nextStep, context); + } + bestMatch = condition; - logWriter.record("匹配更新为:\"" + userinfo.id2config.get(condition.id) + "\"", 2); logWriter.writeln(); + logWriter.record("匹配更新为:\"" + userinfo.id2config.get(condition.id) + "\"", 2); + logWriter.writeln(); } + + } else { + logWriter.record("-----------------------------------优先级不足,跳过", 0); + logWriter.record(userinfo.id2config.get(condition.id), 1); } + + + } return bestMatch; @@ -799,8 +824,7 @@ public class QuestionMatcher { try { - int randNum = (int) (Math.random() * ansCondition.answer.length); - reply = ansCondition.answer[randNum]; + reply = MyFunc.randStr(ansCondition.answer); //用正则表达式将回答中的变量模板{conditionName-2}替换成后台存储的变量值 String keyword; Matcher m = replacePattern.matcher(reply); @@ -853,6 +877,8 @@ public class QuestionMatcher { historyInfoPoint.put("currentAction", next); historyInfoPoint.put("activeList", historyInfoPoint.get("activeList") + "|" + next); + logWriter.record("处理完成后的信息点:
" + historyInfoPoint.toString(), 1); + HashSet skipSet = new HashSet() { { add("chat_key"); @@ -919,6 +945,9 @@ public class QuestionMatcher { add("bot_name"); add("action_name"); add("lastReply"); + add("unknownTextList"); + add("finalUnknownText"); + add("unknownText"); } }; @@ -937,15 +966,19 @@ public class QuestionMatcher { } } - debugInfo += ")(已知:"; - it = historyInfoPoint.keySet().iterator(); - while (it.hasNext()) { + debugInfo += ")"; + if(curInfoPoint.containsKey("debug_mode")) { + debugInfo = debugInfo.replace("-)", ""); + debugInfo += "(已知:"; + it = historyInfoPoint.keySet().iterator(); + while (it.hasNext()) { - key = it.next(); - value = historyInfoPoint.get(key); - if (value != null && !value.equals(" ") && !value.equals("") && !skipSet.contains(key) && !key.endsWith("最后的回答") && !key.endsWith("最后一个condition") && !key.startsWith("临时变量")) - debugInfo += (" " + key + ":\'" + value + "\' "); + key = it.next(); + value = historyInfoPoint.get(key); + if (value != null && !value.equals(" ") && !value.equals("") && !skipSet.contains(key) && !key.endsWith("最后的回答") && !key.endsWith("最后一个condition") && !key.startsWith("临时变量")) + debugInfo += (" " + key + ":\'" + value + "\' "); + } } ans.setAnswer(debugInfo + ")" + ans.getAnswer()); } @@ -978,98 +1011,12 @@ public class QuestionMatcher { postType = elem[1]; -// if (postType.equals("all")) { -// k_iter = curInfoPoint.keySet().iterator(); -// while (k_iter.hasNext()) { -// key = k_iter.next(); -// if (curInfoPoint.get(key) != "") -// //infoMap.put(key + "_cur", curInfoPoint.get(key)[0]); -// pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key))); -// } -// -// k_iter = historyInfoPoint.keySet().iterator(); -// while (k_iter.hasNext()) { -// key = k_iter.next(); -// if (historyInfoPoint.get(key) != "") -// //infoMap.put(key + "_his", historyInfoPoint.get(key)); -// if (key.equals("game_step")) -// pairList.add(new BasicNameValuePair(key, historyInfoPoint.get(key))); -// else if(skipSet.contains(key)){} -// else -// pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key))); -// } -// - -// } else if (postType.equals("term")) { -// pairList.add(new BasicNameValuePair("chat_key", curInfoPoint.get("chat_key"))); -// pairList.add(new BasicNameValuePair("action_name", curInfoPoint.get("action_name"))); -// pairList.add(new BasicNameValuePair("bot_name", curInfoPoint.get("bot_name"))); -// k_iter = ansCondition.currentPremise.keySet().iterator(); -// while (k_iter.hasNext()) { -// key = k_iter.next().split("::")[0]; -// if (curInfoPoint.get(key) != "") -// pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key))); -// } -// -// k_iter = ansCondition.historyPremise.keySet().iterator(); -// while (k_iter.hasNext()) { -// key = k_iter.next().split("::")[0]; -// if (historyInfoPoint.get(key) != "") -// pairList.add(new BasicNameValuePair(key + "_his", historyInfoPoint.get(key))); -// //infoMap.put(key + "_his", historyInfoPoint.get(key)); -// } -// } -// -// logWriter.record("提交表单的数据:
" + pairList.toString(), 2); -// -// HttpPost httpPost = new HttpPost(url); -// CloseableHttpClient client = HttpClients.createDefault(); -// String respContent = null; -// String keyName = null; -// -// -// UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "utf-8"); -// entity.setContentType("application/x-www-form-urlencoded"); -// httpPost.setEntity(entity); -// -// try { -// HttpResponse resp = client.execute(httpPost); -// if (resp.getStatusLine().getStatusCode() == 200) { -// HttpEntity he = resp.getEntity(); -// respContent = EntityUtils.toString(he, "UTF-8"); -// logWriter.record("提交表单接收到的数据:
" + respContent, 2); -// JSONObject jobj = JSONObject.parseObject(respContent); -// Iterator kit = jobj.keySet().iterator(); -// -// while (kit.hasNext()) { -// keyName = kit.next(); -// if (keyName.equals("process")) { -// ans.setNext((String) jobj.get(keyName)); -// historyInfoPoint.put("process", (String) jobj.get(keyName)); -// } else if (keyName.equals("solution")) { -// ans.setAnswer((String) jobj.get(keyName)); -// } else if (keyName.equals("status")){ -// continue; -// } else{ -// historyInfoPoint.put(keyName, jobj.getString(keyName)); -// } -// } -// } else { -// ans.setAnswer(API_ERROR); -// } -// } catch (Exception e) { -// e.printStackTrace(); -// -// ans.setAnswer(POST_ERROR + url); -// return ans; -// } - if(postType.equals("all")){ poster.postAll(curInfoPoint, historyInfoPoint, ans, url); }else if(postType.equals("term")){ poster.postTerm(curInfoPoint, historyInfoPoint, ans, ansCondition, url); }else if(postType.equals("gameQA")){ - poster.postGameQA(curInfoPoint, historyInfoPoint, ans, gameEnv, worldController, url); + poster.postGameQA(curInfoPoint, historyInfoPoint, ans, gameEnv, worldController, url, userinfo); } return ans; @@ -1238,8 +1185,7 @@ public class QuestionMatcher { } else if (updateValue.endsWith("nextStep-3}")) { updateValue = condition.nextStep; } else if (updateValue.endsWith("reply-3}")) { - int randNum = (int) (Math.random() * condition.answer.length); - updateValue = condition.answer[randNum]; + updateValue = MyFunc.randStr(condition.answer); } if (variableName.startsWith("process-nextStep")) { condition.nextStep = updateValue; @@ -1276,6 +1222,7 @@ public class QuestionMatcher { List originConditionList = new ArrayList(); for (String configIdStr : activateList.split(",")) { + logWriter.record("------激活-------" + configIdStr + "-------
", 0); try { if (StringUtils.isNumeric(configIdStr)) { configId = Integer.parseInt(configIdStr); @@ -1312,7 +1259,7 @@ public class QuestionMatcher { newCondition = new Condition(originCondition, basePriority, baseAuxiliaryPriority); //condition = QuestionMatcher.buildCondition(condition, configStr); - logWriter.record("------激活-------" + userinfo.id2config.get(configId) + "-------
", 0); + if (activatedMap.containsKey(configId)) { if(newCondition.auxiliaryPriority > activatedMap.get(configId).auxiliaryPriority) diff --git a/src/processing/ResponseFilter.java b/src/processing/ResponseFilter.java index edd3795..054cc69 100644 --- a/src/processing/ResponseFilter.java +++ b/src/processing/ResponseFilter.java @@ -6,6 +6,8 @@ import com.qiwu.chatbotbackend.entity.Solution; 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; import java.util.regex.Pattern; @@ -27,10 +29,9 @@ public class ResponseFilter { String site = historyInfoPoint.get("site"); - String answer[] = reply.split("~"); - int randNum = (int) (Math.random() * answer.length); - reply = answer[randNum]; - if(reply.startsWith("【" + historyInfoPoint.get(PlotConstructor.ASSISTANT))){ + reply = MyFunc.randStr(reply.split("~")); + + if(reply.startsWith("【" + historyInfoPoint.get(PlotConstructor.ASSISTANT)+ "】") ){ return reply; }else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter)){ return reply; @@ -38,26 +39,43 @@ public class ResponseFilter { } if(userInfo.varInitialMap.get("unknownTextList") != null){ + List unknownList = new ArrayList(); for(String ans:userInfo.varInitialMap.get("unknownTextList").split("~")){ if(ans.equals("")) continue; if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter)){ - return ans; + unknownList.add(ans); + //return ans; } } + if(unknownList.size() > 0){ + return MyFunc.randStr(unknownList); + + + } } if(userInfo.varInitialMap.get("finalUnknownText") != null){ finalUnknownText = userInfo.varInitialMap.get("finalUnknownText"); - if (sameLocation(finalUnknownText, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter)){ - return finalUnknownText; + List finalUnknownList = new ArrayList(); + for(String ans:finalUnknownText.split("~")){ + if(ans.equals("")) + continue; + if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter)){ + finalUnknownList.add(ans); + //return ans; + } + } + if(finalUnknownList.size() > 0){ + return MyFunc.randStr(finalUnknownList); + } } } - return ""; + return "找不到匹配文本"; } static Boolean sameLocation(String reply, Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController, String site, LogWriter logWriter){ @@ -66,7 +84,7 @@ public class ResponseFilter { Matcher m = findTalker.matcher(reply); if(m.find()) { npc = m.group(1); - if (worldController.worldOperation(gameEnv, "NPC_query", "queryLocationByNPCName:" + npc, curInfoPoint, historyInfoPoint).equals(site)){ + if (worldController.worldOperation(gameEnv, "npc_query", "queryLocationByNPCName:" + npc, curInfoPoint, historyInfoPoint).equals(site)){ return true; }{ logWriter.record(npc +"不在" + site + "跳过",1 ); diff --git a/src/processing/WorldController.java b/src/processing/WorldController.java index 8596c48..6d60616 100644 --- a/src/processing/WorldController.java +++ b/src/processing/WorldController.java @@ -26,7 +26,7 @@ public class WorldController { logWriter.record(String.format("---------------------key:%s, value:%s", varName, varValue), 0); - + String location = "", value = ""; if(valuePair[0].startsWith("query")){ //查询专用 if(varName.startsWith("goods_")) { @@ -40,10 +40,14 @@ public class WorldController { case "queryAttrByGoodsName": subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2); - subValuePair[0] = subValuePair[0].replace("哪里", "location"); - returnStr = gameEnv.queryGoodsAttrByGoodsName(subValuePair[0], subValuePair[1]); - if(returnStr == null) - returnStr = "无"; + value = gameEnv.queryGoodsAttrByGoodsName(subValuePair[0], subValuePair[1]); + + if(returnStr == null) { + returnStr = "没找到"; + }else{ + returnStr = userInfo.varInitialMap.get("GET_ITEM_ATTR").replace("[物品名]", subValuePair[0]).replace("[属性名]", subValuePair[1]).replace("[属性值]", value); + + } break; case "queryAllAttrByGoodsName": textList = gameEnv.queryGoodsAllAttrByGoodsName(varName); @@ -65,9 +69,25 @@ public class WorldController { returnStr = returnStr.substring(1); } break; + + case "queryLocationByConditionName": + // + String NPCName = currentInfoPoint.get(valuePair[1]).split(":")[1]; + returnStr = gameEnv.queryGoodsAttrByGoodsName(NPCName, "可被询问"); + if(returnStr == null || returnStr.equals("否")){ + returnStr = "没找到"; + } else if(returnStr.equals("是")){ + location = gameEnv.queryGoodsAttrByGoodsName(NPCName, "location"); + if(location == null){ + returnStr = "没找到"; + }else{ + returnStr = userInfo.varInitialMap.get("FIND_ITEM_LOCATION").replace("[物品名]", NPCName).replace("[地点]", location); + } + } + break; default: } - }else if(varName.startsWith("NPC_")) { + }else if(varName.startsWith("npc_")) { switch(valuePair[0]){ case "queryNpcIntro": //operationFlag = gameEnv.queryNpcIntro(valuePair[1], namePair[2]); @@ -81,16 +101,42 @@ public class WorldController { //根据condition的名字,从当前信息点中获取npc的名字 subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2); subValuePair[0] = subValuePair[0].replace("哪里", "location"); - returnStr = gameEnv.queryNpcAttrByNpcName(subValuePair[0], subValuePair[1]); - if(returnStr == null) - returnStr = "无"; + value = gameEnv.queryNpcAttrByNpcName(subValuePair[0], subValuePair[1]); + if(returnStr == null) { + returnStr = "没找到"; + }else{ + returnStr = userInfo.varInitialMap.get("GET_NPC_ATTR").replace("[人名]", subValuePair[0]).replace("[属性名]", subValuePair[1]).replace("[属性值]", value); + + } break; + case "queryLocationByNPCName": // - returnStr = gameEnv.queryNpcAttrByNpcName(valuePair[1], "location"); - if(returnStr == null) - returnStr = "无"; + location = gameEnv.queryNpcAttrByNpcName(valuePair[1], "location"); + if(location == null){ + returnStr = "没找到"; + }else{ + returnStr = location; + } + break; + case "queryLocationByConditionName": + // + String 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_LOCATION").replace("[人名]", NPCName).replace("[地点]", location); + } + } + break; + + default: } }else if (varName.startsWith("map_")) { @@ -102,7 +148,7 @@ public class WorldController { if(userInfo.varInitialMap.containsKey("AROUND_THINGS")) { format = userInfo.varInitialMap.get("AROUND_THINGS"); }else { - format = "有%s"; + format = "周围有[人物物品列表]"; } @@ -117,14 +163,14 @@ public class WorldController { text.append("、" + site); } - returnStr = String.format(format, text.substring(1)); + returnStr = format.replace("[人物物品列表]", text.substring(1)); } break; case "queryAroundNpcBySite": if(userInfo.varInitialMap.containsKey("AROUND_PEOPLE")) { format = userInfo.varInitialMap.get("AROUND_PEOPLE"); }else { - format = "有%s"; + format = "周围有[人物列表]"; } @@ -139,7 +185,7 @@ public class WorldController { text.append("、" + site); } - returnStr = String.format(format, text.substring(1)); + returnStr = format.replace("[人物列表]", text.substring(1)); } break; case "queryAroundGoodsBySite": @@ -147,7 +193,7 @@ public class WorldController { if(userInfo.varInitialMap.containsKey("AROUND_ITEMS")) { format = userInfo.varInitialMap.get("AROUND_ITEMS"); }else { - format = "有%s"; + format = "周围有[物品列表]"; } sites = gameEnv.queryAroundGoodsBySite(historyInfoPoint.get("site")); @@ -160,7 +206,7 @@ public class WorldController { for(String site:sites){ text.append("、" + site); } - returnStr = String.format(format, text.substring(1)); + returnStr = format.replace("[物品列表]", text.substring(1)); } } break; @@ -169,7 +215,7 @@ public class WorldController { if(userInfo.varInitialMap.containsKey("CAN_GO_SITES")) { format = userInfo.varInitialMap.get("CAN_GO_SITES"); }else { - format = "可以去%s"; + format = "你可以去[可去列表]"; } sites = gameEnv.queryCanGoBySite(historyInfoPoint.get("site")); @@ -185,7 +231,7 @@ public class WorldController { for(String site:sites){ text.append("、" + site); } - returnStr = String.format(format, text.substring(1)); + returnStr = format.replace("[可去列表]", text.substring(1)); } } break; @@ -194,7 +240,7 @@ public class WorldController { if(userInfo.varInitialMap.containsKey("PATH_EXIST")) { format = userInfo.varInitialMap.get("PATH_EXIST"); }else { - format = "通过%s可以到达"; + format = "通过[途径]可以到达[目的地]"; } if(!currentInfoPoint.containsKey(valuePair[1])) { @@ -213,7 +259,7 @@ public class WorldController { for(String site:sites){ text.append("、" + site); } - returnStr = String.format(format, text.substring(1)); + returnStr = format.replace("[途径]", text.substring(1)).replace("[目的地]", currentInfoPoint.get(valuePair[1]).split(":")[1]); } } break; @@ -222,7 +268,7 @@ public class WorldController { if(userInfo.varInitialMap.containsKey("SITE_NOT_ADJOINT")) { format = userInfo.varInitialMap.get("SITE_NOT_ADJOINT"); }else { - format = "通过%s可以到达"; + format = "通过[途径]可以到达[目的地]"; } if(!currentInfoPoint.containsKey(valuePair[1])) { @@ -240,7 +286,7 @@ public class WorldController { for(String site:sites){ text.append("、" + site); } - returnStr = String.format(format, text.substring(1)); + returnStr = format.replace("[途径]", text.substring(1)).replace("[目的地]", currentInfoPoint.get(valuePair[1]).split(":")[1]); } } break; @@ -269,4 +315,9 @@ public class WorldController { return returnStr; } + public static String findLocationName(GameEnv gameEnv, String locationName, String site){ + return gameEnv.getPlaceNameByNickname(site, locationName); + } + + } diff --git a/src/servlet/GameDesignServlet.java b/src/servlet/GameDesignServlet.java index 4a6a614..8385f04 100644 --- a/src/servlet/GameDesignServlet.java +++ b/src/servlet/GameDesignServlet.java @@ -24,6 +24,7 @@ import java.util.*; public class GameDesignServlet extends HttpServlet { String POST_URL = "http://localhost:1111/conditionProcess"; + String KEYWORD_DIR = "keywords.txt"; //分组及其相应的id,id初始化为0, 新建分组成功后id会更新。 HashMap categoryMap = new HashMap(){ { @@ -42,8 +43,11 @@ public class GameDesignServlet extends HttpServlet { //所有需要修改的词性 StringBuffer POS = new StringBuffer(); - //每个condition的三元组两端需要补充的关键词,比如npc名字、npc属性等 - HashMap> relationKeywords = new HashMap>(); + //每个condition的三元组两端需要补充的关键词,比如npc名字、npc属性等,格式为: "conditionName_tail/head":"keywords" + HashMap> additionalKeywords = new HashMap>(); + + //预先定义好的所有condition相关的关键词,格式为 "conditionName_标签":"keywords" + Map keywordMap = new HashMap(); //特定的relation的三元组不会被添加到relationKeywords HashSet exceptRelation = new HashSet(); @@ -105,35 +109,40 @@ public class GameDesignServlet extends HttpServlet { StringBuffer mergedConfigText = new StringBuffer(); int skipCount = 0; + + //从文件中读取condition相关的关键词 + System.out.println("----------------------read-------------------------/r------------------------------------------------------"); + readKeywords(keywordMap, KEYWORD_DIR); + String moduleList[] = {"map", "goods", "globalVariable", "npc", "plots"}; for(String moduleName: moduleList){ switch (moduleName) { case "map": moduleName2 = "地图"; - constructor = new MapConstructor2(helper, botId, skipCount, botAccount, exceptRelation, POS); + constructor = new MapConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); constructor.construct(gameElements, userinfo); break; case "plots": moduleName2 = "剧情"; - constructor = new PlotConstructor(helper, botId, skipCount, botAccount, exceptRelation, POS); + constructor = new PlotConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); constructor.construct(gameElements, userinfo); root = ((PlotConstructor) constructor).getId2j().get((String) gameElements.get("start")); break; case "goods": moduleName2 = "物品"; - constructor = new ItemConstructor(helper, botId, skipCount, botAccount, exceptRelation, POS); + constructor = new ItemConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); constructor.construct(gameElements, userinfo); break; case "globalVariable": moduleName2 = "全局变量"; - constructor = new GlobalVariableConstructor(helper, botId, skipCount, botAccount, exceptRelation, POS); + constructor = new GlobalVariableConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); constructor.construct(gameElements, userinfo); break; case "npc": moduleName2 = "NPC"; - constructor = new CharacterConstructor(helper, botId, skipCount, botAccount, exceptRelation, POS); + constructor = new CharacterConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); constructor.construct(gameElements, userinfo); break; default: @@ -150,7 +159,7 @@ public class GameDesignServlet extends HttpServlet { List jsonList = new ArrayList(); for(JConfig jConfig: constructor.getjConfigList()){ json = jConfig.toJson(constructor.getConditionDescription()); - constructor.parseKeyword(json, relationKeywords, exceptRelation); + constructor.parseKeyword(json, additionalKeywords, exceptRelation); jsonList.add(json); } @@ -174,7 +183,7 @@ public class GameDesignServlet extends HttpServlet { UserInfoController.buildUserInfo(br, userinfo, true); context.setAttribute(botAccount, userinfo); ConditionTableController.writeConfigText(botAccount, userinfo); - String postResult = actionRegenerate(root, gameElements, userinfo, relationKeywords, exceptRelation, POS); + String postResult = actionRegenerate(root, gameElements, userinfo, additionalKeywords, exceptRelation, POS); if(!postResult.equals("success")){ returnStatus = 0; @@ -229,7 +238,7 @@ public class GameDesignServlet extends HttpServlet { return deleteConfigFlag && deleteVariableFlag; } - public String actionRegenerate(JSONObject root, JSONObject gameElements, UserInfo userInfo, HashMap> relationKeywords, HashSet exceptRelation, StringBuffer POS){ + public String actionRegenerate(JSONObject root, JSONObject gameElements, UserInfo userInfo, HashMap> additionalKeywords, HashSet exceptRelation, StringBuffer POS){ String startCondition, POS2 = ""; String botName = (String)gameElements.get("botName"); JSONObject returnMessage = null; @@ -243,7 +252,7 @@ public class GameDesignServlet extends HttpServlet { actionPostData.put("botId", (Integer)gameElements.get("botId")); actionPostData.put("type", "game_plot_init"); actionPostData.put("welcome", "欢迎来到" + (String)gameElements.get("botName") + ",请说开始剧情或者重新开始"); - actionPostData.put("relationKeywords", relationKeywords); + actionPostData.put("relationKeywords", additionalKeywords); actionPostData.put("auth", gameElements.get("auth")); @@ -271,4 +280,35 @@ public class GameDesignServlet extends HttpServlet { } } + + public void readKeywords(Map keywordsMap, String path){ + + File file = new File(path); + String line, pair[]; + + System.out.println(file.getAbsolutePath()); + if(file.exists()){ + FileReader reader = null; + try { + reader = new FileReader(file); + BufferedReader br = new BufferedReader(reader); + + + while ((line = br.readLine()) != null) { + if(!line.equals("") && !line.startsWith("#")){ + pair = line.split("\\|", 2); + keywordsMap.put(pair[0], new StringBuffer(pair[1])); + } + } + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + } + } + + + }