From 7648340ee93d1e984353fc4a00f175b3e8ff8e47 Mon Sep 17 00:00:00 2001 From: hxw Date: Wed, 20 Feb 2019 18:14:18 +0800 Subject: [PATCH] 激活优先级默认会加一,剧情生成的分支中数据reply、unknownText、等放到原来的剧情中 --- src/entity/Action.java | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/entity/ConfigTerm.java | 495 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/entity/UserInfo.java | 12 ++++++------ src/gameDesign/CharacterConstructor.java | 30 +++++++++++++++--------------- src/gameDesign/ElementConstructor.java | 16 ++++++++-------- src/gameDesign/ItemConstructor.java | 26 +++++++++++++------------- src/gameDesign/ListeningConstructor.java | 116 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/gameDesign/MapConstructor.java | 124 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------------------------------------- src/gameDesign/PlotConstructor2.java | 691 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/processing/ActionMatcher.java | 1189 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/processing/ChatCacheController.java | 11 +++++++++-- src/processing/FormsPoster.java | 25 +++++++++++-------------- src/processing/ResponseFilter.java | 410 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/processing/UserInfoController.java | 311 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------------------------------- src/processing/WorldController.java | 63 ++++++++++++++++++++++++++++++++++++++++++++++----------------- src/servlet/ContextDestroyListener.java | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/servlet/GameDesignServlet.java | 29 ++++++++++++++--------------- src/servlet/GetAnswerServlet.java | 26 ++++++++++++++------------ src/servlet/UpdateServlet.java | 22 +++++++++++----------- src/servlet/UpdateSingleConfigServlet.java | 24 +++++++++++++----------- src/task/utils/BasicBotUtil.java | 5 +++-- src/task/utils/GameBotUtil.java | 422 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------------------------------- 22 files changed, 3382 insertions(+), 791 deletions(-) create mode 100644 src/entity/Action.java create mode 100644 src/entity/ConfigTerm.java create mode 100644 src/gameDesign/ListeningConstructor.java create mode 100644 src/processing/ActionMatcher.java create mode 100644 src/servlet/ContextDestroyListener.java diff --git a/src/entity/Action.java b/src/entity/Action.java new file mode 100644 index 0000000..54304cd --- /dev/null +++ b/src/entity/Action.java @@ -0,0 +1,66 @@ +package com.qiwu.chatbotbackend.entity; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; + + +/** + * 保存配置文件每一行(单行)解析后的信息的实体类。 + * 独立于引擎的另一种condition + */ +public class Action { + public int priority = -1; + public int activePriority = 0; //如果本condition被其他condition激活 + public int auxiliaryPriority = 0; //用于priority一样时人为设置的辅助优先级 + public HashSet keywordSet = new HashSet(); + public HashMap> historyPremise = new HashMap>(); + public HashMap> currentPremise = new HashMap>(); + public HashMap updateKnowledge = new LinkedHashMap(); + public String[] answer = {"",}; + public String nextStep = ""; + public HashMap featureMap = new HashMap(); + public String indexName = ""; + public int id = 0; + public String configName = ""; + public String status = "waiting"; + //public ArrayList indexName = new ArrayList(); + + public Action(int priority) { + this.priority = priority; + this.activePriority = priority; + } + + /** + * + * @param originAction 这个action的初始状态 + * @param basePriority 激活originAction的action的条件数量 + * @param baseAuxiliaryPriority 激活originAction的action的辅助优先级 + */ + public Action(Action originAction, int basePriority, int baseAuxiliaryPriority) { + this.priority = originAction.priority; + this.keywordSet = originAction.keywordSet; + this.historyPremise = originAction.historyPremise; + this.currentPremise = originAction.currentPremise; + this.answer = originAction.answer; + this.nextStep = originAction.nextStep; + this.featureMap = originAction.featureMap; + this.updateKnowledge = originAction.updateKnowledge; + this.indexName = originAction.indexName; + this.id = originAction.id; + this.configName = originAction.configName; + this.status = originAction.status; + this.activePriority = originAction.activePriority + basePriority + 1; //激活会多一个优先级 + + + //如果激活originAction的action,它的辅助优先级高于originAction,那么。。 + if(baseAuxiliaryPriority > originAction.auxiliaryPriority) + this.auxiliaryPriority = baseAuxiliaryPriority; + else + this.auxiliaryPriority = originAction.auxiliaryPriority; + } + + public Action() { + } + +} diff --git a/src/entity/ConfigTerm.java b/src/entity/ConfigTerm.java new file mode 100644 index 0000000..8dd3b5d --- /dev/null +++ b/src/entity/ConfigTerm.java @@ -0,0 +1,495 @@ +package com.qiwu.chatbotbackend.entity; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +public class ConfigTerm implements Cloneable{ + + static int iterNum = 0; + + private int id = 0; + private String jCurPremise = ""; + private String jHisPremise = ""; + private String jFeature = ""; + + + private String jNextStep = ""; + private String jReply = ""; + private String jAuxiliaryPriority = "0"; + private int jStatus = 0; + + + private String curPremise = ""; + private String hisPremise = ""; + private String feature = ""; + private String reply = ""; + private String nextStep = ""; + private String updateKnowledge = ""; + private String nextStepStatus = "return"; + private String configName = ""; + private String auxiliaryPriority = "1"; + private String status = "waiting"; + + + public void setjStatus(int jStatus) { + this.jStatus = jStatus; + } + public String getFeature() { + return feature; + } + + public void setFeature(String feature) { + this.feature = feature; + } + + public String getCurPremise() { + return curPremise; + } + + public String getNextStep() { + return nextStep; + } + + public void setNextStep(String nextStep) { + this.nextStep = nextStep; + } + public String getConfigName() { + return configName; + } + + public void setConfigName(String configName, Boolean append) { + + if(append) { + iterNum++; + this.configName = configName + "_" + iterNum; + }else{ + this.configName = configName; + } + } + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + + public String getjCurPremise() { + return jCurPremise; + } + + public void setjCurPremise(String jCurPremise) { + this.jCurPremise = jCurPremise; + } + + public String getjHisPremise() { + return jHisPremise; + } + + public void setjHisPremise(String jHisPremise) { + this.jHisPremise = jHisPremise; + } + + public String getjFeature() { + return jFeature; + } + + public void setjFeature(String jFeature) { + this.jFeature = jFeature; + } + + public String getjNextStep() { + return jNextStep; + } + + public void setjNextStep(String jNextStep) { + this.jNextStep = jNextStep; + } + + public String getjReply() { + return jReply; + } + + public void setjReply(String jReply) { + this.jReply = jReply; + } + + public String getjAuxiliaryPriority() { + return jAuxiliaryPriority; + } + + public void setjAuxiliaryPriority(String jAuxiliaryPriority) { + this.jAuxiliaryPriority = jAuxiliaryPriority; + } + + public int getjStatus() { + return jStatus; + } + + public void setCurPremise(String curPremise) { + this.curPremise = curPremise; + } + + public String getHisPremise() { + return hisPremise; + } + + public void setHisPremise(String hisPremise) { + this.hisPremise = hisPremise; + } + + public String getReply() { + return reply; + } + + public void setReply(String reply) { + this.reply = reply; + } + + public String getAuxiliaryPriority() { + return auxiliaryPriority; + } + + public String getStatus() { + return status; + } + + public String getNextStepStatus() { + return nextStepStatus; + } + + public String getUpdateKnowledge() { + return updateKnowledge; + } + + public void setUpdateKnowledge(String updateKnowledge) { + this.updateKnowledge = updateKnowledge; + } + + + static Map statusMap = new HashMap() { + { + put("return", "return"); + put("return-1", "back"); + put("return-0", "stay"); + put("activate", "activate"); + put("activate:after", "activate:after"); + } + }; + + public void setStatus(String status) { + this.status = status; + } + public void setAuxiliaryPriority(String auxiliaryPriority) { + this.auxiliaryPriority = auxiliaryPriority; + } + + public void setNextStepStatus(String nextStepStatus) { + this.nextStepStatus = nextStepStatus; + } + + public ConfigTerm(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge) { + this.curPremise = curPremise; + this.hisPremise = hisPremise; + this.feature = feature; + if (!updateKnowledge.equals("")) + this.updateKnowledge += "updateKnowledge-<-" + updateKnowledge; + + this.reply = reply; + this.nextStep = nextStep; + } + + public ConfigTerm(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge, Map autoJumpUpdateKnowledge) { + this.curPremise = curPremise; + this.hisPremise = hisPremise; + this.feature = feature; + this.updateKnowledge = appendKnowledgeStr(autoJumpUpdateKnowledge, updateKnowledge); + //if (!updateKnowledge.equals("")) + // this.updateKnowledge += "updateKnowledge-<-" + updateKnowledge; + + this.reply = reply; + this.nextStep = nextStep; + } + + + public ConfigTerm(List curPremise, List hisPremise, Map updateKnowledge, String extraCP, String extraHP, String extraUK, String feature, String reply, String nextStep, String auxiliaryPriority) { + this.curPremise = appendPremiseStr(curPremise, extraCP); + this.hisPremise = appendPremiseStr(hisPremise, extraHP); + this.updateKnowledge = appendKnowledgeStr(updateKnowledge, extraUK); + this.feature = feature; + this.reply = reply; + this.nextStep = nextStep; + this.auxiliaryPriority = auxiliaryPriority; + } + + public String appendPremiseStr(List premises, String extraPM) { + StringBuffer sb = new StringBuffer(); + String premiseStr = ""; + + for (String premise : premises) + sb.append("," + premise); + if (sb.length() > 0) + sb.deleteCharAt(0); //删除第一个逗号 + + + if (!extraPM.equals("")) { + if (sb.length() == 0) + sb.append(extraPM); + else + sb.append("," + extraPM); + } else if (sb.length() == 0) { + sb.append(" "); + } + premiseStr = sb.toString(); + + return premiseStr; + } + + public String appendKnowledgeStr(Map knowledge, String extraKL) { + 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); + + 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 + knowledgeStr = ""; + + return knowledgeStr; + } + + + public void appendJPremise(JSONArray premiseList, String premise, Map conditionDescription) { + //System.out.println(premise); + + String pair1[] = premise.split("=", 2); + String key = pair1[0]; + + String keywords = pair1[1]; + String pair2[] = key.split("::"); + String conditionName = pair2[0]; + String pair3[] = pair2[1].split("-"); + String cmpType = pair3[0]; + String operator = ""; + if (pair3.length > 1) + operator = pair3[1]; + + String question = ""; + if (conditionDescription.get(conditionName) != null) + question = conditionDescription.get(conditionName); + + JSONObject premiseJ = new JSONObject(); + premiseJ.put("keywords", keywords); + premiseJ.put("actionName", conditionName); + premiseJ.put("cmpType", cmpType); + premiseJ.put("question", question); + premiseJ.put("operator", operator); + + premiseList.add(premiseJ); + + } + + public void appendJKnowledge(JSONArray knowledgeList, String knowledge, Map conditionDescription) { + String pair[] = knowledge.split(":", 2); + + if (knowledge.equals("") || pair.length < 2) + return; + + String question = ""; + if (conditionDescription.get(pair[0]) != null) + question = conditionDescription.get(pair[0]); + + JSONObject knowledgeJ = new JSONObject(); + knowledgeJ.put("variableName", pair[0]); + knowledgeJ.put("keyword", pair[1]); + + knowledgeList.add(knowledgeJ); + } + + public void appendJNextStep(JSONArray nextStepList, String next, Map conditionDescription) { + String pair[] = next.split("-"); + JSONObject nextStepJ = new JSONObject(); + JSONArray exceptJ = new JSONArray(); + + for (int i = 1; i < pair.length; i++) + exceptJ.add(pair[i]); + + String question = ""; + if (conditionDescription.get(pair[0]) != null) + question = conditionDescription.get(pair[0]); + + nextStepJ.put("nextStep", pair[0]); + nextStepJ.put("except", exceptJ); + nextStepJ.put("nextStepText", question); + nextStepList.add(nextStepJ); + } + + public JSONObject toJson(Map conditionDescription) { + JSONObject data = new JSONObject(); + JSONArray curPremiseList = new JSONArray(); + JSONArray hisPremiseList = new JSONArray(); + + //添加当前对话内容 + for (String premise : curPremise.split(",")) { + if (!premise.equals("") && !premise.equals(" ")) + appendJPremise(curPremiseList, premise, conditionDescription); + } + data.put("currentPremiseList", curPremiseList); + + //添加已知信息的内容 + for (String premise : hisPremise.split(",")) { + if (!premise.equals("") && !premise.equals(" ")) + appendJPremise(hisPremiseList, premise, conditionDescription); + } + data.put("historyPremiseList", hisPremiseList); + + //添加下一步状态 + + + //添加configName + data.put("configName", configName); + + //添加config状态 + data.put("configStatus", jStatus); + + + boolean doPost = false; + String postURL = "", postType = "all", pair[]; + + for (String feat : feature.split(",")) { + if (feat.startsWith("post")) { + doPost = true; + pair = feat.substring(0, feat.length() - 1).split("\\(", 2); + postURL = pair[1]; + postType = pair[0].split("::")[1]; + }else if(feat.equals("return-0")){ + nextStepStatus = "return-0"; + }else if(feat.equals("activate")){ + nextStepStatus = "activate"; + }else if(feat.equals("activate:after")){ + nextStepStatus = "activate:after"; + } + } + + + data.put("nextStepStatus", statusMap.get(nextStepStatus)); + //添加post参数 + data.put("doPost", doPost); + data.put("postURL", postURL); + data.put("postType", postType); + + //添加回答 + data.put("reply", reply); + + //添加config类别id + data.put("categoryId", 0); + + //添加辅助优先级 + data.put("auxiliaryPriority", auxiliaryPriority); + + //添加更新答案处的信息 + JSONArray knowledgeList = new JSONArray(); + if (!updateKnowledge.equals("")) { + for (String knowledge : updateKnowledge.split("-<-")) { + appendJKnowledge(knowledgeList, knowledge, conditionDescription); + } + } + data.put("updateKnowledge", knowledgeList); + + //添加下一步 + JSONArray nextStepList = new JSONArray(); + for (String next : nextStep.split(",")) { + appendJNextStep(nextStepList, next, conditionDescription); + } + data.put("nextStepList", nextStepList); + + return data; + } + + public String toString() { + + String text = curPremise + "|" + + hisPremise + "|" + + feature + "," + updateKnowledge + "," + nextStepStatus + "|" + + "auxiliaryPriority=" + auxiliaryPriority + "|" + + "configName=" + configName + "|=>|" + + reply + "|" + + "nextStep=" + nextStep + "|" + + "status=" + status + "|" + + "configId="; + + return text; + } + + public Object clone() { + Object o=null; + try{ + o= super.clone(); + }catch(CloneNotSupportedException e){ + System.out.println(e.toString()); + } + return o; + } + + + public static void activateCopy(ConfigTerm configTerm, List configTermList, String name){ + + configTerm.setReply(configTerm.getReply() + "{临时变量reply-2}"); + + + ConfigTerm configTerm2 = (ConfigTerm) configTerm.clone(); +// if(configTerm.getHisPremise().equals(" ")) +// configTerm.setHisPremise("临时变量condition::match-Include=+null"); +// else +// configTerm.setHisPremise(configTerm.getjHisPremise() + ",临时变量condition::match-Include=+null"); +// configTerm.setConfigName(name, true); + + if(configTerm2.getUpdateKnowledge().equals("")) + configTerm2.setUpdateKnowledge("process-nextStep:var={临时变量condition-2}"); + else + configTerm2.setUpdateKnowledge(configTerm2.getUpdateKnowledge() + "-<-process-nextStep:var={临时变量condition-2}"); + configTerm2.setConfigName(name, true); + + + //configTermList.add(configTerm); + configTermList.add(configTerm2); + + } + + + public static ConfigTerm simpleCopy(ConfigTerm configTerm){ + + ConfigTerm configTerm2 = (ConfigTerm) configTerm.clone(); + + return configTerm2; + } +} diff --git a/src/entity/UserInfo.java b/src/entity/UserInfo.java index af785eb..cfe6ada 100644 --- a/src/entity/UserInfo.java +++ b/src/entity/UserInfo.java @@ -8,7 +8,7 @@ import java.util.List; */ public class UserInfo { public UserInfo(String botAccount) { - this.conditionTable = new HashMap>(); + this.conditionTable = new HashMap>(); this.configStr = ""; this.botAccount = botAccount; this.extraInfo = new HashMap() { @@ -17,18 +17,18 @@ public class UserInfo { } }; this.id2config = new HashMap(); - this.id2condition = new HashMap(); + this.id2condition = new HashMap(); this.varInitialMap = new HashMap(); - this.name2condition = new HashMap(); + this.name2condition = new HashMap(); } - public HashMap> conditionTable; + public HashMap> conditionTable; public String configStr; public String botAccount; public HashMap extraInfo; public HashMap id2config; - public HashMap id2condition; - public HashMap name2condition; + public HashMap id2condition; + public HashMap name2condition; //存储需要初始化的变量 public HashMap varInitialMap; diff --git a/src/gameDesign/CharacterConstructor.java b/src/gameDesign/CharacterConstructor.java index e254a1b..9936164 100644 --- a/src/gameDesign/CharacterConstructor.java +++ b/src/gameDesign/CharacterConstructor.java @@ -3,7 +3,7 @@ package com.qiwu.chatbotbackend.gameDesign; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.JConfig; +import com.qiwu.chatbotbackend.entity.ConfigTerm; import com.qiwu.chatbotbackend.entity.UserInfo; import java.util.*; @@ -128,66 +128,66 @@ public class CharacterConstructor extends ElementConstructor { //根据根据NPC的名字查询地点 for (String conditionName : locationRelateConditions) { - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + keywordMap.get("npc_" + conditionName), " ", "match,return-0", "", "yaobuyao", "npc_query:queryLocationByConditionName:" + conditionName ); - JConfig.activateCopy(jConfig, jConfigList, "npc"); + ConfigTerm.activateCopy(configTerm, configTermList, "npc"); //zainali 和wenzainali 都识别到时优先匹配wenzainali - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + keywordMap.get("npc_" + conditionName) + "," + "zainali::match-Keyword=" + keywordMap.get("map_zainali").toString(), " ", "match,return-0", "", "yaobuyao", "npc_query:queryLocationByConditionName:" + conditionName ); - JConfig.activateCopy(jConfig, jConfigList, "npc"); - //jConfigList.add(jConfig); + ConfigTerm.activateCopy(configTerm, configTermList, "npc"); + //configTermList.add(configTerm); } //根据根据NPC名字和属性查询属性值 for(String conditionName: attrRelateConditions){ - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + keywordMap.get("npc_" + conditionName), " ", "match,return-0", "", "yaobuyao", "npc_query:queryAttrByNPCName:" + conditionName ); - JConfig.activateCopy(jConfig, jConfigList, "npc"); + ConfigTerm.activateCopy(configTerm, configTermList, "npc"); } //根据根据NPC类别和地点属性查询所有NPC实例 for (String conditionName : classRelateConditions) { - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + keywordMap.get("npc_" + conditionName), " ", "match,return-0", "", "yaobuyao", "npc_query:queryAroundNpcByClassName:" + conditionName ); - JConfig.activateCopy(jConfig, jConfigList, "npc"); - //jConfigList.add(jConfig); + ConfigTerm.activateCopy(configTerm, configTermList, "npc"); + //configTermList.add(configTerm); } //根据类名查询周围所有实例 for (String conditionName : findRelateConditions) { - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + keywordMap.get("npc_" + conditionName).toString(), " ", "match,return-0", "", " ", "npc_query:queryFindNPCWay:" + conditionName ); - JConfig.activateCopy(jConfig, jConfigList, "npc"); + ConfigTerm.activateCopy(configTerm, configTermList, "npc"); } //查询说话的人 for (String conditionName : talkerRelateConditions) { - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + keywordMap.get("talker_" + conditionName).toString().replace("botname", botName), " ", "match,return-0", "", " ", "npc_query:queryLastTalker:" ); - JConfig.activateCopy(jConfig, jConfigList, "npc"); + ConfigTerm.activateCopy(configTerm, configTermList, "npc"); } diff --git a/src/gameDesign/ElementConstructor.java b/src/gameDesign/ElementConstructor.java index 252613e..dc83cd0 100644 --- a/src/gameDesign/ElementConstructor.java +++ b/src/gameDesign/ElementConstructor.java @@ -3,7 +3,7 @@ package com.qiwu.chatbotbackend.gameDesign; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.JConfig; +import com.qiwu.chatbotbackend.entity.ConfigTerm; import com.qiwu.chatbotbackend.entity.UserInfo; import java.util.*; @@ -19,7 +19,7 @@ public class ElementConstructor { Map keywordMap = null; SqlHelper helper = null; HashSet exceptRelation = null; - JConfig jConfig = null; + ConfigTerm configTerm = null; String CHITCHAT_URL = "http:192.168.1.178:1111/test"; String botAccount; @@ -29,7 +29,7 @@ public class ElementConstructor { List configDataList = new ArrayList(); - List jConfigList = new ArrayList(); + List configTermList = new ArrayList(); StringBuffer configText = new StringBuffer(); Map varInitialMap = new HashMap(); Map conditionDescription = new HashMap(); @@ -46,8 +46,8 @@ public class ElementConstructor { public void construct(JSONObject gameElements, UserInfo userinfo) { } - public List getjConfigList() { - return jConfigList; + public List getConfigTermList() { + return configTermList; } public Map getConditionDescription() { @@ -69,12 +69,12 @@ public class ElementConstructor { public void generateConfigText(List idList) { int id, length = idList.size(); String varValue; - JConfig jConfig = null; + ConfigTerm configTerm = null; for (int i = 0; i < length; i++) { - jConfig = jConfigList.get(i); + configTerm = configTermList.get(i); id = idList.get(i); - configText.append(jConfig.toString() + id + "\n"); + configText.append(configTerm.toString() + id + "\n"); } for (String varName : varInitialMap.keySet()) { varValue = varInitialMap.get(varName); diff --git a/src/gameDesign/ItemConstructor.java b/src/gameDesign/ItemConstructor.java index 0f0cb9e..3882487 100644 --- a/src/gameDesign/ItemConstructor.java +++ b/src/gameDesign/ItemConstructor.java @@ -3,7 +3,7 @@ package com.qiwu.chatbotbackend.gameDesign; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.JConfig; +import com.qiwu.chatbotbackend.entity.ConfigTerm; import com.qiwu.chatbotbackend.entity.UserInfo; import java.util.*; @@ -109,7 +109,7 @@ public class ItemConstructor extends ElementConstructor { //与地点查询相关的condition for(String conditionName: locationRelateConditions){ - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + keywordMap.get("item_" + conditionName).toString() + "," + "zainali::match-Keyword=" + keywordMap.get("map_zainali").toString(), " ", "match,return-0", @@ -117,65 +117,65 @@ public class ItemConstructor extends ElementConstructor { " ", "goods_query:queryLocationByConditionName:" + conditionName ); - JConfig.activateCopy(jConfig, jConfigList, "item"); - jConfig = new JConfig( + ConfigTerm.activateCopy(configTerm, configTermList, "item"); + configTerm = new ConfigTerm( conditionName + "::match-Include=" + keywordMap.get("item_" + conditionName).toString(), " ", "match,return-0", "", " ", "goods_query:queryLocationByConditionName:" + conditionName ); - JConfig.activateCopy(jConfig, jConfigList, "item"); + ConfigTerm.activateCopy(configTerm, configTermList, "item"); } //根据根据物品名字和属性查询属性值 for (String conditionName : attrRelateConditions) { - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + keywordMap.get("item_" + conditionName).toString(), " ", "match,return-0", "", " ", "goods_query:queryAttrByGoodsName:" + conditionName ); - JConfig.activateCopy(jConfig, jConfigList, "item"); + ConfigTerm.activateCopy(configTerm, configTermList, "item"); } //根据类名查询周围所有实例 for (String conditionName : attrRelateConditions) { - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + classKeywords, " ", "match,return-0", "", " ", "goods_query:queryAroundGoodsByClassName:" + conditionName ); - JConfig.activateCopy(jConfig, jConfigList, "item"); + ConfigTerm.activateCopy(configTerm, configTermList, "item"); } //根据类名查询周围所有实例 for (String conditionName : ownRelateConditions) { - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + keywordMap.get("item_" + conditionName).toString(), " ", "match,return-0", "", " ", "goods_query:queryPlayerItems:" + conditionName ); - JConfig.activateCopy(jConfig, jConfigList, "item"); + ConfigTerm.activateCopy(configTerm, configTermList, "item"); } //根据类名查询周围所有实例 for (String conditionName : findRelateConditions) { - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + keywordMap.get("item_" + conditionName).toString(), " ", "match,return-0", "", " ", "goods_query:queryFindItemWay:" + conditionName ); - JConfig.activateCopy(jConfig, jConfigList, "item"); + ConfigTerm.activateCopy(configTerm, configTermList, "item"); } } catch(Exception e){ diff --git a/src/gameDesign/ListeningConstructor.java b/src/gameDesign/ListeningConstructor.java new file mode 100644 index 0000000..3db91e5 --- /dev/null +++ b/src/gameDesign/ListeningConstructor.java @@ -0,0 +1,116 @@ +package com.qiwu.chatbotbackend.gameDesign; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.ConfigTerm; +import com.qiwu.chatbotbackend.entity.UserInfo; + +import java.util.*; + +import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor2.*; + +public class ListeningConstructor extends ElementConstructor{ + + public ListeningConstructor(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { + super(); + this.helper = helper; + this.botId = botId; + this.botAccount = botAccount; + this.exceptRelation = exceptRelation; + this.keywordMap = keywordMap; + this.POS = POS; + } + + public void construct(JSONObject jsonObject, UserInfo userinfo) { + + + + + } + + public static void cc(String botAccount, JSONObject gameELments, HashMap plotIndex, List configTermList){ + int size = 0; + String feature, nextPlotId, reply = "", nextCondition = "", nextLocation = "", priority; + String nTaskLineName, lastTaskCondition, lastTaskReply, nextGameStep; + Boolean autoJump = false; + List curPremiseList = new ArrayList(); + List hisPremiseList = new ArrayList(); + JSONArray listeningActions = gameELments.getJSONArray("listeningActions"); + JSONObject plotNode = null; + size = listeningActions.size(); + JSONObject config = null; + + for(int i = 0; i < size;i++){ + plotNode = null; + autoJump = false; + priority = "1"; + feature = "match"; + config = listeningActions.getJSONObject(i); + curPremiseList = JSONArray.parseArray(config.getJSONArray("curPremise").toJSONString(), String.class); + hisPremiseList = JSONArray.parseArray(config.getJSONArray("hisPremise").toJSONString(), String.class); + Map updateKnowledge = JSONObject.parseObject(config.getJSONObject("updateKnowledge").toJSONString(), Map.class); + nextPlotId = config.getString("nextPlotId"); + + if(nextPlotId != null){ + plotNode = plotIndex.get(nextPlotId); + } + + + if(plotNode != null){ + reply = plotNode.getString("plotText"); + nextCondition = plotNode.getString("conditionName"); + nextLocation = plotNode.getString("place"); + autoJump = plotNode.getBoolean("autoJump"); + + + if(nextCondition == null || nextCondition.equals("")){ + nextCondition = "yaobuyao"; + } + + if(autoJump){ + feature = "match,activate:after"; + updateKnowledge.put("plot_jump_text", "str+" + reply); + nextCondition = "plot_" + nextPlotId + "_*"; + reply = ""; + }else{ + feature = "match"; + + } + + if(plotNode.getString("priority") != null) + priority = plotNode.getString("priority"); + + updateKnowledge.put(nextPlotId + "_from", ""); + updateKnowledge.put("site", nextLocation); + + + nTaskLineName = String.format(TASK_LINE, nextLocation); + //任务线最后一个condition + lastTaskCondition = String.format(TASK_CONDITION, nextLocation); + lastTaskReply = String.format(TASK_REPLY, nextLocation); + nextGameStep = String.format(GAME_STEP_FORMAT, botAccount,nextPlotId); + + + updateKnowledge.put(lastTaskCondition, nextCondition); + updateKnowledge.put(lastTaskReply, reply); + updateKnowledge.put(nextPlotId, "1"); //下一步设为1 + updateKnowledge.put(nTaskLineName, nextGameStep); + }else{ + feature = "match,return-0"; + } + + ConfigTerm configTerm = new ConfigTerm( + curPremiseList, + hisPremiseList, + updateKnowledge, + "", "", "", feature, reply, nextCondition, priority + ); + + System.out.println("生成:" + curPremiseList.get(0)); + configTermList.add(configTerm); + } + } + + +} diff --git a/src/gameDesign/MapConstructor.java b/src/gameDesign/MapConstructor.java index c18219c..9a4cfb8 100644 --- a/src/gameDesign/MapConstructor.java +++ b/src/gameDesign/MapConstructor.java @@ -3,7 +3,7 @@ package com.qiwu.chatbotbackend.gameDesign; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.JConfig; +import com.qiwu.chatbotbackend.entity.ConfigTerm; import com.qiwu.chatbotbackend.entity.UserInfo; import java.util.*; @@ -50,7 +50,7 @@ public class MapConstructor extends ElementConstructor { keywordMap.get("site_list").append("+").append(locationName); - taskLineName = String.format(PlotConstructor.TASK_LINE, locationName); + taskLineName = String.format(PlotConstructor2.TASK_LINE, locationName); if (!varInitialMap.containsKey(taskLineName)) { @@ -90,7 +90,7 @@ public class MapConstructor extends ElementConstructor { List neighbours = JSONArray.parseArray(locations.getJSONObject(i).getJSONArray("neighbours").toJSONString(), Integer.class); for (int neighbourId : neighbours) { JSONObject neighbourObject = id2j.get(neighbourId); - System.out.println(neighbourObject); + //System.out.println(neighbourObject); index = (Integer) neighbourObject.get("index"); matrix[i][index] = 1; matrix[index][i] = 1; @@ -155,6 +155,11 @@ public class MapConstructor extends ElementConstructor { script.put("WHO_YOU_ARE", "我是[人名]"); if(!script.containsKey("TASK_DESCRIPTION")) script.put("TASK_DESCRIPTION", "我们的任务是[任务描述]"); + if(!script.containsKey("ITEM_IS_YOURS")) + script.put("ITEM_IS_YOUR", "在你身上呢"); + if(!script.containsKey("FIND_ITEM_OWNER")) + script.put("FIND_INTEM_OWNER", "[物品名]在[人名]那"); + if(script == null){ @@ -205,14 +210,14 @@ public class MapConstructor extends ElementConstructor { conditionKeywords = keywordMap.get("map_" + condition).toString(); - jConfig = new JConfig( + configTerm = new ConfigTerm( condition + "::match-Include=" + conditionKeywords, " ", "match", "", "yaobuyao", "map_query:queryWhereIam:" ); - jConfig.setNextStepStatus("return-0"); - jConfig.setAuxiliaryPriority("1"); - JConfig.activateCopy(jConfig, jConfigList, "map"); + configTerm.setNextStepStatus("return-0"); + configTerm.setAuxiliaryPriority("1"); + ConfigTerm.activateCopy(configTerm, configTermList, "map"); } @@ -236,7 +241,7 @@ public class MapConstructor extends ElementConstructor { } - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + placeKeywords + ",isNeighbour:"+ conditionName + "::match-Include=0", " ", @@ -245,13 +250,13 @@ public class MapConstructor extends ElementConstructor { " ", "map_query:queryPathAt:" ); - jConfig.setNextStepStatus("return-0"); - jConfig.setAuxiliaryPriority("1"); - JConfig.activateCopy(jConfig, jConfigList, "map"); + configTerm.setNextStepStatus("return-0"); + configTerm.setAuxiliaryPriority("1"); + ConfigTerm.activateCopy(configTerm, configTermList, "map"); - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + placeKeywords + ",isNeighbour:"+ conditionName + "::match-Include=1+3+4", " " , @@ -260,14 +265,14 @@ public class MapConstructor extends ElementConstructor { " ", "map_query:queryPathAdjoin:" ); - jConfig.setNextStepStatus("return-0"); - jConfig.setAuxiliaryPriority("1"); - JConfig.activateCopy(jConfig, jConfigList, "map"); + configTerm.setNextStepStatus("return-0"); + configTerm.setAuxiliaryPriority("1"); + ConfigTerm.activateCopy(configTerm, configTermList, "map"); - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + placeKeywords + ",isNeighbour:"+ conditionName + "::match-Include=2", " " , @@ -276,9 +281,9 @@ public class MapConstructor extends ElementConstructor { " ", "map_query:queryHowToPathBySite:" + conditionName ); - jConfig.setNextStepStatus("return-0"); - jConfig.setAuxiliaryPriority("1"); - JConfig.activateCopy(jConfig, jConfigList, "map"); + configTerm.setNextStepStatus("return-0"); + configTerm.setAuxiliaryPriority("1"); + ConfigTerm.activateCopy(configTerm, configTermList, "map"); @@ -295,14 +300,14 @@ public class MapConstructor extends ElementConstructor { String placeA, placeB, pathNode; - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + conditionKeywords, " ", "match,return-0", "", " ", "map_query:queryCanGoBySite:" ); - jConfig.setNextStepStatus("return-0"); - jConfig.setAuxiliaryPriority("1"); - JConfig.activateCopy(jConfig, jConfigList, "map"); + configTerm.setNextStepStatus("return-0"); + configTerm.setAuxiliaryPriority("1"); + ConfigTerm.activateCopy(configTerm, configTermList, "map"); } @@ -311,7 +316,7 @@ public class MapConstructor extends ElementConstructor { * 生成‘我要去那里’所需要的配置文件 */ public void generateWantToThere(int[][] pathMatirx, int[][] preTable, JSONObject gameElements, Map keywordMap) { - String placeA, placeB, descriptionB, text, pathNode, lastTaskCondition, lastTaskReply; + String placeA, placeB, descriptionB, text, pathNode, lastTaskCondition, lastTaskReply, taskLine; String conditionName = "yaobuyao"; String conditionKeywords = "地点"; String start = (String) gameElements.get("start"); @@ -340,8 +345,9 @@ public class MapConstructor extends ElementConstructor { toSitekeywords.append(gotoSite); } - lastTaskCondition = String.format(PlotConstructor.TASK_CONDITION, placeA); - lastTaskReply = String.format(PlotConstructor.TASK_REPLY, placeA); + lastTaskCondition = String.format(PlotConstructor2.TASK_CONDITION, placeA); + lastTaskReply = String.format(PlotConstructor2.TASK_REPLY, placeA); + taskLine = String.format(PlotConstructor2.TASK_LINE, placeA); //地点任务和地点回答的初始化 @@ -357,26 +363,26 @@ public class MapConstructor extends ElementConstructor { * 要去某个地方,并且该地点相邻或者可以直接到达 */ conditionName = goRelateConditions[0]; - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + toSitekeywords + "," + ",isNeighbour:" + conditionName + "::match-Include=1+3+4", " ", "match, reutrn-0,activate", "{" + lastTaskReply + "-2}", "plot_" + placeA + "_*", "" ); - jConfig.setConfigName("map", true); - jConfigList.add(jConfig); + configTerm.setConfigName("map", true); + configTermList.add(configTerm); //上一个配置文件激活时的默认选项 - jConfig = new JConfig( + configTerm = new ConfigTerm( " ", " ", "", "{" + lastTaskReply + "-2}", " ", "process-nextStep:var={" + lastTaskCondition + "-2}-<-site:" + placeA - + "-<-npc_update:updateFollowerLocation:" + placeA + + "-<-npc_update:updateFollowerLocation:" + placeA + "-<-game_step:var={" + taskLine + "-2}" ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("plot_" + placeA + "_doudi", false); - jConfig.setjStatus(1); - jConfigList.add(jConfig); + configTerm.setStatus("sleeping"); + configTerm.setConfigName("plot_" + placeA + "_doudi", false); + configTerm.setjStatus(1); + configTermList.add(configTerm); } @@ -384,7 +390,7 @@ public class MapConstructor extends ElementConstructor { /** * 要去的地方就在当前地点 */ - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + toAllSiteskeywords + ",isNeighbour:" + conditionName + "::match-Include=0", " ", @@ -393,14 +399,14 @@ public class MapConstructor extends ElementConstructor { " ", "map_query:queryPathAt:" ); - jConfig.setConfigName("map", true); - jConfigList.add(jConfig); + configTerm.setConfigName("map", true); + configTermList.add(configTerm); /** * 要去的地方要经过几个地点才能到达 */ - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + toAllSiteskeywords + ",isNeighbour:" + conditionName + "::match-Include=2", " ", @@ -409,8 +415,8 @@ public class MapConstructor extends ElementConstructor { " ", "map_query:queryToDoPathBySite:" + conditionName ); - jConfig.setConfigName("map", true); - jConfigList.add(jConfig); + configTerm.setConfigName("map", true); + configTermList.add(configTerm); } @@ -424,12 +430,12 @@ public class MapConstructor extends ElementConstructor { String conditionName = "know_exist_what"; String conditionKeywords = keywordMap.get("people_" + conditionName).toString(); - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + conditionKeywords, " ", "match,return-0", "", "yaobuyao", "map_query:queryAroundNpcBySite:" ); - JConfig.activateCopy(jConfig, jConfigList, "map"); + ConfigTerm.activateCopy(configTerm, configTermList, "map"); } @@ -441,12 +447,12 @@ public class MapConstructor extends ElementConstructor { String conditionName = "know_exist_what"; String conditionKeywords = keywordMap.get("item_" + conditionName).toString(); - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + conditionKeywords, " ", "match,return-0", "", "yaobuyao", "map_query:queryAroundGoodsBySite:" ); - JConfig.activateCopy(jConfig, jConfigList, "map"); + ConfigTerm.activateCopy(configTerm, configTermList, "map"); } @@ -459,12 +465,12 @@ public class MapConstructor extends ElementConstructor { String conditionName = "know_exist_what_mohu"; String conditionKeywords = keywordMap.get("things_" + conditionName).toString(); - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + conditionKeywords, " ", "match,return-0", "", "yaobuyao", "map_query:queryAroundAllBySite:" ); - JConfig.activateCopy(jConfig, jConfigList, "map"); + ConfigTerm.activateCopy(configTerm, configTermList, "map"); } @@ -476,13 +482,13 @@ public class MapConstructor extends ElementConstructor { String conditionName = "know_exist_what"; String conditionKeywords = keywordMap.get("place_" + conditionName).toString(); - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + conditionKeywords, " ", "match,return-0", "", " ", "map_query:queryAroundPlace:" ); - jConfig.setNextStepStatus("return-0"); - JConfig.activateCopy(jConfig, jConfigList, "map"); + configTerm.setNextStepStatus("return-0"); + ConfigTerm.activateCopy(configTerm, configTermList, "map"); } @@ -495,13 +501,13 @@ public class MapConstructor extends ElementConstructor { String conditionName = "know_exist_what_mohu"; String conditionKeywords = keywordMap.get("we_have_" + conditionName).toString(); - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + conditionKeywords, " ", "match,return-0", "", " ", "goods_query:queryPlayerItems:" ); - jConfig.setNextStepStatus("return-0"); - JConfig.activateCopy(jConfig, jConfigList, "map"); + configTerm.setNextStepStatus("return-0"); + ConfigTerm.activateCopy(configTerm, configTermList, "map"); } @@ -521,13 +527,13 @@ public class MapConstructor extends ElementConstructor { String conditionKeywords = keywordMap.get("inner_" + conditionName).toString(); - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + conditionKeywords, " ", "match,return-0", "", " ", "map_query:queryInnerNpcBySite:" ); - jConfig.setNextStepStatus("return-0"); - JConfig.activateCopy(jConfig, jConfigList, "map"); + configTerm.setNextStepStatus("return-0"); + ConfigTerm.activateCopy(configTerm, configTermList, "map"); } @@ -546,13 +552,13 @@ public class MapConstructor extends ElementConstructor { String conditionName = "shishenme"; String conditionKeywords = keywordMap.get("task_" + conditionName).toString(); - jConfig = new JConfig( + configTerm = new ConfigTerm( conditionName + "::match-Include=" + conditionKeywords, " ", "match,return-0", "", " ", "map_query:queryTaskDescription:" ); - jConfig.setNextStepStatus("return-0"); - JConfig.activateCopy(jConfig, jConfigList, "map"); + configTerm.setNextStepStatus("return-0"); + ConfigTerm.activateCopy(configTerm, configTermList, "map"); } diff --git a/src/gameDesign/PlotConstructor2.java b/src/gameDesign/PlotConstructor2.java index 69a3555..b84c6d9 100644 --- a/src/gameDesign/PlotConstructor2.java +++ b/src/gameDesign/PlotConstructor2.java @@ -3,7 +3,7 @@ package com.qiwu.chatbotbackend.gameDesign; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.JConfig; +import com.qiwu.chatbotbackend.entity.ConfigTerm; import com.qiwu.chatbotbackend.entity.UserInfo; import java.io.*; @@ -19,22 +19,22 @@ public class PlotConstructor2 extends ElementConstructor { public static String TASK_DESCRIPTION = "globalVariable_任务"; public static String TALKER_PATTERN = "【%s@%s】"; - String GAME_STEP_FORMAT = "%s_plot_%s"; + public static String GAME_STEP_FORMAT = "%s_plot_%s"; JSONArray plots = null; HashMap> adjList = new HashMap>(); HashMap> revAdjList = new HashMap>(); - private HashMap id2j = new HashMap(); + private HashMap plotIndex = new HashMap(); HashMap visited = new HashMap(); + public HashMap getPlotIndex() { + return plotIndex; + } public static String TASK_LINE = "任务线_%s进度"; public static String TASK_CONDITION = "任务线%s最后一个condition"; public static String TASK_REPLY = "任务线%s最后的回答"; - public HashMap getId2j() { - return id2j; - } public PlotConstructor2(SqlHelper helper, int botId, String botAccount, Map keywordMap, HashSet exceptRelation, StringBuffer POS) { super(); @@ -61,8 +61,8 @@ public class PlotConstructor2 extends ElementConstructor { this.plots = plots; constructAdjList(plots); - if (id2j.containsKey(start)) { - String taskLineName = "任务线_" + id2j.get(start).get("place") + "进度"; + if (plotIndex.containsKey(start)) { + String taskLineName = "任务线_" + plotIndex.get(start).get("place") + "进度"; conditionDescription.put(taskLineName, taskLineName); if(jsonObject.get("firstUnknownText") == null) @@ -71,11 +71,11 @@ public class PlotConstructor2 extends ElementConstructor { varInitialMap.put("unknownText", (String)jsonObject.get("firstUnknownText")); - varInitialMap.put("game_step", String.format(GAME_STEP_FORMAT, botAccount, (String) id2j.get(start).get("id"))); + varInitialMap.put("game_step", String.format(GAME_STEP_FORMAT, botAccount, (String) plotIndex.get(start).get("id"))); conditionDescription.put("unknownText", "对于无法识别的问题做出的回答"); conditionDescription.put("game_step", "QA问答游戏进度"); - BFSGenerate4(id2j.get(start), userinfo, jsonObject); + BFSGenerate4(plotIndex.get(start), userinfo, jsonObject); varInitialMap.put(start, "1"); @@ -87,6 +87,8 @@ public class PlotConstructor2 extends ElementConstructor { return; } + ListeningConstructor.cc(botAccount, jsonObject, plotIndex, configTermList); + } catch(Exception e){ @@ -100,7 +102,7 @@ public class PlotConstructor2 extends ElementConstructor { //根据id构造邻接表 public void constructAdjList(JSONArray plots) { int length = plots.size(), branchSize; - String id = "", nextPlotId = ""; + String id = "", nextPlotId = "", nextPlotText; JSONObject plot = null; JSONArray branch = null; @@ -113,33 +115,53 @@ public class PlotConstructor2 extends ElementConstructor { adjList.put(id, new ArrayList<>()); } + varSlotFilt(plot, keywordMap); + //添加branch中的下一个plot branch = plot.getJSONArray("branch"); branchSize = branch.size(); for (int j = 0; j < branchSize; j++) { nextPlotId = (String) branch.getJSONObject(j).get("nextPlotId"); + + branch.getJSONObject(j).put("curPremise", premiseTextFilt(branch.getJSONObject(j).getJSONArray("curPremise"))); + branch.getJSONObject(j).put("hisPremise", premiseTextFilt(branch.getJSONObject(j).getJSONArray("hisPremise"))); + + + //将剧情和相应文本相对应 + //plotTextIndex.put(nextPlotId, nextPlotText); + if (revAdjList.get(nextPlotId) == null) { revAdjList.put(nextPlotId, new ArrayList<>()); } - varSlotFilt(branch.getJSONObject(j), keywordMap); + adjList.get(id).add(nextPlotId); revAdjList.get(nextPlotId).add(id); } - id2j.put(id, plot); + plotIndex.put(id, plot); } } + JSONArray premiseTextFilt(JSONArray premiseList){ + int size = premiseList.size(); + for(int i = 0;i < size;i++){ + premiseList.set(i, premiseList.getString(i).replace("\r\n", "").replace("\n", "").replace("\r", "")); + } + + return premiseList; + } + /** * 如果剧情文本中出现变量槽,那么需要判断这个剧情的npc是不是在线模式,如果不是在线模式,就需要把变量槽过滤掉 - * @param branchNode + * @param plot */ - public static void varSlotFilt(JSONObject branchNode, Map keywordMap){ + public static void varSlotFilt(JSONObject plot, Map keywordMap){ String VARIABLE_SEARCH_PATTERN = "【(.*?)@(.*?)(\\$\\{.*?})", npcName, middleText = "", varSlot = ""; + System.out.println(plot.getString("id")); Pattern replacePattern = Pattern.compile(VARIABLE_SEARCH_PATTERN); - Matcher m = replacePattern.matcher(branchNode.getString("reply")); + Matcher m = replacePattern.matcher(plot.getString("plotText")); while (m.find()) { npcName = m.group(1); //onlineModeTalkers, 在CharecterConstructor中定义,q前面加一个逗号是为了防止出现子串匹配的问题 @@ -148,7 +170,7 @@ public class PlotConstructor2 extends ElementConstructor { if(keywordMap.get("onlineModeTalkers").indexOf("," + npcName + ",") == -1) { varSlot = m.group(3); middleText = m.group(2); - branchNode.put("reply", branchNode.getString("reply").replace(npcName + "@" + middleText + varSlot, npcName + "@" + middleText)); + plot.put("plotText", plot.getString("plotText").replace(npcName + "@" + middleText + varSlot, npcName + "@" + middleText)); } } @@ -164,11 +186,11 @@ public class PlotConstructor2 extends ElementConstructor { */ public void BFSGenerate4(JSONObject root, UserInfo userinfo, JSONObject jsonObject) { String id, rootId = (String) root.get("id"), adjId, nextId, conditionName = "yaobuyao", - nextUnknownText, curUnknownText, nextCondition, location, nextLocation, nextGameStep, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition, reply; - String beforeJumpLocatin, jumpNextNextId, jumpNextNextLocation, extraBeforeJumpUK; - JSONObject node = null, branchNode = null, adjNode = null; - StringBuffer skipText = new StringBuffer(); - String extraHP = "", extraUK = "", extraFT = ""; + nextUnknownText, curUnknownText, nextCondition, location, nextLocation, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition, reply; + String hint, gameStep, nextGameStep; + JSONObject node = null, branchNode = null; + Boolean curAutoJump, nextAutoJump = false, prevAutoJump, moveWithPlot = false; + StringBuffer skipText = new StringBuffer(), extraUK = new StringBuffer(), extraHP = new StringBuffer(), extraFT = new StringBuffer(), arriveUK = new StringBuffer(); JSONArray branch = null; @@ -178,6 +200,8 @@ public class PlotConstructor2 extends ElementConstructor { root.put("nextUnknownText", varInitialMap.get("unknownText")); root.put("parentId", "null"); + root.put("autoJump", false); + root.put("prevAutoJump", false); jsonObject.put("plotStartText", ((String)jsonObject.get("plotStartText")).replace("\n", "").replace(",", ",")); if(root.get("conditionName") != null && !root.get("conditionName").equals("")) @@ -194,7 +218,7 @@ public class PlotConstructor2 extends ElementConstructor { String startTaskCondition = String.format(PlotConstructor2.TASK_CONDITION, startPlace); String startTaskReply = String.format(PlotConstructor2.TASK_REPLY, startPlace); varInitialMap.put("site", startPlace); - varInitialMap.put(startTaskLine, rootId); + varInitialMap.put(startTaskLine, String.format(GAME_STEP_FORMAT, botAccount, rootId)); varInitialMap.put(startTaskCondition, ""); varInitialMap.put(startTaskReply, ""); conditionDescription.put(startTaskLine, startTaskLine); @@ -205,7 +229,6 @@ public class PlotConstructor2 extends ElementConstructor { //generateStartGame(root, jsonObject, startPlace, conditionName); Queue queue = new LinkedList(); - Map autoJumpUpdateKnowledge = new HashMap(); queue.add(root); @@ -214,7 +237,9 @@ public class PlotConstructor2 extends ElementConstructor { id = (String) node.get("id"); location = ((String) node.get("place")).split("\\+")[0]; conditionName = (String) node.get("conditionName"); - curUnknownText = (String) node.get("nextUnknownText"); + curAutoJump = node.getBoolean("autoJump"); + prevAutoJump = node.getBoolean("prevAutoJump"); + curUnknownText = (String) node.get("unknownText"); taskLineName = String.format(PlotConstructor2.TASK_LINE, location); conditionDescription.put(id, "剧情" + id + "状态"); varInitialMap.put(id ,""); @@ -231,87 +256,51 @@ public class PlotConstructor2 extends ElementConstructor { for (int i = 0; i < branchSize; i++) { - System.out.println("branch:" + i); skipText.setLength(0); branchNode = branch.getJSONObject(i); + //reply = branchNode.getString("reply"); Map updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class); - //System.out.println("id:" + id + "剧情分支:" + branchNode.toJSONString()); - - nextUnknownText = updateKnowledge.get("unknownText"); - //System.out.println(id + "分支内" +nextUnknownText); - nextId = (String)branchNode.get("nextPlotId"); - //skipText.append(); - if(nextId == null || nextId.equals("") || !id2j.containsKey(nextId)){ + nextId = branchNode.getString("nextPlotId"); + moveWithPlot = branchNode.getBoolean("moveWithPlot"); + if(nextId == null || nextId.equals("") || !plotIndex.containsKey(nextId)){ nextId = id + "_end"; - branchNode.put("nextPlotId", nextId); createEndNode(node, id, nextId, curUnknownText); } - //保留下一步剧情的地点 - beforeJumpLocatin = ((String)id2j.get(nextId).get("place")).split("\\+")[0]; - autoJumpUpdateKnowledge.clear(); - - /** - * 自动跳转到下一个剧情,因为有可能存在多步自动跳转,所以要用一个while来处理, - * 如果下一步剧情是自动跳转,那么把下一步剧情的更新答案(属性)移到当前剧情,并将下一步剧情id改为下下步剧情id - */ - 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)branchNode.get("reply")); - branchNode.put("reply", jumpBranchNode.get("reply")); - Map newUpdateKnowledge = jumpBranchNode.getJSONObject("updateKnowledge"); - autoJumpUpdateKnowledge.putAll(newUpdateKnowledge); + if(moveWithPlot == null || curAutoJump) + moveWithPlot = true; - nextUnknownText = (String)newUpdateKnowledge.get("unknownText"); - System.out.println("循环内" +nextUnknownText); - //updateKnowledge.putAll(newUpdateKnowledge); - jumpNextNextId = (String)jumpBranchNode.get("nextPlotId"); + nextUnknownText = plotIndex.get(nextId).getString("unknownText"); + nextAutoJump = plotIndex.get(nextId).getBoolean("autoJump"); + reply = plotIndex.get(nextId).getString("plotText"); - //如果下一步剧情存在 - if(jumpNextNextId != null && !jumpNextNextId.equals("") && id2j.containsKey(jumpNextNextId)){ - System.out.println(jumpNextNextId); - System.out.println(id2j.get(jumpNextNextId)); - jumpNextNextLocation = (String)id2j.get(jumpNextNextId).get("place"); - autoJumpUpdateKnowledge.put("site", jumpNextNextLocation); - autoJumpUpdateKnowledge.put("npc_update", "updateFollowerLocation:" + jumpNextNextLocation); - branchNode.put("autoJump", jumpBranchNode.get("autoJump")); - }else { - jumpNextNextId = nextId + "_end"; - jumpBranchNode.put("nextPlotId", jumpNextNextId); - createEndNode(node, nextId, jumpNextNextId, curUnknownText); - branchNode.put("autoJump", false); - } - - branchNode.put("nextPlotId", jumpNextNextId); - } + /** + * 自动跳转到下一个剧情,因为有可能存在多步自动跳转,所以要用一个while来处理, + * 如果下一步剧情是自动跳转,那么把下一步剧情的更新答案(属性)移到当前剧情,并将下一步剧情id改为下下步剧情id + */ - nextId = (String) branchNode.get("nextPlotId"); - reply = (String)branchNode.get("reply"); if(reply.equals("")) reply = curUnknownText; //如果存在下一剧情,就将下一步剧情的condition设为下一个激活的conditin,把地点更新为下一步剧情的地点,并更新任务线进度 - nextCondition = (String) id2j.get(nextId).get("conditionName"); + nextCondition = plotIndex.get(nextId).getString("conditionName"); if(nextCondition.equals("")) nextCondition = "yaobuyao"; - nextLocation = ((String) id2j.get(nextId).get("place")).split("\\+")[0]; + nextLocation = plotIndex.get(nextId).getString("place"); //任务线 nTaskLineName = String.format(TASK_LINE, nextLocation); @@ -319,6 +308,16 @@ public class PlotConstructor2 extends ElementConstructor { lastTaskCondition = String.format(TASK_CONDITION, nextLocation); lastTaskReply = String.format(TASK_REPLY, nextLocation); +// if(nextId.endsWith("_end")) +// nextGameStep = id; +// else +// nextGameStep = nextId; + + + gameStep = String.format(GAME_STEP_FORMAT, botAccount, id); + nextGameStep = String.format(GAME_STEP_FORMAT, botAccount,nextId); + + /** * 额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情 @@ -329,17 +328,34 @@ public class PlotConstructor2 extends ElementConstructor { //现在暂时放开下一步剧情未发生过的限制条件 //extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1 + "," + nextId + "::match-Include=null"; - extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1; - extraUK = nTaskLineName + ":" + nextId + "-<-" + lastTaskCondition + ":" + nextCondition + "-<-" + lastTaskReply + ":" + reply + - "-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1" + "-<-plot_jump_text:" + skipText; + appendPremise(extraHP, taskLineName, "match", "Include", gameStep); + appendPremise(extraHP, "site", "match", "Include", location); + appendPremise(extraHP, id, "match", "Include", "1"); + + + appendKnowledge(extraUK, lastTaskCondition, nextCondition); + appendKnowledge(extraUK, lastTaskReply, reply); + appendKnowledge(extraUK, id, "+1"); //当前剧情状态加一 + appendKnowledge(extraUK, nextId, "1"); //下一步设为1 + appendKnowledge(extraUK, nTaskLineName, nextGameStep); + + + - if(!beforeJumpLocatin.equals(nextLocation)) { - //extraBeforeJumpUK = + //如果下一步剧情不存在,那么下一步剧情id为当前id加后缀_end,但是用户提交qa的game_step应该还是当前id,没有加上_end + if(nextId.endsWith("_end")) { + nextGameStep = String.format(GAME_STEP_FORMAT, botAccount,id); + } + + + System.out.println(id); + + appendFeature(extraFT, "match"); + //下一步为自动跳转且地点相同,则将回答放在plot_jump_text + if(doActivatePlot(nextAutoJump, location, nextLocation, moveWithPlot) ){ + appendKnowledge(extraUK, "plot_jump_text", "str+" + reply); } - if(nextId.endsWith("_end")) - nextGameStep = id; - else - nextGameStep = nextId; + /** @@ -373,19 +389,25 @@ public class PlotConstructor2 extends ElementConstructor { * 3. 当前剧情和下一步剧情更新状态 */ - String beforeJumpTaskCondition = String.format(TASK_CONDITION, beforeJumpLocatin); - String beforeJumpTaskReply = String.format(TASK_REPLY, beforeJumpLocatin); - String beforeJumpUK = "-<-" + beforeJumpTaskCondition + ":yaobuyao" + "-<-" + beforeJumpTaskReply + ":" + skipText + "-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1" ; + + if(branchNode.containsKey("activateExtraPlot")) { + //激活除了下一步剧情以外的剧情 + extraActivatedPlot(extraUK, nextLocation, branchNode.getJSONObject("activateExtraPlot")); + } + //如果主角的位置随着剧情移动或者下一步剧情地点和当前剧情相同,主角地点和game_step要做相应更新 - if((!branchNode.containsKey("moveWithPlot") || (Boolean)branchNode.get("moveWithPlot")) || location.equals(beforeJumpLocatin)) { - extraUK = beforeJumpUK + "-<-" + extraUK + "-<-site:" + nextLocation + "-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextGameStep); + if(moveWithPlot || location.equals(nextLocation)) { + appendKnowledge(extraUK, "site", nextLocation); + appendKnowledge(extraUK, "game_step", nextGameStep); + appendKnowledge(extraUK,"unknownText", nextUnknownText); + //extraUK += "-<-site:" + nextLocation + "-<-game_step:" + nextGameStep; + //如果当前剧情所在地喝下一步剧情所在地不一样,那么unknown文本 + //只有到达下一步剧情所在地时才会更新 - //自动跳转剧情如果有更新属性,这些数据也需要更新 - updateKnowledge.putAll(autoJumpUpdateKnowledge); - }else { + } else { //任务线最后一个condition @@ -397,40 +419,32 @@ public class PlotConstructor2 extends ElementConstructor { * 地点更新为跳转后的地点 */ //可能因为不存在自动跳转或者地点不同,所以执行现在的代码,如果在剧情中存在自动跳转的情况,那么应该比较自动跳转完成后的地点喝下一步剧情的地点是否相同 - if(!location.equals(beforeJumpLocatin)){ + if(!location.equals(nextLocation)){ //System.out.println(id + "报异常" + curUnknownText); if(curUnknownText.equals("")) { - reply = "请到" + beforeJumpLocatin; + + //如果没有unknown,就提示他到下一个地点 + hint = "请到" + nextLocation; //如果当前地点和下一步剧情地点不同,要提示 }else { - reply = curUnknownText; + //如果有unknown,就提示unknown文本 + hint = curUnknownText; } - //如果下一步剧情和当前剧情的地点是不一样的,那么在玩家没有到达下一个地点是剧情还是停留在当前剧情,只有到达目的地后,下一步剧情才会发生变化 - jConfig = new JConfig( - "yaobuyao::match-Keyword=+" + beforeJumpLocatin, - "game_step::match-Include=" + String.format(GAME_STEP_FORMAT, botAccount, id) + "," + id + "::number-BiggerOrEqual=" + 1, - "match", (String)branchNode.get("reply"), (String) nextCondition, - extraUK + "-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextGameStep) - + "-<-unknownText:" + nextUnknownText + "-<-site:" + nextLocation + "-<-npc_update:updateFollowerLocation:"+ nextLocation, autoJumpUpdateKnowledge - ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("plot_" + beforeJumpLocatin + "_" + id,false); - jConfig.setjStatus(1); + //下一部剧情在不同地点时,为了防止到达下个地点的剧情重复执行,需要加一个标志表示下一步剧情是否已经发生过 + appendKnowledge(extraUK, nextId + "_from", id); + - jConfigList.add(jConfig); - //如果当前剧情所在地喝下一步剧情所在地不一样,那么unknown文本 - //只有到达下一步剧情所在地时才会更新 - updateKnowledge.remove("unknownText"); - updateKnowledge.remove("site"); - extraUK = beforeJumpUK; + arriveActivatePlot2(jsonObject, id, nextId, nextLocation); //如果下一步剧情不在同一地点,那么即使有跳转剧情,也是在下一个地点才说 - skipText.setLength(0); + reply = hint; + + //必须在上一个jConfig添加完之后 //extraUK = extraUK.replace("-<-" + nextId + ":" + "+1", ""); @@ -444,50 +458,61 @@ public class PlotConstructor2 extends ElementConstructor { - extraFT = ""; //是否将当前识别到的数据加入到已知数据列表 if((Boolean)branchNode.get("includeCurInfo")){ - extraFT += ",includeCurInfo"; + appendFeature(extraFT, "includeCurInfo"); } if(branchNode.get("extraFeature") != null){ - extraFT += "," + branchNode.getString("extraFeature"); + appendFeature(extraFT, branchNode.getString("extraFeature")); } - jConfig = new JConfig( + + if(doActivatePlot(nextAutoJump, location, nextLocation, moveWithPlot) ){ + appendFeature(extraFT, "activate:after"); + nextCondition = "plot_" + nextId + "_*"; + } + + configTerm = new ConfigTerm( curPremiseList, historyPremiseList, updateKnowledge, - "", extraHP, extraUK, - "match"+extraFT, reply, (String) nextCondition, "1" + "", extraHP.toString(), extraUK.toString(), + extraFT.toString(), reply, nextCondition, "1" ); + configTerm.setConfigName("plot_" + id, true); - //当剧情没有条件限制时的操作 - if (curPremiseList.size() == 0 && historyPremiseList.size() == 0){ - unconditionalPlotProcess(jConfig, nextCondition); + //当剧情没有条件限制时的操作 ,额外要求上一步剧情不是自动跳转,因为自动跳转的标识放在了上一部剧情的分支里,所以是上上个分支是否存在自动跳转 + if (curPremiseList.size() == 0 && historyPremiseList.size() == 0 && !prevAutoJump){ + Boolean activateFlag = false; + if(extraFT.indexOf("activate") != -1) + activateFlag = true; + unconditionalPlotProcess(configTerm, nextCondition, activateFlag); } if (branchNode.getBoolean("higherPriority") != null && branchNode.getBoolean("higherPriority")) - jConfig.setAuxiliaryPriority("3"); - jConfigList.add(jConfig); + configTerm.setAuxiliaryPriority("3"); + configTermList.add(configTerm); //将子结点加入队列 - adjId = (String) branchNode.get("nextPlotId"); - if (visited.get(adjId) == null && id2j.get(adjId) != null) { - visited.put(adjId, true); - adjNode = id2j.get(adjId); - - adjNode.put("parentId", id); - //System.out.println("下一个剧情id:" + adjId + ",nextUnknownText:" + nextUnknownText); - adjNode.put("nextUnknownText", nextUnknownText); - queue.add(adjNode); - } else { - conditionDescription.put(adjId, "剧情" + adjId + "进度"); - varInitialMap.put(adjId, ""); + adjId = nextId; + plotEnQueue(queue, id, adjId, nextUnknownText, curAutoJump); + if(branchNode.getJSONObject("activateExtraPlot") != null){ + for(String activateId:branchNode.getJSONObject("activateExtraPlot").keySet()){ + plotEnQueue(queue, id, activateId, nextUnknownText, curAutoJump); + } } + extraFT.setLength(0); + extraHP.setLength(0); + extraUK.setLength(0); + skipText.setLength(0); + arriveUK.setLength(0); + + + } @@ -507,33 +532,33 @@ public class PlotConstructor2 extends ElementConstructor { * 4. 无论哪种情况都会跳下一步剧情 */ - jConfig = new JConfig( + configTerm = new ConfigTerm( " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("queryskip1",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); + configTerm.setStatus("sleeping"); + configTerm.setConfigName("queryskip1",false); + configTerm.setjStatus(1); + configTerm.setAuxiliaryPriority("0"); + configTermList.add(configTerm); - jConfig = new JConfig( + configTerm = new ConfigTerm( " ", "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); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); + configTerm.setStatus("sleeping"); + configTerm.setConfigName("queryskip2",false); + configTerm.setjStatus(1); + configTerm.setAuxiliaryPriority("0"); + configTermList.add(configTerm); - jConfig = new JConfig( + configTerm = new ConfigTerm( " ", "qa_status::match-Include=not_found", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}" ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("queryskip3",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); + configTerm.setStatus("sleeping"); + configTerm.setConfigName("queryskip3",false); + configTerm.setjStatus(1); + configTerm.setAuxiliaryPriority("0"); + configTermList.add(configTerm); @@ -544,66 +569,66 @@ public class PlotConstructor2 extends ElementConstructor { */ //处于激活状态,其他的属于待激活状态,jStatus这一条不设为1,而是0 - jConfig = new JConfig(" ", " ", "activate,post::gameQA(" + keywordMap.get("QA_URL").toString()+ ")", "", "unknown4,unknown3,unknown2,unknown1,common_answer", ""); - jConfig.setNextStepStatus("active"); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); + configTerm = new ConfigTerm(" ", " ", "activate,post::gameQA(" + keywordMap.get("QA_URL").toString()+ ")", "", "unknown4,unknown3,unknown2,unknown1,common_answer", ""); + configTerm.setNextStepStatus("active"); + configTerm.setAuxiliaryPriority("0"); + configTermList.add(configTerm); - jConfig = new JConfig( + configTerm = new ConfigTerm( " ", "qa_status::match-Include=not_found", "match,return-0", "{unknownText-2}", " ", "" ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("unknown1",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); + configTerm.setStatus("sleeping"); + configTerm.setConfigName("unknown1",false); + configTerm.setjStatus(1); + configTerm.setAuxiliaryPriority("0"); + configTermList.add(configTerm); - jConfig = new JConfig( + configTerm = new ConfigTerm( " ", "qa_status::match-Include=not_found,unknownText::match-Include=null", "match,return-0", "不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧", " ", "" ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("unknown2",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); + configTerm.setStatus("sleeping"); + configTerm.setConfigName("unknown2",false); + configTerm.setjStatus(1); + configTerm.setAuxiliaryPriority("0"); + configTermList.add(configTerm); - jConfig = new JConfig( + configTerm = new ConfigTerm( " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90,unknownText::match-Include=null", "match,return-0", "不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧", " ", "" ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("unknown3",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); + configTerm.setStatus("sleeping"); + configTerm.setConfigName("unknown3",false); + configTerm.setjStatus(1); + configTerm.setAuxiliaryPriority("0"); + configTermList.add(configTerm); - jConfig = new JConfig( + configTerm = new ConfigTerm( " ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match,return-0", "{unknownText-2}", " ", "" ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("unknown4",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); + configTerm.setStatus("sleeping"); + configTerm.setConfigName("unknown4",false); + configTerm.setjStatus(1); + configTerm.setAuxiliaryPriority("0"); + configTermList.add(configTerm); //由于剧情跳转时地点可能发生变化, qa问答的句子可能因为npc不再同一位置而被过滤掉,所以将common_answer的字符串合并放在postprocessing中 - jConfig = new JConfig( + configTerm = new ConfigTerm( " ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match,return-0", "" ," ", "" ); - jConfig.setStatus("sleeping"); - jConfig.setConfigName("common_answer",false); - jConfig.setjStatus(1); - jConfig.setAuxiliaryPriority("0"); - jConfigList.add(jConfig); + configTerm.setStatus("sleeping"); + configTerm.setConfigName("common_answer",false); + configTerm.setjStatus(1); + configTerm.setAuxiliaryPriority("0"); + configTermList.add(configTerm); //--------------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------------- @@ -612,48 +637,15 @@ public class PlotConstructor2 extends ElementConstructor { * ---------------------------------------------------------------------------------------------------- * 用于存档 */ - jConfig = new JConfig( + configTerm = new ConfigTerm( "save_game::match-Include=+要:存档", " ", "match,return-0,gameBackup", "{archiveOperation-2}" ," ", "" ); - jConfig.setAuxiliaryPriority("4"); - jConfigList.add(jConfig); + configTerm.setAuxiliaryPriority("4"); + configTermList.add(configTerm); } - /** - * 游戏开始的配置 - */ - public void generateStartGame(JSONObject root, JSONObject jsonObject, String startPlace, String conditionName){ - - //用于开始游戏的配置 - jConfig = new JConfig( - "start_options::match-Include=+开始+开始游戏+继续游戏+继续+重新开始", - "任务线" + startPlace + "最后一个condition::match-Include=+null", - "match", - (String)jsonObject.get("plotStartText"), - conditionName, - "任务线" + startPlace + "最后一个condition:" + conditionName + "-<-" + root.get("id") + ":+1" + - "-<-任务线" + startPlace + "最后的回答:" + (String)jsonObject.get("plotStartText") + "-<-" + String.format(TASK_LINE, startPlace) + ":" + root.get("id") - ); - jConfig.setAuxiliaryPriority("2"); - jConfigList.add(jConfig); - - jConfig = new JConfig( - " ", - "任务线" + startPlace + "最后一个condition::match-Include=+null", - "match", - "请说开始游戏或者继续游戏", - "start_options", - "" - ); - jConfig.setAuxiliaryPriority("2"); - jConfigList.add(jConfig); - } - - @Override - public void postProcessing(List idList, int categoryId){ - } public void createEndNode(JSONObject node, String id, String nextId, String nextUnknownText){ @@ -669,75 +661,20 @@ public class PlotConstructor2 extends ElementConstructor { endNode.put("place", location); endNode.put("conditionName", condition); endNode.put("id", nextId); - endNode.put("reply", nextUnknownText); + endNode.put("plotText", nextUnknownText); + endNode.put("autoJump", false); endNode.put("includeCurInfo", true); endNode.put("updateKnowledge", new ArrayList()); + endNode.put("unknownText", ""); - id2j.put(nextId, endNode); + plotIndex.put(nextId, endNode); visited.put(nextId, true); } void addGameStartPlot(JSONObject gameElements, Map keywordMap){ -// JSONObject startPlot = new JSONObject(); -// startPlot.put("id", "start"); -// startPlot.put("conditionName", "start_options"); -// startPlot.put("place", "哪呢? 还没开始呢"); -// startPlot.put("branch", new JSONArray()); -// -// JSONObject branch1 = new JSONObject(); -// branch1.put("curPremise", new JSONArray(){ -// { -// add("start_options::match-Include=+重新开始"); -// } -// }); -// -// branch1.put("higherPriority", true); -// branch1.put("hisPremise", new JSONArray()); -// branch1.put("extraFeature", "newGame"); -// branch1.put("reply", gameElements.get("plotStartText")); -// branch1.put("updateKnowledge", new JSONObject(){ -// { -// put("unknownText", gameElements.get("firstUnknownText")); -// } -// }); -// branch1.put("nextPlotId", gameElements.get("start")); -// branch1.put("includeCurInfo", false); -// -// -// -// startPlot.getJSONArray("branch").add(branch1); -// -// -// JSONObject branch2 = new JSONObject(); -// branch2.put("curPremise", new JSONArray(){ -// { -// add("start_options::match-Include=+开始+开始游戏+继续游戏+继续"); -// } -// }); -// -// branch2.put("higherPriority", true); -// branch2.put("hisPremise", new JSONArray()); -// branch2.put("reply", gameElements.get("plotStartText")); -// branch2.put("updateKnowledge", new JSONObject(){ -// { -// put("unknownText", gameElements.get("firstUnknownText")); -// } -// }); -// branch2.put("extraFeature", "loadLastArchive"); -// branch2.put("nextPlotId", gameElements.get("start")); -// branch2.put("includeCurInfo", false); -// if(gameElements.get("startAutoJump") != null) -// branch2.put("autoJump", gameElements.get("startAutoJump")); -// else -// branch2.put("autoJump", false); -// startPlot.getJSONArray("branch").add(branch2); -// -// -// gameElements.getJSONArray("plots").add(startPlot); -// gameElements.put("start", "start"); -// gameElements.put("firstUnknownText", "请说开始游戏或者继续游戏"); + File file = null; FileReader fr = null; @@ -756,7 +693,7 @@ public class PlotConstructor2 extends ElementConstructor { jsonStr = jsonStr.replace("site_list", keywordMap.get("site_list").toString()); JSONObject config = JSONObject.parseObject(jsonStr); - System.out.println(config.toJSONString()); + //System.out.println(config.toJSONString()); // jsonStr = jsonStr.replace("startAutoJump", gameElements.getString("startAutoJump")); // jsonStr = jsonStr.replace("startAutoJump", gameElements.getString("startAutoJump")); gameElements.getJSONArray("plots").addAll(config.getJSONArray("gameStart")); @@ -777,23 +714,31 @@ public class PlotConstructor2 extends ElementConstructor { //如果是无条件剧情,那么需要跟着一个激活操作 - public void unconditionalPlotProcess(JConfig jConfig, String nextCondition){ - jConfig.setFeature(jConfig.getFeature() + ",activate,post::gameQA(" + keywordMap.get("QA_URL").toString() + ")"); - jConfig.setNextStep("queryskip*,map*,item*,npc*"); - jConfig.setUpdateKnowledge(jConfig.getUpdateKnowledge() + "-<-临时变量condition:"+ nextCondition +"-<-临时变量reply:var={reply-3}"); - jConfig.setNextStepStatus("active"); + public void unconditionalPlotProcess(ConfigTerm configTerm, String nextCondition, Boolean activateFlag){ + configTerm.setFeature(configTerm.getFeature() + ",activate,post::gameQA(" + keywordMap.get("QA_URL").toString() + ")"); + + // + //if() + if(activateFlag){ + configTerm.setNextStep(nextCondition+ ",queryskip*,map*,item*,npc*"); + }else { + configTerm.setNextStep("queryskip*,map*,item*,npc*"); + } + + //将本配置条目中nextStep的值放在“临时变量condition”中,将本配置条目中的回答放在“临时变量reply”中 + configTerm.setUpdateKnowledge(configTerm.getUpdateKnowledge() + "-<-临时变量condition:"+ nextCondition +"-<-临时变量reply:var={reply-3}"); + configTerm.setNextStepStatus("active"); } public void appendPremise(StringBuffer premiseStr, String conditionName, String cmpType, String operator, String value){ int strLen = premiseStr.length(); + String split_punt = ""; - if(strLen == 0 || strLen == 1){ - premiseStr = new StringBuffer(); - }else{ - premiseStr.append(","); - } + if(premiseStr.length() != 0) + split_punt = ","; + premiseStr.append(split_punt); premiseStr.append(conditionName); premiseStr.append("::"); premiseStr.append(cmpType); @@ -809,9 +754,163 @@ public class PlotConstructor2 extends ElementConstructor { knowledgeStr.append(key); knowledgeStr.append(":"); knowledgeStr.append(value); + } + + public void appendFeature(StringBuffer featureStr, String key){ + featureStr.append(","); + featureStr.append(key); + } + + public void extraActivatedPlot(StringBuffer updateKnowledge, String nextPlotLocation, Map activateExtraPlot){ + JSONObject plot = null; + String plotId = "", location = "", lastTaskCondition = "", lastTaskReply = "", plotText = "", conditionName = "", taskLine = ""; + StringBuffer newUK = updateKnowledge; + + Iterator plotIter = activateExtraPlot.keySet().iterator(); + + while(plotIter.hasNext()){ + plotId = plotIter.next(); + plotText = (String)activateExtraPlot.get(plotId); + + plot = plotIndex.get(plotId); + conditionName = plot.getString("conditionName"); + + if(conditionName == null || conditionName.equals("")){ + conditionName = "yaobuyao"; + } + location = plot.getString("place"); + + lastTaskCondition = String.format(TASK_CONDITION, location); + lastTaskReply = String.format(TASK_REPLY, location); + taskLine = String.format(TASK_LINE, location); + + + appendKnowledge(newUK, lastTaskCondition, conditionName); + appendKnowledge(newUK, lastTaskReply, plotText); + appendKnowledge(newUK, taskLine, String.format(GAME_STEP_FORMAT, botAccount, plotId)); + appendKnowledge(newUK, plotId, "1"); + //newUK.append("-<-").append(lastTaskCondition).append(":").append(conditionName).append("-<-").append(lastTaskReply).append(":").append(plotText); + + + } + } + + + + void plotEnQueue(Queue queue, String parentId, String adjId, String nextUnknownText, Boolean thisAutoJump){ + JSONObject adjNode; + if (visited.get(adjId) == null && plotIndex.get(adjId) != null) { + visited.put(adjId, true); + adjNode = plotIndex.get(adjId); + + adjNode.put("parentId", parentId); + adjNode.put("prevAutoJump", thisAutoJump); + queue.add(adjNode); + } else { + conditionDescription.put(adjId, "剧情" + adjId + "进度"); + varInitialMap.put(adjId, ""); + } + } + + + /** + * 当前剧情和下一步剧情不在同一个地点,需要到达地点后才能激活剧情的情况 + */ + void arriveActivatePlot(Map updateKnowledge, String plotId, String nextId, String reply, String gameStep, String nextGameStep, String nextLocation, String nextCondition, String nextUnknownText, String extraUK, String feature){ + + //如果下一步剧情和当前剧情的地点是不一样的,那么在玩家没有到达下一个地点是剧情还是停留在当前剧情,只有到达目的地后,下一步剧情才会发生变化 + StringBuffer hisPremise = new StringBuffer(); + StringBuffer curPremise = new StringBuffer(); + + appendPremise(curPremise, "yaobuyao", "match", "Include", nextLocation); + appendPremise(hisPremise, plotId, "match", "Include", "2"); //剧情已完成且未前往 + appendPremise(hisPremise, "isNeighbour:yaobuyao", "match", "Include", "1+3+4"); +// appendPremise(hisPremise, "from_" + plotId, "match", "Include", "0"); +// appendPremise(hisPremise, "to_" + nextId, "match", "Include", "0"); + + + + configTerm = new ConfigTerm( + curPremise.toString(), + hisPremise.toString(), + feature, reply, nextCondition, + extraUK + "-<-game_step:" + nextGameStep + + "-<-unknownText:" + nextUnknownText + "-<-site:" + nextLocation + "-<-npc_update:updateFollowerLocation:"+ nextLocation + ); + configTerm.setStatus("sleeping"); + configTerm.setConfigName("plot_" + nextLocation + "_" + plotId,false); + configTerm.setjStatus(1); + + configTermList.add(configTerm); + + + //如果当前剧情所在地喝下一步剧情所在地不一样,那么unknown文本 + //只有到达下一步剧情所在地时才会更新 + //updateKnowledge.remove("unknownText"); + updateKnowledge.remove("site"); + } + /** + * 当前剧情和下一步剧情不在同一个地点,需要到达地点后才能激活剧情的情况,将这块处理当做listening模块的一个剧情处理 + */ + void arriveActivatePlot2(JSONObject gameElements, String plotId, String nextId, String nextLocation){ + + String feature; + //如果下一步剧情和当前剧情的地点是不一样的,那么在玩家没有到达下一个地点是剧情还是停留在当前剧情,只有到达目的地后,下一步剧情才会发生变化 + StringBuffer hisPremise = new StringBuffer(); + StringBuffer curPremise = new StringBuffer(); + + appendPremise(curPremise, "yaobuyao", "match", "Include", nextLocation); + appendPremise(hisPremise, nextId + "_from", "match", "Include", plotId); + appendPremise(hisPremise, "isNeighbour:yaobuyao", "match", "Include", "1+3+4"); + +// appendPremise(hisPremise, plotId, "match", "Include", "2"); //剧情已完成且未前往 +// appendPremise(hisPremise, "from_" + plotId, "match", "Include", "0"); +// appendPremise(hisPremise, "to_" + nextId, "match", "Include", "0"); + + +// if(autoJump) { +// feature = "match,activate:after" +// appendKnowledge(extraUK, "plot_jump_text", "str+" + reply); +// +// arriveActivatePlot2(jsonObject, id, nextId, gameStep, "plot_" + nextId + "_*", nextUnknownText, arriveUK.toString(), "match,activate:after"); +// }else { +// feature = "match"; +// arriveActivatePlot2(jsonObject, id, nextId, reply, gameStep, nextGameStep, nextLocation, nextCondition, nextUnknownText, arriveUK.toString(), "match"); +// } + + + JSONObject updateKnowledge = new JSONObject(); + + JSONArray curPremiseList = new JSONArray(); + curPremiseList.add(curPremise.toString()); + + JSONArray hisPremiseList = new JSONArray(); + hisPremiseList.add(hisPremise.toString()); + + + + JSONObject listeningConfig = new JSONObject(); + listeningConfig.put("curPremise", curPremiseList); + listeningConfig.put("hisPremise", hisPremiseList); + listeningConfig.put("updateKnowledge", updateKnowledge); + listeningConfig.put("nextPlotId", nextId); + + if(gameElements.getJSONArray("listeningActions") == null) + gameElements.put("listeningActions", new JSONArray()); + + gameElements.getJSONArray("listeningActions").add(listeningConfig); + + } + + Boolean doActivatePlot(Boolean nextAutoJump, String location, String nextLocation, Boolean moveWithPlot) { + + return nextAutoJump && (location.equals(nextLocation) || moveWithPlot); + } + + } diff --git a/src/processing/ActionMatcher.java b/src/processing/ActionMatcher.java new file mode 100644 index 0000000..a137f38 --- /dev/null +++ b/src/processing/ActionMatcher.java @@ -0,0 +1,1189 @@ +package com.qiwu.chatbotbackend.processing; + +import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; +import com.qiwu.chatbotbackend.entity.Action; +import com.qiwu.chatbotbackend.entity.Solution; +import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.task.utils.BasicBotUtil; +import org.apache.commons.lang.StringUtils; +import org.apache.http.message.BasicNameValuePair; + +import javax.servlet.ServletContext; +import java.io.IOException; +import java.text.ParseException; +import java.util.*; + + +public class ActionMatcher { + + Map activatedMap = new HashMap(); + + + static String POST_DATA_ERROR = "post数据有误"; + static String POST_ERROR = "数据post时出错了"; + static String API_ERROR = "api处理过程中出错了"; + + + + + public LogWriter logWriter = null; + public UserInfo userinfo = null; + public ServletContext context = null; + public GameEnv gameEnv = null; + public Map curInfoPoint = null; + public Map historyInfoPoint = null; + public WorldController worldController = null; + BasicBotUtil botUtil = null; + + public ActionMatcher(Map curInfoPoint, Map historyInfoPoint, LogWriter logWriter, UserInfo userinfo, ServletContext context, GameEnv gameEnv, BasicBotUtil botUtil) { + this.curInfoPoint = curInfoPoint; + this.historyInfoPoint = historyInfoPoint; + this.logWriter = logWriter; + this.userinfo = userinfo; + this.context = context; + this.gameEnv = gameEnv; + this.worldController = new WorldController(logWriter, userinfo); + this.botUtil = botUtil; + } + + + public ActionMatcher(){ + + } + + + + + /** + * 用迭代器迭代当前信息点中的非空关键字,由conditionName索引到状态表中保存的包含conditionName这个条件的列表,并查询状态表中的条件是否满足,优先级是否更高,满足条件且优先级更高就设为bestMatch + * + * @param conditionTable 满足什么条件,就回答什么,下一步跳什么 + * @return bestMatch 状态表中满足条件最多的一条 + */ + public Action getBestMatch(HashMap> conditionTable, ServletContext context, UserInfo userInfo) throws IOException { + + Integer configId = 0; + List actionList = null; + Action bestMatch = new Action(-1), iterCon; + Iterator it = curInfoPoint.keySet().iterator(); + Queue activatedQueue = new LinkedList(); + Queue activatedAction = new LinkedList(); + + + + while (it.hasNext()) { + String conditionName = it.next(); + String keywords = curInfoPoint.get(conditionName); + String keyword = null; + Boolean activateFlag = false; + Boolean replaceFlag = false; + Boolean satisfyFlag = false; + + if (keywords != null && !keywords.equals("")) + keyword = keywords; + + + if (keyword != null && conditionTable.get(conditionName) != null) { + actionList = conditionTable.get(conditionName); + + + for (Action action : actionList) { + activateFlag = false; + satisfyFlag = false; + replaceFlag = false; + if (action.status.equals("waiting")){ + + //是否有激活操作,如果有激活操作且没有提交表单则判断是否满足条件,如果有激活有提交表单,则放在整个操作完成(getSolution)之后再激活 + if (action.featureMap.get("activate") != null && !action.featureMap.containsKey("post")) { + activateFlag = true; + } + + if((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.priority > bestMatch.priority)){ + replaceFlag = true; + } + + + + //没有激活,优先级不够高,直接跳过 + if(!activateFlag && !replaceFlag){ + logWriter.record("-----------------------------------优先级不足其没有激活,跳过", 0); + continue; + } + + if(conditionSatisfy(action)){ + satisfyFlag = true; + } + + + if(satisfyFlag){ + if(activateFlag){ + activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.priority, action.auxiliaryPriority, action.nextStep, context); + } + if(replaceFlag){ + bestMatch = action; + logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.id) + "\"", 2); + logWriter.writeln(); + } + } + + + +// if ((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.priority > bestMatch.priority) +// || action.featureMap.get("activate") != null){ +// if(conditionSatisfy(action)){ +// if (action.featureMap.get("activate") != null && !action.featureMap.containsKey("post")) { +// //有post这个feature的配置条目会在最后激活它的待激活列表,这里就不激活了。 +// activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.priority, action.auxiliaryPriority, action.nextStep, context); +// } +// if((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.priority > bestMatch.priority)) { +// bestMatch = action; +// logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.id) + "\"", 2); +// logWriter.writeln(); +// } +// +// +// } +// +// }else { +// logWriter.record("-----------------------------------优先级不足,跳过", 0); +// logWriter.record(userinfo.id2config.get(action.id), 1); +// } +// } +// +// +// +// +// +// if (action.status.equals("waiting")){ +// if ((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.priority > bestMatch.priority) +// || action.featureMap.get("activate") != null){ +// if(conditionSatisfy(action)){ +// if (action.featureMap.get("activate") != null && !action.featureMap.containsKey("post")) { +// //有post这个feature的配置条目会在最后激活它的待激活列表,这里就不激活了。 +// activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.priority, action.auxiliaryPriority, action.nextStep, context); +// } +// if((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.priority > bestMatch.priority)) { +// bestMatch = action; +// logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.id) + "\"", 2); +// logWriter.writeln(); +// } +// +// +// } +// +// }else { +// logWriter.record("-----------------------------------优先级不足,跳过", 0); +// logWriter.record(userinfo.id2config.get(action.id), 1); +// } + } + } + } + + } + logWriter.record("----------------------匹配结束", 2); + + bestMatch = activatedQueueMatching(bestMatch, activatedQueue, context); + + + return bestMatch; + } + + /** + * 在激活列表中选择满足匹配且优先级最高的一条配置条目 + * @param bestMatch + * @param activatedQueue + * @param context + * @return + * @throws IOException + */ + public Action activatedQueueMatching(Action bestMatch, Queue activatedQueue, ServletContext context) throws IOException { + Action action; + Boolean activateFlag = false; + Boolean replaceFlag = false; + Boolean satisfyFlag = false; + Boolean parentFlag = false; + + //待激活配置条目被激活后的匹配 + while (!activatedQueue.isEmpty()) { + activateFlag = false; + replaceFlag = false; + satisfyFlag = false; + parentFlag = false; + + action = activatedQueue.remove(); + activatedMap.remove(action.id); + + + if((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.activePriority > bestMatch.activePriority)) + replaceFlag = true; + + if(action.featureMap.get("activate") != null && !action.featureMap.containsKey("post")) + activateFlag = true; + + if(bestMatch.nextStep.contains(String.valueOf(action.id))) + //现在的condition是被bestMatch这个condition激活的 + parentFlag = true; + + + //没有激活功能, 优先级不够, condition不是被bestMatch激活,直接跳过 + if(!activateFlag && !replaceFlag && !parentFlag) { + logWriter.record("-----------------------------------优先级不足,跳过", 0); + logWriter.record(userinfo.id2config.get(action.id), 1); + continue; + } + + if(conditionSatisfy(action)){ + if(activateFlag) { + activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.priority, action.auxiliaryPriority, action.nextStep, context); + } + if(replaceFlag){ + bestMatch = action; + logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.id) + "\"", 2); + logWriter.writeln(); + } + } + + + + + +// //当前condition的辅助优先级高于bestMatch、或者优先级已知添加数量更多、或者 +// if ((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.activePriority > bestMatch.activePriority) +// || action.featureMap.get("activate") != null +// || bestMatch.nextStep.contains(String.valueOf(action.id)) || (!action.configName.equals("") && bestMatch.nextStep.contains(action.configName.substring(0,3)))){ +// //激活优先级先比较,但是如果激活的是无条件的就直接判断名字。 +// if(conditionSatisfy(action)){ +// +// //有激活配置文件,但是没有post提交表单,则激活,如果有post就放到提交表单之后激活(postActivate) +// if (action.featureMap.get("activate") != null && !action.featureMap.containsKey("post")) { +// activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.priority, action.auxiliaryPriority, action.nextStep, context); +// } +// +// bestMatch = action; +// logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.id) + "\"", 2); +// logWriter.writeln(); +// +// } +// +// } else { +// logWriter.record("-----------------------------------优先级不足,跳过", 0); +// logWriter.record(userinfo.id2config.get(action.id), 1); +// } + + + + + } + + return bestMatch; + + } + + /** + * 根据当前信息点,历史信息点,判断是否满足该action的条件,match关键字指引擎识别的关键字包含在action相应的关键词列表中,这里可以根据特征添加其他操作。 + * currentPremise是当前信息点需要满足的条件,historyPremise是历史信息点需要满足的条件 + * + * @param action 配置文件(状态表)的一行 + * @return 满足条件就为True, 不满足就为False + */ + public boolean conditionSatisfy(Action action) { + boolean flag = true; + String actionName, keywords, keyword, comparePair[], cmpType, premiseStr; + HashSet keywordSet = null; + + logWriter.record("-----------------------------------检索到配置条目", 0); + logWriter.record(userinfo.id2config.get(action.id), 1); + + if (action.featureMap.containsKey("match")) { + Iterator it = action.currentPremise.keySet().iterator(); + while (flag && it.hasNext()) { + premiseStr = it.next(); + comparePair = premiseStr.split("::"); + actionName = comparePair[0]; + cmpType = comparePair[1]; + keyword = botUtil.getKeyword(curInfoPoint, historyInfoPoint, false, actionName); + + if (keyword == null) { + flag = false; + if(flag == false){ + logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); + } + break; + } + + keywordSet = action.currentPremise.get(premiseStr); + if (!premiseSatisfy(keyword, cmpType, keywordSet)) + flag = false; + + if(flag == false){ + logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); + } + } + + it = action.historyPremise.keySet().iterator(); + while (flag && it.hasNext()) { + premiseStr = it.next(); + comparePair = premiseStr.split("::"); + cmpType = comparePair[1]; + actionName = comparePair[0]; + //如果featureMap中包含includeCurInfo,则已知信息中包含啦当前对话中识别的所有信息 + keyword = botUtil.getKeyword(historyInfoPoint, curInfoPoint, action.featureMap.containsKey("includeCurInfo"), actionName); + + if (keyword == null) { + flag = false; + if(flag == false){ + logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); + } + break; + } + + + + keywordSet = action.historyPremise.get(premiseStr); + if (!premiseSatisfy(keyword, cmpType, keywordSet)) + flag = false; + + if(flag == false){ + logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); + } + } + } + + + return flag; + + } + + + + + /** + * 单个条件的匹配,判断是否满足条件 + * 比较类型分为 match、number、time、variable, + * curVarCmp和hisVarCmp是变量比较的两种形式,分别是比较当前信息和比较已知信息 + * + * @param keyword + * @param cmpType 比较类型 + * @param keywordSet 候选关键字集合,满足其中任意一个都算满足条件 + * @return 返回匹配或者不匹配 + */ + public boolean premiseSatisfy(String keyword, String cmpType, HashSet keywordSet) { + boolean flag = true; + String operator = ""; + + try { + String splitPair[] = cmpType.split("-", 2); + if (splitPair.length > 1) { + operator = splitPair[1]; + cmpType = splitPair[0]; + } + + + if (cmpType.equals("match")) { + if(operator.equals("Keyword") || operator.equals("Include")) { + if (!keywordSet.contains(keyword)) { + flag = false; + } + if (flag == false && keyword.contains(":")) { + String ks[] = keyword.split(":"); + for (String k : ks) { + if (keywordSet.contains(k)) + flag = true; + } + } + } else if(operator.equals("Exclude")) { + if(keyword.contains(":")){ + String ks[] = keyword.split(":", 2); + if(keywordSet.contains(ks[0]) || keywordSet.contains(ks[1])) + flag = false; + }else { + if (keywordSet.contains(keyword)) { + flag = false; + } + } + }else if(operator.equals("Have")){ + for(String key:keywordSet){ + if(key.equals("")) + continue; + if(!keyword.contains(key)){ + flag = false; + break; + } + } + }else{ + flag = false; + } + + + } else if (cmpType.equals("number") && !keyword.equals("")) { + int candidateA = 0; + int candidateB = 0; + + if (keyword.contains(":")) { + String ks[] = keyword.split(":"); + for (String k : ks) { + if(StringUtils.isNumeric(k)) + keyword = k; + + } + } + + if(!StringUtils.isNumeric(keyword)){ + return false; + + } + + candidateA = Integer.parseInt(keyword); + for (String k : keywordSet) { + if (!k.equals("")) { + candidateB = Integer.parseInt(k); + break; + } + } + if (operator.equals("Bigger")) + flag = candidateA > candidateB; + else if (operator.equals("BiggerOrEqual")) + flag = candidateA >= candidateB; + else if (operator.equals("Smaller")) + flag = candidateA < candidateB; + else if (operator.equals("SmallerOrEqual")) + flag = candidateA <= candidateB; + else if (operator.equals("NotEqual")) + flag = candidateA != candidateB; + + } else if (cmpType.equals("time")) { + + long candidateA, candidateB = 0; + + if (keyword.contains(":")) { + String ks[] = keyword.split(":"); + for (String k : ks) { + if(k.contains("年") && k.contains("月") && k.contains("日")) + keyword = k; + + } + } + + candidateA = MyFunc.transferToMillisecond(keyword); + + for (String k : keywordSet) { + if (!k.equals("")) { + candidateB = MyFunc.transferToMillisecond(k); + break; + } + } + if (operator.equals("Early")) + flag = candidateA < candidateB; + else if (operator.equals("Later")) + flag = candidateA > candidateB; + + } else if(cmpType.equals("curVarCmp") || cmpType.equals("hisVarCmp")) { + String conditionName2 = "", conditionValue2 = ""; + for (String k : keywordSet) { + if (!k.equals("")) { + conditionName2 = k; + break; + } + } + + if(cmpType.equals("curVarCmp") && curInfoPoint.get(conditionName2) != null && !curInfoPoint.get(conditionName2).equals("")) { + conditionValue2 = botUtil.getKeyword(curInfoPoint, historyInfoPoint, false, conditionName2); + }else if (cmpType.equals("hisVarCmp") && historyInfoPoint.get(conditionName2) != null && !historyInfoPoint.get(conditionName2).equals("")){ + conditionValue2 = botUtil.getKeyword(historyInfoPoint, curInfoPoint, false, conditionName2); + }else { + flag = false; + } + + + if(flag ){ + /** + * flag 默认为空, 当同为数字或者时间且比较结果为真是flag才为true + */ + flag = false; + if(operator.equals("Equal")){ + flag = keyword.equals(conditionValue2); + + }else if(keyword.contains(":") && conditionValue2.contains(":")){ + String relPair1[] = keyword.split(":", 2), keyword1 = ""; + String relPair2[] = conditionValue2.split(":", 2), keyword2 = ""; + boolean similar = false; + + if(relPair1[0].equals(relPair2[0])){ + similar = true; + keyword1 = relPair1[1]; + keyword2 = relPair2[1]; + }else if (relPair1[1].equals(relPair2[1])){ + similar = true; + keyword1 = relPair1[0]; + keyword2 = relPair2[0]; + } + + if(similar){ + if(StringUtils.isNumeric(keyword1) && StringUtils.isNumeric(keyword2)){ + int candidateA = Integer.parseInt(keyword1); + int candidateB = Integer.parseInt(keyword2); + + + if (operator.equals("Bigger")) + flag = candidateA > candidateB; + else if (operator.equals("BiggerOrEqual")) + flag = candidateA >= candidateB; + else if (operator.equals("Smaller")) + flag = candidateA < candidateB; + else if (operator.equals("SmallerOrEqual")) + flag = candidateA <= candidateB; + else if (operator.equals("Equal")) + flag = candidateA == candidateB; + else if (operator.equals("NotEqual")) + flag = candidateA != candidateB; + + } else if(keyword1.contains("年") && keyword1.contains("月") && keyword1.contains("日") + && keyword2.contains("年") && keyword2.contains("月") && keyword2.contains("日")){ + long candidateA = MyFunc.transferToMillisecond(keyword1); + long candidateB = MyFunc.transferToMillisecond(keyword2); + + if (operator.equals("Bigger")) + flag = candidateA > candidateB; + else if (operator.equals("BiggerOrEqual")) + flag = candidateA >= candidateB; + else if (operator.equals("Smaller")) + flag = candidateA < candidateB; + else if (operator.equals("SmallerOrEqual")) + flag = candidateA <= candidateB; + else if (operator.equals("Equal")) + flag = candidateA == candidateB; + else if (operator.equals("NotEqual")) + flag = candidateA != candidateB; + + // 操作符为等于时可以比较两个字符串是否相同 + } + } + }else if(!keyword.contains(":") && !conditionValue2.contains(":")){ + if(StringUtils.isNumeric(keyword) && StringUtils.isNumeric(conditionValue2)){ + int candidateA = Integer.parseInt(keyword); + int candidateB = Integer.parseInt(conditionValue2); + + + if (operator.equals("Bigger")) + flag = candidateA > candidateB; + else if (operator.equals("BiggerOrEqual")) + flag = candidateA >= candidateB; + else if (operator.equals("Smaller")) + flag = candidateA < candidateB; + else if (operator.equals("SmallerOrEqual")) + flag = candidateA <= candidateB; + else if (operator.equals("Equal")) + flag = candidateA == candidateB; + else if (operator.equals("NotEqual")) + flag = candidateA != candidateB; + + } else if(keyword.contains("年") && keyword.contains("月") && keyword.contains("日") + && conditionValue2.contains("年") && conditionValue2.contains("月") && conditionValue2.contains("日")){ + long candidateA = MyFunc.transferToMillisecond(keyword); + long candidateB = MyFunc.transferToMillisecond(conditionValue2); + + if (operator.equals("Bigger")) + flag = candidateA > candidateB; + else if (operator.equals("BiggerOrEqual")) + flag = candidateA >= candidateB; + else if (operator.equals("Smaller")) + flag = candidateA < candidateB; + else if (operator.equals("SmallerOrEqual")) + flag = candidateA <= candidateB; + else if (operator.equals("Equal")) + flag = candidateA == candidateB; + else if (operator.equals("NotEqual")) + flag = candidateA != candidateB; + + // 操作符为等于时可以比较两个字符串是否相同 + } + } + } + + + + } else if (cmpType.equals("any")) { + if (keyword.equals("")) //当前信息点中的关键词不为空即满足条件,为空则不满足 + flag = false; + + } else { + flag = false; + } + } catch (IndexOutOfBoundsException e) { + System.out.println("配置文件格式有误"); + flag = false; + e.printStackTrace(); + } catch (ParseException e) { + System.out.println("时间解析错误"); + e.printStackTrace(); + flag = false; + } catch (Exception e) { + System.out.println("操作符有误"); + e.printStackTrace(); + flag = false; + } + + return flag; + } + + /** + * 替换答案中相应的变量{xxx-1},并根据当前信息点更新历史信息点(当前在下一轮变成历史)。 + * + * @return 返回给引擎的数据 + */ + public Solution getSolution(Action ansAction, ServletContext context, UserInfo userinfo) throws IOException, ParseException { + + Iterator it = curInfoPoint.keySet().iterator(); + String actionName, reply, variable; + Solution ans = new Solution(0, "", ""); + + + //如果一条配置文件有多个答案,则随 + // 机选择一个答案 + + //System.out.println(ans.getAnswer()); + + //post关键字 + if (ansAction.featureMap.containsKey("post")) { + logWriter.record("---------------------进入表单结束",1); + ans = postToServer(ans, ansAction); + logWriter.record("---------------------提交表单结束",1); + + //nextNext关键字 + } + //----------------------------------------------------------------------------- + //----------------------------------------------------------------------------- + + //updateKnowledge关键字 + if (ansAction.featureMap.containsKey("updateKnowledge")) { + logWriter.record("---------------------进入更新答案【略】",1); + updateKnowledge(ansAction); + logWriter.record("---------------------更新答案结束",1); + } + + //----------------------------------------------------------------------------- + //----------------------------------------------------------------------------- + + + if (ansAction.featureMap.containsKey("newNext")) { + logWriter.record("---------------------进入判断下一步【略】",1); + ans = findNewNext(ans, ansAction); + logWriter.record("---------------------判断下一步结束",1); + //上一步 + } else if (ansAction.featureMap.containsKey("return-1")) { + String activeList[] = historyInfoPoint.get("activeList").split("\\|"); + if (activeList.length == 1) + ans.setNext("nextStep=" + activeList[activeList.length - 1]); + else { + ans.setNext("nextStep=" + activeList[activeList.length - 2]); + } + //停留 + } else if (ansAction.featureMap.containsKey("return-0")) { + String activeList[] = historyInfoPoint.get("activeList").split("\\|"); + if(activeList.length > 0) + ans.setNext("nextStep=" + activeList[activeList.length - 1]); + else + ans.setNext("nextStep= "); + //激活 + } else if (ansAction.featureMap.containsKey("activate") || ansAction.featureMap.containsKey("activate:after")) { + String activeList[] = historyInfoPoint.get("activeList").split("\\|"); + if (activeList.length == 1) + ans.setNext("nextStep=" + activeList[activeList.length - 1]); + else { + ans.setNext("nextStep=" + activeList[activeList.length - 2]); + } + } + + + + + + try { + + reply = MyFunc.randStr(ansAction.answer); + reply = botUtil.varSlotReplace(reply); + //reply = ResponseFilter.filt(curInfoPoint,historyInfoPoint,gameEnv,worldController, reply, userinfo, ansAction, logWriter); + + ans.setAnswer(reply); + + + botUtil.extraOperation(ansAction, ans); + + //----------------------------------------------------------------------------- + //----------------------------------------------------------------------------- + + + if (ans.getNext().equals("")) { + ans.setNext("nextStep=" + ansAction.nextStep); + } + + } catch (Exception e) { + e.printStackTrace(); + } + + return ans; + } + + /** + * 请求处理结束后台将当前信息的信息点转移到已知信息 + * @param ans + * @param context + * @param debugFlag + */ + public void infoTransfer(Solution ans, ServletContext context, boolean debugFlag) { + //将当前信息点更新至历史信息点 + Iterator it = curInfoPoint.keySet().iterator(); + String actionName, lastReply; + String next = ans.getNext().split("=", 2)[1]; + + //保存即将跳转的action名以供下一轮使用,nextStep的结构是nextStep=xxx + historyInfoPoint.put("currentAction", next); + historyInfoPoint.put("activeList", historyInfoPoint.get("activeList") + "|" + next); + + logWriter.record("处理完成后的信息点:
" + historyInfoPoint.toString(), 1); + + HashSet skipSet = new HashSet() { + { + add("chat_key"); + add("action_name"); + add("bot_name"); + add("emptySet"); + add("query_text"); + } + }; + +// if (debugFlag) +// lastReply = ans.getAnswer().split(")")[2]; +// else +// lastReply = ans.getAnswer(); +// historyInfoPoint.put("lastReply", lastReply); + + try { + String keyword1, keyword2; + while (it.hasNext()) { + actionName = it.next(); + + if(skipSet.contains(actionName)) + continue; + + keyword1 = curInfoPoint.get(actionName); + keyword2 = historyInfoPoint.get(actionName); + if (keyword2 == null) { + historyInfoPoint.put(actionName, keyword1); + }else if (historyInfoPoint.get(actionName).equals("do_reset")){ + historyInfoPoint.put(actionName, ""); + }else if (keyword2 != null && !(keyword1 == null) && !keyword1.equals("")) + historyInfoPoint.put(actionName, keyword1); + } + historyInfoPoint.put("临时变量reply", ""); + historyInfoPoint.put("临时变量condition", ""); + historyInfoPoint.put("临时变量3", ""); + + + + //context.setAttribute("chat_key+"+userinfo.botAccount,historyInfoPoint); + + + } catch (Exception e) { + e.printStackTrace(); + } + } + + + /** + * 在新平台添加debug_mode这个关键字, 后台会将存储的变量值返回给页面以作调试 + * + * @param ans 最终返回的数据 + * @param context + */ + public void appendDebugInfo(Solution ans, ServletContext context) { + Iterator it = null; + String key, values, value; + + HashSet skipSet = new HashSet() { + { + add("activeList"); + add("currentAction"); + add("lastUpdateTime"); + add("bot_name"); + add("action_name"); + add("lastReply"); + add("unknownTextList"); + add("finalUnknownText"); + add("unknownText"); + add("randKey"); + add("userKey"); + } + }; + + it = curInfoPoint.keySet().iterator(); + String debugInfo = ""; + debugInfo += "(识别:"; + + while (it.hasNext()) { + key = it.next(); + values = curInfoPoint.get(key); + if (values != null && !values.equals(" ") && !values.equals("") && !skipSet.contains(key)) { + if (key.endsWith("_backup")) { + key = key.substring(0, key.length() - 7); + } + debugInfo += (" " + key + ":\'" + values + "\' "); + } + } + + 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")) + debugInfo += (" " + key + ":\'" + value + "\' "); + + } + } + ans.setAnswer(debugInfo + ")" + ans.getAnswer()); + } + + + /** + * 重新post到其他服务器读取数据,并根据这些数据修改返回给用户的信息,可能包括nextStep,和回答文本中的可变参数(用replace方法替换) + * + * @param ans 返回给用户的数据 + * @param ansAction 满足条件最多的condition(配置文件的某一行) + */ + public Solution postToServer(Solution ans, Action ansAction) throws IOException { + String url = null, elem[], subElem[], key,keys, postType = "all"; + Map infoMap = new HashMap(); + List pairList = new ArrayList(); + Iterator k_iter = null; + FormsPoster poster = new FormsPoster(logWriter); + + HashSet skipSet = new HashSet() { + { + add("activeList"); + add("currentAction"); + add("lastUpdateTime"); + add("lastReply"); + } + }; + + elem = ansAction.featureMap.get("post").split("\\|"); + url = elem[0]; + postType = elem[1]; + + + if(postType.equals("all")){ + poster.postAll(curInfoPoint, historyInfoPoint, ans, url); + }else if(postType.equals("term")){ + poster.postTerm(curInfoPoint, historyInfoPoint, ans, ansAction, url); + }else if(postType.equals("gameQA")){ + poster.postGameQA(curInfoPoint, historyInfoPoint, ans, gameEnv, worldController, url, userinfo); + } + + return ans; + + } + + public Solution findNewNext(Solution ans, Action ansAction) { + String nextOptions[] = ansAction.nextStep.split(","); + String conditionName, premises[], cpPair[]; + boolean flag = true; + + String activeList = historyInfoPoint.get("activeList"); + + for (String option : nextOptions) { + flag = true; + cpPair = option.split(":"); + conditionName = cpPair[0]; + if (cpPair.length == 1) { + ans.setNext("nextStep=" + conditionName); + break; + } + premises = cpPair[1].split("-"); + for (String premise : premises) { + if (premise.equals("known")) { + //如果当前/历史信息点中有option这个键,并且这个键的值不为空也不为unknown,那么证明这个option(即相应condition)已经被识别 + boolean conditionExistInCurInfoPoint = curInfoPoint.containsKey(conditionName) && !curInfoPoint.get(conditionName).equals("") && !curInfoPoint.get(conditionName).equals("unknown") && !curInfoPoint.get(conditionName).equals("do_reset"); + boolean conditionExistInHistoryInfoPoint = historyInfoPoint.containsKey(conditionName) && !historyInfoPoint.get(conditionName).equals("") && !historyInfoPoint.get(conditionName).equals("unknown") && !historyInfoPoint.get(conditionName).equals("do_reset"); + + //只有前两者都为假时,conditionExist才为真 + boolean conditionExist = (conditionExistInCurInfoPoint || conditionExistInHistoryInfoPoint); + + if (conditionExist) + flag = false; + } + + if (premise.equals("active")) { + boolean isActive = activeList.contains(conditionName); + if (isActive) + flag = false; + } + } + + if (flag) { + ans.setNext("nextStep=" + conditionName); + break; + } + + } + return ans; + + } + + + public void updateKnowledge(Action action) throws ParseException { + String keyword, variableName, updateValue, returnStr = "1"; + + + + Iterator iit = action.updateKnowledge.keySet().iterator(); + while (iit.hasNext()) { + + variableName = iit.next(); + + keyword = botUtil.getKeyword(historyInfoPoint, curInfoPoint, false, variableName); + updateValue = botUtil.knowledgeProcess(variableName, action.updateKnowledge.get(variableName)); + + + try { + //做数字加法 + if (updateValue.startsWith("+")) { + if (keyword == null || keyword.equals("")) + keyword = "0"; + if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { + long time = MyFunc.transferToMillisecond(keyword); + int offset = Integer.parseInt(updateValue.substring(1)); + updateValue = MyFunc.transferToStandardTime(time + (1000 * offset)); + } else if (StringUtils.isNumeric(keyword)) { + int number = Integer.parseInt(keyword); + int offset = Integer.parseInt(updateValue.substring(1)); + updateValue = String.valueOf(number + offset); + } + //做数字减法 + } else if (updateValue.startsWith("-")) { + if (keyword == null || keyword.equals("")) + keyword = "0"; + if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { + long time = MyFunc.transferToMillisecond(keyword); + int offset = Integer.parseInt(updateValue.substring(1)); + updateValue = MyFunc.transferToStandardTime(time - (1000 * offset)); + } else if (StringUtils.isNumeric(keyword)) { + int number = Integer.parseInt(keyword); + int offset = Integer.parseInt(updateValue.substring(1)); + updateValue = String.valueOf(number - offset); + } + //做字符串累加 + } else if (updateValue.startsWith("str+")) { + if (keyword == null || keyword.equals("")) + keyword = ""; + updateValue = keyword + updateValue.substring(4); + //做字符串删除 + } else if (updateValue.startsWith("str-")) { + if (keyword == null || keyword.equals("")) + keyword = ""; + updateValue = keyword.replace(updateValue.substring(4), ""); + + } else if (updateValue.startsWith("int+=")) { + if (keyword == null || keyword.equals("")) + keyword = "0"; + if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { + long time = MyFunc.transferToMillisecond(keyword); + int offset = Integer.parseInt(updateValue.substring(1)); + updateValue = MyFunc.transferToStandardTime(time + (1000 * offset)); + } else if (StringUtils.isNumeric(keyword)) { + int number = Integer.parseInt(keyword); + int offset = Integer.parseInt(updateValue.substring(5)); + updateValue = String.valueOf(number + offset); + } + //做数字减法 + } else if (updateValue.startsWith("int-=")) { + if (keyword == null || keyword.equals("")) + keyword = "0"; + if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { + long time = MyFunc.transferToMillisecond(keyword); + int offset = Integer.parseInt(updateValue.substring(5)); + updateValue = MyFunc.transferToStandardTime(time - (1000 * offset)); + } else if (StringUtils.isNumeric(keyword)) { + int number = Integer.parseInt(keyword); + int offset = Integer.parseInt(updateValue.substring(1)); + updateValue = String.valueOf(number - offset); + } + //做字符串累加 + } else if (updateValue.startsWith("str+=")) { + if (keyword == null || keyword.equals("")) + keyword = ""; + updateValue = keyword + updateValue.substring(5); + //做字符串删除 + } else if (updateValue.startsWith("str-=")) { + if (keyword == null || keyword.equals("")) + keyword = ""; + updateValue = keyword.replace(updateValue.substring(5), ""); + + + //变量提取 + } else if (updateValue.startsWith("var=")) { + String conditionName = updateValue.substring(5, updateValue.length() - 3); + if (updateValue.endsWith("-1}")) { + if (curInfoPoint.get(conditionName) != null) { + updateValue = curInfoPoint.get(conditionName); + } else { + updateValue = ""; + } + } else if (updateValue.endsWith("-2}")) { + if (historyInfoPoint.get(conditionName) != null) { + updateValue = historyInfoPoint.get(conditionName); + } else { + updateValue = ""; + } + + //提取配置条目的下一步 + } else if (updateValue.endsWith("nextStep-3}")) { + updateValue = action.nextStep; + //提取配置条目的回答 + } else if (updateValue.endsWith("reply-3}")) { + updateValue = MyFunc.randStr(action.answer); + } + //如果变量名叫做process-nextStep,那么下一个激活的condition就是updateValue + if (variableName.startsWith("process-nextStep")) { + action.nextStep = updateValue; + updateValue = ""; + } + + } + + + } catch (Exception e) { + e.printStackTrace(); + continue; + } + + + + if(updateValue.equals("")) { + curInfoPoint.put(variableName + "_backup", curInfoPoint.get(variableName)); //更新答案将某变量设为空时,要将当前信息点也清空,不然后边信息点更新时这个变量的已知信息依然不是空的。 + // 为了避免将当前信息点清空后debug信息显示不完整,现创造一个备份,在appendDebugInfo后会将这个备份清空。 + curInfoPoint.put(variableName, ""); + } + + botUtil.putKeyword(variableName, updateValue); + + + } + + } + + + public void activateCondition(Queue activatedQueue, String botAccount, int basePriority, int baseAuxiliaryPriority, String activateList, ServletContext context) throws IOException { + UserInfo userinfo = (UserInfo) context.getAttribute(botAccount); + String configStr = ""; + Integer configId; + Action newAction, originAction; + List originActionList = new ArrayList(); + + for (String configIdStr : activateList.split(",")) { + logWriter.record("------激活-------" + configIdStr + "-------
", 0); + try { + if (StringUtils.isNumeric(configIdStr)) { + configId = Integer.parseInt(configIdStr); + configStr = userinfo.id2config.get(configId); + originAction = userinfo.id2condition.get(configId); + originActionList.add(originAction); + } else { + if (configIdStr.endsWith("*")) { + String prefix = configIdStr.substring(0, configIdStr.length()-1); + for(String name:userinfo.name2condition.keySet()){ + if (name.startsWith(prefix)){ + originActionList.add(userinfo.name2condition.get(name)); + } + } + + } else { + originActionList.add(userinfo.name2condition.get(configIdStr)); + } + + + } + } catch (Exception e) { + e.printStackTrace(); + logWriter.record("----------查找待激活condition出现异常:" + configIdStr, 5); + } + } + + for (Action action : originActionList){ + originAction = action; + try { + + configId = originAction.id; + + newAction = new Action(originAction, basePriority, baseAuxiliaryPriority); + //action = ActionMatcher.buildCondition(action, configStr); + + + + //如果这条配置文件已经被其他配置文件激活了,处于activatedMap,那么就需要比较优先级是否更高,如果更高则优先级做替换,配置文件的内容不变 + if (activatedMap.containsKey(configId)) { + if(newAction.auxiliaryPriority > activatedMap.get(configId).auxiliaryPriority) + activatedMap.get(configId).auxiliaryPriority = newAction.auxiliaryPriority; + if(newAction.activePriority > activatedMap.get(configId).activePriority) + activatedMap.get(configId).activePriority = newAction.activePriority; + } else if (!activatedMap.containsKey(configId)) { + activatedMap.put(configId, newAction); + activatedQueue.add(newAction); + } + }catch (Exception e) { + e.printStackTrace(); + logWriter.record("----------激活失败:" + action.configName, 5); + } + + } + + + } + + /** + * 一个提交表单后在激活的操作 + * @param ansAction + * @param context + * @param userinfo + * @return + * @throws IOException + * @throws ParseException + */ + public Solution postActivate(Action ansAction, Solution oldBestMatch, ServletContext context, UserInfo userinfo) throws IOException, ParseException { + Queue activatedQueue = new LinkedList(); + Solution bestMatch = oldBestMatch; + Action newAction1 = ansAction, newAction2; +// activateCondition(activatedQueue, userinfo.botAccount, ansAction.priority, ansAction.auxiliaryPriority, ansAction.nextStep, context); +// ansAction = activatedQueueMatching(ansAction, activatedQueue, context); +// +// bestMatch = getSolution(ansAction, context, userinfo); + + + + while ((newAction1.featureMap.containsKey("activate") && newAction1.featureMap.containsKey("post")) || newAction1.featureMap.containsKey("activate:after")) { + //如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段 + activateCondition(activatedQueue, userinfo.botAccount, newAction1.priority, newAction1.auxiliaryPriority, newAction1.nextStep, context); + newAction2 = activatedQueueMatching(newAction1, activatedQueue, context); + + + + if(newAction1 == newAction2) + break; + + bestMatch = getSolution(newAction2, context, userinfo); + newAction1 = newAction2; + } + + return bestMatch; + + + + + } + + +} diff --git a/src/processing/ChatCacheController.java b/src/processing/ChatCacheController.java index b319104..0837e28 100644 --- a/src/processing/ChatCacheController.java +++ b/src/processing/ChatCacheController.java @@ -90,7 +90,7 @@ public class ChatCacheController { LocalDateTime now = LocalDateTime.now(); DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); String nowTime = now .format(format); - Boolean opFlag; + Boolean opFlag, destroy = false; System.out.println("游戏存档中"); @@ -102,6 +102,7 @@ public class ChatCacheController { if(helper == null){ helper = new SqlHelper(); + destroy = true; } File dir = new File(CHAT_CACHE_DIR); @@ -125,6 +126,9 @@ public class ChatCacheController { opFlag = helper.insertArchiveInfo(archiveName, userKey, site); + if(destroy) + helper.destroy(); + } catch (Exception e) { System.out.println("游戏存档时发生异常"); e.printStackTrace(); @@ -140,6 +144,7 @@ public class ChatCacheController { ChatCache chatCache = null; GameEnv gameEnv = null; Map infoPoint = null; + System.out.println(archiveInfo.getArchiveId()); String keys[] = archiveInfo.getArchiveId().split(COMBINE_PUNC1); keys[1] = keys[1].split("-")[0]; @@ -196,7 +201,7 @@ public class ChatCacheController { while (it.hasNext()) { sessionKey = it.next(); if (sessionKey.equals(userKey)) { - saveChatCache(chatCacheMap.get(sessionKey),null); +// saveChatCache(chatCacheMap.get(sessionKey),null); continue; } history = chatCacheMap.get(sessionKey).getInfoPoint(); @@ -246,6 +251,8 @@ public class ChatCacheController { helper = new SqlHelper(); archiveInfo = helper.queryUserLastGameArchive(userKey); + helper.destroy(); + } catch(Exception e){ e.printStackTrace(); diff --git a/src/processing/FormsPoster.java b/src/processing/FormsPoster.java index 7fcc5da..1bb00fc 100644 --- a/src/processing/FormsPoster.java +++ b/src/processing/FormsPoster.java @@ -4,9 +4,10 @@ import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; -import com.qiwu.chatbotbackend.entity.Condition; +import com.qiwu.chatbotbackend.entity.Action; import com.qiwu.chatbotbackend.entity.Solution; import com.qiwu.chatbotbackend.entity.UserInfo; +import com.qiwu.chatbotbackend.task.utils.GameBotUtil; import org.apache.http.message.BasicNameValuePair; import org.springframework.beans.factory.annotation.Value; @@ -20,13 +21,13 @@ public class FormsPoster { LogWriter logWriter; - static String TALKER = "【(.*?)@.*?】"; + public static String TALKER = "【(.*?)@.*?】"; @Value("${qa.url}") public String QA_URL; - public void setQaUrl(String qaUrl) { + public void setQaUrl(String qaUrl) { QA_URL = qaUrl; } @@ -46,7 +47,7 @@ public class FormsPoster { /** - * 提交类型为all时,会把当前信息点和历史信息点都作为post到另一个服务器 + * 提交类型为all时,会把当前信息点和历史信息点都作为post到另一个服务器,还有回答 * @param curInfoPoint * @param historyInfoPoint * @param ans @@ -81,6 +82,7 @@ public class FormsPoster { } } + pairList.add(new BasicNameValuePair("reply", ans.getAnswer())); logWriter.record("提交表单的数据:
" + pairList.toString(), 2); @@ -119,11 +121,11 @@ public class FormsPoster { * @param curInfoPoint * @param historyInfoPoint * @param ans - * @param ansCondition + * @param ansAction * @param URL * @throws UnsupportedEncodingException */ - public void postTerm(Map curInfoPoint, Map historyInfoPoint, Solution ans, Condition ansCondition, String URL) throws UnsupportedEncodingException { + public void postTerm(Map curInfoPoint, Map historyInfoPoint, Solution ans, Action ansAction, String URL) throws UnsupportedEncodingException { String key, keyName; Iterator k_iter = null; List pairList = new ArrayList(); @@ -131,14 +133,14 @@ public class FormsPoster { 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(); + k_iter = ansAction.currentPremise.keySet().iterator(); while (k_iter.hasNext()) { key = k_iter.next().split("::")[0]; if (curInfoPoint.get(key) != null && !curInfoPoint.equals("")) pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key))); } - k_iter = ansCondition.historyPremise.keySet().iterator(); + k_iter = ansAction.historyPremise.keySet().iterator(); while (k_iter.hasNext()) { key = k_iter.next().split("::")[0]; if(!historyInfoPoint.get(key).equals("")) { @@ -228,16 +230,11 @@ public class FormsPoster { if (m.find()) { npc = m.group(1); - if ((ResponseFilter.sameLocation((String)textscore.get(0), curInfoPoint, historyInfoPoint, gameEnv, worldController, historyInfoPoint.get("site"), logWriter) == 1)) { + if ((GameBotUtil.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), historyInfoPoint, gameEnv, worldController)); - historyInfoPoint.put("qa_score", String.valueOf(textscore.get(1))); - break; } } diff --git a/src/processing/ResponseFilter.java b/src/processing/ResponseFilter.java index 64bf2fb..8839631 100644 --- a/src/processing/ResponseFilter.java +++ b/src/processing/ResponseFilter.java @@ -1,83 +1,72 @@ -package com.qiwu.chatbotbackend.processing; - -import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; -import com.qiwu.chatbotbackend.entity.Condition; -import com.qiwu.chatbotbackend.entity.UserInfo; -import com.qiwu.chatbotbackend.gameDesign.PlotConstructor; - -import java.util.*; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor.TALKER_PATTERN; -import static com.qiwu.chatbotbackend.processing.FormsPoster.TALKER; - -public class ResponseFilter { - - static String filt(Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController, - String reply, UserInfo userInfo, Condition ansCondition, LogWriter logWriter){ - String botType = userInfo.varInitialMap.get("botType"), npc, finalUnknownText; - - - if(botType == null || botType.equals("")){ - return reply; - - }else if (botType.equals("game")){ - - String site = historyInfoPoint.get("site"); - - - reply = MyFunc.randStr(reply.split("~")); - - if(reply.endsWith("请说开始剧情或者继续剧情")){ - return reply; - } - - if(historyInfoPoint.get("plot_jump_text") != null && !historyInfoPoint.get("plot_jump_text").equals("")){ - return reply; - } - - if(reply.startsWith(String.format(TALKER_PATTERN, PlotConstructor.ASSISTANT, PlotConstructor.ASSISTANT_EMOTION)) ){ - return reply; - }else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1){ - return reply; - }else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0 && !reply.equals("")){ - return appendTalker(reply, historyInfoPoint, gameEnv, worldController); - }else if (reply.equals("") && ( - (historyInfoPoint.get("common_answer") != null && !historyInfoPoint.get("common_answer").equals(""))) - || (historyInfoPoint.get("map_query") != null && !historyInfoPoint.get("map_query").equals("")) - || (historyInfoPoint.get("goods_query") != null && !historyInfoPoint.get("goods_query").equals("") ) - || (historyInfoPoint.get("npc_query") != null && !historyInfoPoint.get("npc_query").equals("")) - ){ - return reply; - } - - - - - - if(userInfo.varInitialMap.get("unknownTextList") != null){ - List unknownList = new ArrayList(); - - String lastTalker = ""; - //如果作者当前地点和剧情所在地点相同,那么回答unknown文本的人必须是上个剧情中的人 -// if(historyInfoPoint.get("game_step").endsWith(historyInfoPoint.get(String.format(PlotConstructor.TASK_LINE, site)))){ -// Matcher m = findTalker(historyInfoPoint.get(String.format(PlotConstructor.TASK_REPLY, site))); -// while(m.find()) { -// //回答unknown文本的npc必须处于在线模式 -// npc = m.group(1); -// if(isOnlineMode(npc, historyInfoPoint)) { -// lastTalker = npc; -// }else{ -// System.out.println(npc + "是离线模式"); -// } -// } +//package com.qiwu.chatbotbackend.processing; +// +//import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; +//import com.qiwu.chatbotbackend.entity.Action; +//import com.qiwu.chatbotbackend.entity.UserInfo; +//import com.qiwu.chatbotbackend.gameDesign.PlotConstructor; +// +//import java.util.*; +//import java.util.regex.Matcher; +//import java.util.regex.Pattern; +// +//import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor.TALKER_PATTERN; +//import static com.qiwu.chatbotbackend.processing.FormsPoster.TALKER; +// +//public class ResponseFilter { +// +// static String filt(Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController, +// String reply, UserInfo userInfo, Action ansCondition, LogWriter logWriter){ +// String botType = userInfo.varInitialMap.get("botType"), npc, finalUnknownText; +// +// +// if(botType == null || botType.equals("")){ +// return reply; +// +// }else if (botType.equals("game")){ +// +// String site = historyInfoPoint.get("site"); +// +// +// reply = MyFunc.randStr(reply.split("~")); +// +// if(reply.endsWith("请说开始剧情或者继续剧情")){ //不需要添加人名和情绪 +// return reply; +// } +// +// if(historyInfoPoint.get("plot_jump_text") != null && !historyInfoPoint.get("plot_jump_text").equals("")){ +// return reply; +// } +// +// if(reply.startsWith(String.format(TALKER_PATTERN, PlotConstructor.ASSISTANT, PlotConstructor.ASSISTANT_EMOTION)) ){ +// return reply; +// }else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1){ +// return reply; +// }else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0 && !reply.equals("")){ +// return appendTalker(reply, historyInfoPoint, gameEnv, worldController); +// }else if (reply.equals("") && ( +// (historyInfoPoint.get("common_answer") != null && !historyInfoPoint.get("common_answer").equals("")) && !historyInfoPoint.get("common_answer").equals("no answer")) +// || (historyInfoPoint.get("map_query") != null && !historyInfoPoint.get("map_query").equals("")) +// || (historyInfoPoint.get("goods_query") != null && !historyInfoPoint.get("goods_query").equals("") ) +// || (historyInfoPoint.get("npc_query") != null && !historyInfoPoint.get("npc_query").equals("")) +// ){ +// return reply; +// } +// +// +// +// +// +// if(userInfo.varInitialMap.get("unknownTextList") != null){ +// List unknownList = new ArrayList(); +// +// String lastTalker = ""; +// //如果作者当前地点和剧情所在地点相同,那么回答unknown文本的人必须是上个剧情中的人 +// // // for (String ans : userInfo.varInitialMap.get("unknownTextList").split("~")) { // if (ans.equals("")) // continue; -// if (ans.contains(lastTalker) &&sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1) { -// +// if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1) { // if(isOnlineText(ans, historyInfoPoint)) // unknownList.add(ans); // //return ans; @@ -89,148 +78,131 @@ public class ResponseFilter { // return MyFunc.randStr(unknownList); // } // +// } +// +// if(userInfo.varInitialMap.get("finalUnknownText") != null){ +// finalUnknownText = userInfo.varInitialMap.get("finalUnknownText"); +// List finalUnknownList = new ArrayList(); +// +// +// for(String ans:finalUnknownText.split("~")){ +// if(ans.equals("")) +// continue; +// if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1){ +// if(isOnlineText(ans, historyInfoPoint)) +// finalUnknownList.add(ans); +// //return ans; +// }else if(sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0){ +// finalUnknownList.add(appendTalker(ans, historyInfoPoint, gameEnv, worldController)); +// } +// } +// if(finalUnknownList.size() > 0){ +// return MyFunc.randStr(finalUnknownList); +// +// } +// } +// +// } +// +// +// return "找不到匹配文本"; +// } +// +// +// +// 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); +// location = worldController.worldOperation(gameEnv, "npc_query", "queryLocationByNPCName:" + npc, curInfoPoint, historyInfoPoint); +// if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){ +// if(gameEnv.queryNpcAttrByNpcName(npc, "能否说话") == null || gameEnv.queryNpcAttrByNpcName(npc, "能否说话").equals("能")){ +// flag = 1; +// logWriter.record("\"" + reply + "\":匹配", 1); // }else { - - for (String ans : userInfo.varInitialMap.get("unknownTextList").split("~")) { - if (ans.equals("")) - continue; - if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1) { - if(isOnlineText(ans, historyInfoPoint)) - unknownList.add(ans); - //return ans; - } else if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0) { - unknownList.add(appendTalker(ans, historyInfoPoint, gameEnv, worldController)); - } - } - if (unknownList.size() > 0) { - return MyFunc.randStr(unknownList); - } +// flag = 2; +// logWriter.record(npc + "不能说话", 1); // } - } - - if(userInfo.varInitialMap.get("finalUnknownText") != null){ - finalUnknownText = userInfo.varInitialMap.get("finalUnknownText"); - List finalUnknownList = new ArrayList(); - - - for(String ans:finalUnknownText.split("~")){ - if(ans.equals("")) - continue; - if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1){ - if(isOnlineText(ans, historyInfoPoint)) - finalUnknownList.add(ans); - //return ans; - }else if(sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0){ - finalUnknownList.add(appendTalker(ans, historyInfoPoint, gameEnv, worldController)); - } - } - if(finalUnknownList.size() > 0){ - return MyFunc.randStr(finalUnknownList); - - } - } - - } - - - return "找不到匹配文本"; - } - - - - 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); - location = worldController.worldOperation(gameEnv, "npc_query", "queryLocationByNPCName:" + npc, curInfoPoint, historyInfoPoint); - if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){ - if(gameEnv.queryNpcAttrByNpcName(npc, "能否说话") == null || gameEnv.queryNpcAttrByNpcName(npc, "能否说话").equals("能")){ - flag = 1; - logWriter.record("\"" + reply + "\":匹配", 1); - }else { - flag = 2; - logWriter.record(npc + "不能说话", 1); - } - - }else { - logWriter.record("\"" + reply + "\":" + npc +"不在" + site + ",跳过",1 ); - flag = 2; - } - }else{ - logWriter.record("\"" + reply + "\":没有npc名",1 ); - flag = 0; - } - return flag; - - } - - /** - * 在头部没有【%s@%s】的文本加上【%s@%s】 - * @param reply - * @param historyInfoPoint - * @param gameEnv - * @param worldController - * @return - */ - static String appendTalker(String reply, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController){ - - List npcList = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site")); - String npc = ""; - List filtedNpcList = new ArrayList(); - - for(String npcName:npcList){ - if(isOnlineMode(npcName, historyInfoPoint)) { - filtedNpcList.add(npcName); - }else{ - System.out.println(npcName + "是离线模式"); - } - } - if(filtedNpcList.size() != 0) - npc = MyFunc.randStr(filtedNpcList); - else - npc = historyInfoPoint.get(PlotConstructor.ASSISTANT); - - - return String.format(TALKER_PATTERN, npc, PlotConstructor.ASSISTANT_EMOTION) + reply; - - } - - static Boolean isOnlineMode(String npc, Map historyInfoPoint){ - return historyInfoPoint.get("onlineModeTalkers").contains("," + npc + ","); - } - static Boolean isOnlineText(String text, Map historyInfoPoint){ - Matcher m = findTalker(text); - String npc = ""; - if(m.find()) { - npc = m.group(1); - return historyInfoPoint.get("onlineModeTalkers").contains("," + npc + ","); - }else{ - System.out.println("竟然没找到npc"); - return false; - } - } - -} +// +// }else { +// logWriter.record("\"" + reply + "\":" + npc +"不在" + site + ",跳过",1 ); +// flag = 2; +// } +// }else{ +// logWriter.record("\"" + reply + "\":没有npc名",1 ); +// flag = 0; +// } +// return flag; +// +// } +// +// /** +// * 在头部没有【%s@%s】的文本加上【%s@%s】 +// * @param reply +// * @param historyInfoPoint +// * @param gameEnv +// * @param worldController +// * @return +// */ +// static String appendTalker(String reply, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController){ +// +// List npcList = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site")); +// String npc = ""; +// List filtedNpcList = new ArrayList(); +// +// for(String npcName:npcList){ +// if(isOnlineMode(npcName, historyInfoPoint)) { +// filtedNpcList.add(npcName); +// }else{ +// System.out.println(npcName + "是离线模式"); +// } +// } +// if(filtedNpcList.size() != 0) +// npc = MyFunc.randStr(filtedNpcList); +// else +// npc = historyInfoPoint.get(PlotConstructor.ASSISTANT); +// +// +// return String.format(TALKER_PATTERN, npc, PlotConstructor.ASSISTANT_EMOTION) + reply; +// +// } +// +// static Boolean isOnlineMode(String npc, Map historyInfoPoint){ +// return historyInfoPoint.get("onlineModeTalkers").contains("," + npc + ","); +// } +// static Boolean isOnlineText(String text, Map historyInfoPoint){ +// Matcher m = findTalker(text); +// String npc = ""; +// if(m.find()) { +// npc = m.group(1); +// return historyInfoPoint.get("onlineModeTalkers").contains("," + npc + ","); +// }else{ +// System.out.println("竟然没找到npc"); +// return false; +// } +// } +// +//} diff --git a/src/processing/UserInfoController.java b/src/processing/UserInfoController.java index e534023..82d9d57 100644 --- a/src/processing/UserInfoController.java +++ b/src/processing/UserInfoController.java @@ -1,15 +1,12 @@ package com.qiwu.chatbotbackend.processing; -import com.qiwu.chatbotbackend.entity.Condition; +import com.qiwu.chatbotbackend.entity.Action; import com.qiwu.chatbotbackend.entity.UserInfo; import javax.servlet.ServletContext; import java.io.*; import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; +import java.util.*; public class UserInfoController { @@ -85,7 +82,7 @@ public class UserInfoController { } - public static Condition buildCondition(Condition condition, String line) { + public static Action buildCondition(Action action, String line) { String feature, url, element[], pair[], next[], cur_premises[], history_premises[], premises[], features[], firstCnditionName,text[]; @@ -106,25 +103,25 @@ public class UserInfoController { history_premises = premises[1].split(","); if (premises.length < 4) - condition.auxiliaryPriority = 0; + action.auxiliaryPriority = 0; else - condition.auxiliaryPriority = Integer.parseInt(premises[3].split("=", 2)[1]); + action.auxiliaryPriority = Integer.parseInt(premises[3].split("=", 2)[1]); if(premises.length < 5) - condition.configName = ""; + action.configName = ""; else - condition.configName = premises[4].split("=", 2)[1]; + action.configName = premises[4].split("=", 2)[1]; next = element[1].split("\\|"); if (next.length < 4) - return condition; - condition.answer = next[0].split("~"); - //condition.nextStep = next[1]; + return action; + action.answer = next[0].split("~"); + //action.nextStep = next[1]; //第二处 - condition.nextStep = next[1].split("=", 2)[1]; - condition.id = Integer.parseInt(next[3].split("=")[1]); - condition.status = next[2].split("=")[1]; + action.nextStep = next[1].split("=", 2)[1]; + action.id = Integer.parseInt(next[3].split("=")[1]); + action.status = next[2].split("=")[1]; //featureMap的构建 @@ -135,48 +132,48 @@ public class UserInfoController { } else if (feat.startsWith("updateKnowledge")) { String[] knowledge = feat.split("-<-"); int length = knowledge.length; - condition.featureMap.put("updateKnowledge", ""); + action.featureMap.put("updateKnowledge", ""); for (int i = 1; i < length; i++) { if (knowledge[i].equals("") || knowledge[i].equals(" ")) continue; pair = knowledge[i].split(":", 2); - condition.updateKnowledge.put(pair[0], pair[1]); + action.updateKnowledge.put(pair[0], pair[1]); } } else if (feat.startsWith("post")) { pair = feat.split("\\(", 2); url = pair[1]; url = url.substring(0, url.length() - 1); pair = pair[0].split("::"); - condition.featureMap.put("post", url + "|" + pair[1]); + action.featureMap.put("post", url + "|" + pair[1]); } else { - condition.featureMap.put(feat, ""); + action.featureMap.put(feat, ""); } } - insertPremise(condition.currentPremise, cur_premises); - insertPremise(condition.historyPremise, history_premises); + insertPremise(action.currentPremise, cur_premises); + insertPremise(action.historyPremise, history_premises); //满足条件越多,优先级越大 - condition.priority = condition.historyPremise.size() + condition.currentPremise.size(); - condition.activePriority = condition.priority; + action.priority = action.historyPremise.size() + action.currentPremise.size(); + action.activePriority = action.priority; /* for(String premise:cur_premises){ pair = premise.split("="); - condition.indexName.add(pair[0]); + action.indexName.add(pair[0]); } */ firstCnditionName = cur_premises[0]; if (firstCnditionName.equals(" ")) - condition.indexName = "emptySet"; + action.indexName = "emptySet"; else - condition.indexName = firstCnditionName.split("=")[0].split("::")[0]; + action.indexName = firstCnditionName.split("=")[0].split("::")[0]; } catch (IndexOutOfBoundsException e) { e.printStackTrace(); System.out.println(line); System.out.println("文本格式有误"); } - return condition; + return action; } @@ -189,11 +186,11 @@ public class UserInfoController { */ public static UserInfo buildUserInfo(BufferedReader br, UserInfo userinfo, boolean overRide) throws IOException { String line, infoName, extraElements[]; - HashMap> conditionTable = null; + HashMap> conditionTable = null; //是否覆盖原有的数据 if (overRide) { - conditionTable = new HashMap>(); + conditionTable = new HashMap>(); userinfo.id2condition.clear(); userinfo.id2config.clear(); userinfo.configStr = ""; @@ -204,7 +201,7 @@ public class UserInfoController { conditionTable = userinfo.conditionTable; } - List conditionList = null; + List actionList = null; while ((line = br.readLine()) != null) { @@ -221,19 +218,19 @@ public class UserInfoController { extraElements = line.split("\\|", -1); userinfo.varInitialMap.put(extraElements[1], extraElements[2]); } else { - Condition condition = new Condition(); - condition = buildCondition(condition, line); - conditionList = conditionTable.get(condition.indexName); - if (conditionList == null) - conditionList = new ArrayList(); - conditionList.add(condition); - conditionTable.put(condition.indexName, conditionList); - if (condition.id != 0) { - if(!condition.configName.equals("")){ - userinfo.name2condition.put(condition.configName, condition); + Action action = new Action(); + action = buildCondition(action, line); + actionList = conditionTable.get(action.indexName); + if (actionList == null) + actionList = new ArrayList(); + actionList.add(action); + conditionTable.put(action.indexName, actionList); + if (action.id != 0) { + if(!action.configName.equals("")){ + userinfo.name2condition.put(action.configName, action); } - userinfo.id2config.put(condition.id, line); - userinfo.id2condition.put(condition.id, condition); + userinfo.id2config.put(action.id, line); + userinfo.id2condition.put(action.id, action); } } @@ -253,7 +250,7 @@ public class UserInfoController { } /** - * 通过split方法解析配置文件中的条件部分(如:xihuan=+dota+英雄联盟) + * 通过split方法解析配置文件中的条件部分(如:xihuan::match-Include=+dota+英雄联盟) * * @param premiseMap 前提条件哈希表 */ @@ -300,7 +297,7 @@ public class UserInfoController { return null; //userinfo = new UserInfo(botAccount); - //userinfo.conditionTable = new HashMap>(); + //userinfo.conditionTable = new HashMap>(); } else { userinfo = (UserInfo) context.getAttribute(botAccount); } @@ -309,4 +306,228 @@ public class UserInfoController { return userinfo; } + + + public static boolean deleteConfig(String userName, String configId, String data, ServletContext context) throws IOException { + int id = Integer.parseInt(configId); + Action action = new Action(); + UserInfoController userInfoController = new UserInfoController(); + //data=configLine+"---"+conditionNameList + + String conditionNameList[] = data.split(","); + String conditionName = ""; + if (context.getAttribute(userName) == null) { + userInfoController.userConfigInit(userName, context); + } + UserInfo userInfo = (UserInfo) context.getAttribute(userName); + + if (userInfo.id2config.containsKey(id)) { + Action oldAction = userInfo.id2condition.get(id); + //------------------- + try { + + conditionName = oldAction.indexName; + } catch (Exception e) { + e.printStackTrace(); + } + + + if (userInfo.conditionTable.get(conditionName) != null) { + List actionList = userInfo.conditionTable.get(conditionName); + Iterator condIter = userInfo.conditionTable.get(conditionName).iterator(); + while (condIter.hasNext()) { + Action c = condIter.next(); + if (c.id == id) { + condIter.remove(); + } + } + } + + userInfo.name2condition.remove(oldAction.configName); + userInfo.id2config.remove(id); + userInfo.id2condition.remove(id); + } else { + System.out.println("未找到要删除的configId"); + } + + return true; + } + + public static boolean batchDeleteConfig(String userName, List idGroup, UserInfo userInfo) throws IOException { + Action action = new Action(); + String conditionName = ""; + + for (int configId : idGroup) { + if (userInfo.id2config.containsKey(configId)) { + Action oldAction = userInfo.id2condition.get(configId); + try { + + conditionName = oldAction.indexName; + } catch (Exception e) { + e.printStackTrace(); + } + + + if (userInfo.conditionTable.get(conditionName) != null) { + List actionList = userInfo.conditionTable.get(conditionName); + Iterator condIter = userInfo.conditionTable.get(conditionName).iterator(); + while (condIter.hasNext()) { + Action c = condIter.next(); + if (c.id == configId) { + condIter.remove(); + } + } + } + + userInfo.name2condition.remove(oldAction.configName); + userInfo.id2config.remove(configId); + userInfo.id2condition.remove(configId); + } else { + System.out.println("未找到要删除的configId:" + configId); + } + } + + + return true; + } + + + public static boolean insertConfig(String userName, String configId, String data, ServletContext context) throws IOException { + Action action = new Action(); + //data=configLine+"---"+conditionNameList + String dataPair[] = data.split("---"); + String configLine = dataPair[0]; + String conditionNameList[]; + UserInfoController userInfoController = new UserInfoController(); + int id = Integer.parseInt(configId); + + action = userInfoController.buildCondition(action, configLine); + + if (context.getAttribute(userName) == null) { + userInfoController.userConfigInit(userName, context); + } + UserInfo userinfo = (UserInfo) context.getAttribute(userName); + + if (userinfo.conditionTable.get(action.indexName) == null) { + List actionList = new ArrayList(); + userinfo.conditionTable.put(action.indexName, actionList); + } + + if(!action.configName.equals("")){ + userinfo.name2condition.put(action.configName, action); + } + userinfo.conditionTable.get(action.indexName).add(action); + userinfo.id2config.put(id, configLine); + userinfo.id2condition.put(id, action); + + return true; + + } + + public static boolean updateVariable(String userName, String configId, String data, ServletContext context) throws IOException { + Action action = new Action(); + //data=configLine+"---"+conditionNameList + String dataPair[] = data.split("---", -1); + String name = dataPair[0], value = dataPair[1]; + + UserInfoController userInfoController = new UserInfoController(); + + + if (context.getAttribute(userName) == null) { + userInfoController.userConfigInit(userName, context); + } + UserInfo userinfo = (UserInfo) context.getAttribute(userName); + userinfo.varInitialMap.put(name, value); + + + return true; + + } + + public static boolean deleteVariable(String userName, String configId, String data, ServletContext context) throws IOException { + //data=configLine+"---"+conditionNameList + String name = data; + UserInfoController userInfoController = new UserInfoController(); + + + if (context.getAttribute(userName) == null) { + userInfoController.userConfigInit(userName, context); + } + UserInfo userinfo = (UserInfo) context.getAttribute(userName); + userinfo.varInitialMap.remove(name); + + + return true; + + } + + + public static boolean updateExtraInfo(String userName, String data, ServletContext context) throws IOException { + UserInfoController userInfoController = new UserInfoController(); + + + if (context.getAttribute(userName) == null) { + userInfoController.userConfigInit(userName, context); + } + UserInfo userinfo = (UserInfo) context.getAttribute(userName); + + String extraElements[] = data.split("\\|"); + userinfo.extraInfo.put(extraElements[1], extraElements[2]); + + return true; + } + + + public static String writeConfigText(String userName, UserInfo userinfo) throws IOException { + + + String CONFIG_DIR = System.getProperty("user.dir") + "/config", configText; + String path = CONFIG_DIR + "/" + userName + ".txt"; + + + File file = new File(path); + File dir = new File(System.getProperty("user.dir") + "/config"); + + System.out.println(userName); + System.out.println("config_dir" + dir.getAbsolutePath()); + String returnMessage = "success"; + + if (!dir.exists()) + dir.mkdir(); + if (!file.exists()) { + file.createNewFile(); + } + + FileWriter fw = new FileWriter(file); + BufferedWriter bw = new BufferedWriter(fw); + try { + Iterator keyIter = userinfo.extraInfo.keySet().iterator(); + while (keyIter.hasNext()) { + String info = keyIter.next(); + if (!userinfo.extraInfo.get(info).equals("")) + bw.write("-extraInfo-|" + info + "|" + userinfo.extraInfo.get(info) + "\n"); + } + + keyIter = userinfo.varInitialMap.keySet().iterator(); + while (keyIter.hasNext()) { + String info = keyIter.next(); + bw.write("-varInitial-|" + info + "|" + userinfo.varInitialMap.get(info) + "\n"); + } + + Iterator idIter = userinfo.id2config.keySet().iterator(); + while (idIter.hasNext()) { + int id = idIter.next(); + bw.write(userinfo.id2config.get(id) + "\n"); + } + bw.write("\n"); + } catch (Exception e) { + e.printStackTrace(); + returnMessage = "config file write error"; + } finally { + bw.close(); + fw.close(); + } + + return returnMessage; + } } diff --git a/src/processing/WorldController.java b/src/processing/WorldController.java index 85005a7..85016f8 100644 --- a/src/processing/WorldController.java +++ b/src/processing/WorldController.java @@ -3,14 +3,15 @@ package com.qiwu.chatbotbackend.processing; import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; import com.qiwu.chatbotbackend.entity.UserInfo; -import com.qiwu.chatbotbackend.gameDesign.PlotConstructor; +import com.qiwu.chatbotbackend.gameDesign.PlotConstructor2; +import com.qiwu.chatbotbackend.task.utils.GameBotUtil; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.regex.Matcher; -import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor.ASSISTANT_EMOTION; +import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor2.ASSISTANT_EMOTION; public class WorldController { public LogWriter logWriter = null; @@ -22,7 +23,7 @@ public class WorldController { } public String worldOperation(GameEnv gameEnv, String varName, String varValue, Map currentInfoPoint, MaphistoryInfoPoint){ - String moduleName = "", valuePair[] = varValue.split(":", 2), returnStr=""; + String moduleName = "", valuePair[] = varValue.split(":", 2), returnStr="", owner; String namePair[] = varName.split("_"); boolean operationFlag = true; List textList = null; @@ -33,8 +34,10 @@ public class WorldController { String location = "", value = ""; if(valuePair[0].startsWith("query")){ //查询专用 String ItemName = ""; + String currentLocation; if(varName.startsWith("goods_")) { + currentLocation = historyInfoPoint.get("site"); switch (valuePair[0]) { case "queryGoodsIntro": subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2); @@ -78,15 +81,30 @@ public class WorldController { case "queryLocationByConditionName": // ItemName = currentInfoPoint.get(valuePair[1]).split(":")[1]; + ItemName = gameEnv.getGoodsNameByNickname(currentLocation, ItemName); returnStr = gameEnv.queryGoodsAttrByGoodsName(ItemName, "可被询问"); if(returnStr == null || returnStr.equals("否")){ - returnStr = "没找到"; + returnStr = "隐藏了"; } else if(returnStr.equals("是")){ location = gameEnv.queryGoodsAttrByGoodsName(ItemName, "location"); if(location == null){ returnStr = "没找到"; }else{ - returnStr = userInfo.varInitialMap.get("FIND_ITEM_LOCATION").replace("[物品名]", ItemName).replace("[地点]", location); + owner = gameEnv.queryGoodsAttrByGoodsName(ItemName, "所属角色"); + logWriter.record(ItemName + "-owner:" + owner, 0); + + if(owner != null && !owner.equals("")){ + //如果物品的所属角色是玩家,那么回答物品在你身上 + if(owner.equals("玩家")){ + returnStr = userInfo.varInitialMap.get("ITEM_IS_YOURS"); + }else { + //不然回答物品在某个人身上 + returnStr = userInfo.varInitialMap.get("FIND_TEM_OWNER").replace("[物品名]", ItemName).replace("[人名]", owner); + } + }else { + //没有所属角色就回答物品在某个地点 + returnStr = userInfo.varInitialMap.get("FIND_ITEM_LOCATION").replace("[物品名]", ItemName).replace("[地点]", location); + } } } break; @@ -139,9 +157,10 @@ public class WorldController { subValuePair = currentInfoPoint.get(valuePair[1]).split(":", 2); subValuePair[0] = subValuePair[0].replace("哪里", "location"); value = gameEnv.queryNpcAttrByNpcName(subValuePair[0], subValuePair[1]); - if(returnStr == null) { + if(value == null) { returnStr = "没找到"; }else{ + returnStr = userInfo.varInitialMap.get("GET_NPC_ATTR").replace("[人名]", subValuePair[0]).replace("[属性名]", subValuePair[1]).replace("[属性值]", value); } @@ -168,6 +187,8 @@ public class WorldController { if(returnStr == null || returnStr.equals("否")){ returnStr = "没找到"; } else if(returnStr.equals("是")){ + + location = gameEnv.queryNpcAttrByNpcName(NPCName, "location"); if(location == null){ returnStr = "没找到"; @@ -197,12 +218,12 @@ public class WorldController { case "queryLastTalker": String lastTalker = "没找到npc名字"; - Matcher m = ResponseFilter.findTalker(historyInfoPoint.get("lastReply")); + Matcher m = GameBotUtil.findTalker(historyInfoPoint.get("lastReply")); while(m.find()){ lastTalker = m.group(1); } - returnStr = String.format(PlotConstructor.TALKER_PATTERN, lastTalker, ASSISTANT_EMOTION) + userInfo.varInitialMap.get("WHO_YOU_ARE").replace("[人名]", lastTalker); + returnStr = String.format(PlotConstructor2.TALKER_PATTERN, lastTalker, ASSISTANT_EMOTION) + userInfo.varInitialMap.get("WHO_YOU_ARE").replace("[人名]", lastTalker); break; @@ -211,6 +232,8 @@ public class WorldController { } }else if (varName.startsWith("map_")) { String format = ""; + String start = historyInfoPoint.get("site"); + String destination = ""; List sites = new ArrayList<>(); switch (valuePair[0]) { @@ -317,10 +340,12 @@ public class WorldController { returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST"); break; } + destination = currentInfoPoint.get(valuePair[1]).split(":")[1]; + destination = gameEnv.getPlaceNameByNickname(start, destination); - sites = gameEnv.queryPathBySite(historyInfoPoint.get("site"), currentInfoPoint.get(valuePair[1]).split(":")[1]); + sites = gameEnv.queryPathBySite(historyInfoPoint.get("site"), destination); if(sites == null) { - returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST"); + returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST") + destination; } else { if(sites.size() > 0) { @@ -329,7 +354,7 @@ public class WorldController { for(String site:sites){ text.append("、" + site); } - returnStr = format.replace("[途径]", text.substring(1)).replace("[目的地]", currentInfoPoint.get(valuePair[1]).split(":")[1]); + returnStr = format.replace("[途径]", text.substring(1)).replace("[目的地]", destination); } } break; @@ -340,15 +365,17 @@ public class WorldController { }else { format = "通过[途径]可以到达[目的地]"; } + destination = currentInfoPoint.get(valuePair[1]).split(":")[1]; + destination = gameEnv.getPlaceNameByNickname(start, destination); if(!currentInfoPoint.containsKey(valuePair[1])) { - returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST"); + returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST") + destination; break; } - sites = gameEnv.queryPathBySite(historyInfoPoint.get("site"), currentInfoPoint.get(valuePair[1]).split(":")[1]); + sites = gameEnv.queryPathBySite(start, destination); if(sites == null) { - returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST"); + returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST") + destination; } else { if(sites.size() > 0) { StringBuffer text = new StringBuffer(); @@ -356,7 +383,7 @@ public class WorldController { for(String site:sites){ text.append("、" + site); } - returnStr = format.replace("[途径]", text.substring(1)).replace("[目的地]", currentInfoPoint.get(valuePair[1]).split(":")[1]); + returnStr = format.replace("[途径]", text.substring(1)).replace("[目的地]", destination); } } break; @@ -368,7 +395,7 @@ public class WorldController { } - sites = gameEnv.queryCanGoBySite(historyInfoPoint.get("site")); + sites = gameEnv.queryCanGoBySite(start); if(sites == null || sites.size() == 0) { returnStr = "无处可去了"; } else { @@ -413,7 +440,7 @@ public class WorldController { } - returnStr = format.replace("[任务描述]", userInfo.varInitialMap.get(PlotConstructor.TASK_DESCRIPTION)); + returnStr = format.replace("[任务描述]", userInfo.varInitialMap.get(PlotConstructor2.TASK_DESCRIPTION)); break; case "queryWhereIam": @@ -460,4 +487,6 @@ public class WorldController { } + + } diff --git a/src/servlet/ContextDestroyListener.java b/src/servlet/ContextDestroyListener.java new file mode 100644 index 0000000..6a21b42 --- /dev/null +++ b/src/servlet/ContextDestroyListener.java @@ -0,0 +1,60 @@ +package com.qiwu.chatbotbackend.servlet; + +import com.qiwu.chatbotbackend.db.SqlHelper; +import com.qiwu.chatbotbackend.entity.ChatCache; +import com.qiwu.chatbotbackend.processing.ChatCacheController; + +import javax.servlet.ServletContext; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import javax.servlet.annotation.WebListener; +import java.io.IOException; +import java.sql.SQLException; +import java.util.Iterator; +import java.util.Map; + +@WebListener +public class ContextDestroyListener implements ServletContextListener { + + public void contextDestroyed(ServletContextEvent sce) { + System.out.println("destory context...."); + /** + * 在程序中断时先把所有存在servletContext中的对话缓存数据保存下来 + */ + + String chatKey; + ServletContext servletContext = sce.getServletContext(); + Object obj = servletContext.getAttribute("chatCache"); + ChatCache cache = null; + SqlHelper helper = null; + + if(obj != null){ + Map chatCacheMap = (Map)obj; + + Iterator cacheIter = chatCacheMap.keySet().iterator(); + try { + helper = new SqlHelper(); + while (cacheIter.hasNext()) { + chatKey = cacheIter.next(); + cache = chatCacheMap.get(chatKey); + + + + //当用户id和随机对话id不同时,表示用户为登录状态,用户登录且开始游戏,则可以存档 + if (cache != null && !cache.getRandKey().equals(cache.getUserKey()) && cache.isGameStart()) { + System.out.println(String.format("saving %s", chatKey)); + ChatCacheController.saveChatCache(cache, helper); + } + } + cacheIter.remove(); + helper.destroy(); + + } catch (SQLException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + +} diff --git a/src/servlet/GameDesignServlet.java b/src/servlet/GameDesignServlet.java index 645f7e7..7d1414d 100644 --- a/src/servlet/GameDesignServlet.java +++ b/src/servlet/GameDesignServlet.java @@ -2,11 +2,10 @@ package com.qiwu.chatbotbackend.servlet; import com.alibaba.fastjson.JSONObject; import com.qiwu.chatbotbackend.db.SqlHelper; -import com.qiwu.chatbotbackend.entity.JConfig; +import com.qiwu.chatbotbackend.entity.ConfigTerm; import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.gameDesign.*; import com.qiwu.chatbotbackend.processing.MyFunc; -import com.qiwu.chatbotbackend.processing.ConditionTableController; import com.qiwu.chatbotbackend.processing.UserInfoController; import javax.servlet.ServletContext; @@ -87,15 +86,13 @@ public class GameDesignServlet extends HttpServlet { JSONObject gameElements = helper.queryGameElementsByBotId(dataId); gameElements.put("auth", request.getHeader("authorization")); - System.out.println(gameElements.toJSONString()); + //System.out.println(gameElements.toJSONString()); botId = (Integer)gameElements.get("botId"); botAccount = (String) gameElements.get("botAccount"); userName = (String)gameElements.get("userName"); botName = (String)gameElements.get("botName"); - - //假设重建用户信息 if (context.getAttribute(botAccount) == null) { UserInfoController.userConfigInit(botAccount, context); @@ -104,8 +101,6 @@ public class GameDesignServlet extends HttpServlet { UserInfo userinfo = (UserInfo) context.getAttribute(botAccount); - //UserInfo userinfo = new UserInfo(botAccount); - //清空之前生成的配置条目 try { flag = botInit(botId, userinfo, helper); @@ -127,7 +122,7 @@ public class GameDesignServlet extends HttpServlet { ldt = LocalDateTime.now(); now = ldt.format(dtf); timeUsedDetect.append("\n,预处理之后:").append(now); - String moduleList[] = {"map", "goods", "globalVariable", "npc", "plots"}; + String moduleList[] = {"map", "goods", "globalVariable", "npc", "plots", "listeningActions"}; for(String moduleName: moduleList){ switch (moduleName) { @@ -141,7 +136,7 @@ public class GameDesignServlet extends HttpServlet { constructor = new PlotConstructor2(helper, botId, botAccount, keywordMap, exceptRelation, POS); constructor.construct(gameElements, userinfo); - root = ((PlotConstructor2) constructor).getId2j().get((String) gameElements.get("start")); + root = ((PlotConstructor2) constructor).getPlotIndex().get((String) gameElements.get("start")); break; case "goods": moduleName2 = "物品"; @@ -158,6 +153,10 @@ public class GameDesignServlet extends HttpServlet { constructor = new CharacterConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); constructor.construct(gameElements, userinfo); break; + case "listeningActions": + moduleName2 = "生成处于监听的action"; + constructor = new ListeningConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); + constructor.construct(gameElements, userinfo); default: continue; @@ -170,8 +169,8 @@ public class GameDesignServlet extends HttpServlet { helper.batchInsertVariableByBotId(botId, constructor); List jsonList = new ArrayList(); - for(JConfig jConfig: constructor.getjConfigList()){ - json = jConfig.toJson(constructor.getConditionDescription()); + for(ConfigTerm configTerm : constructor.getConfigTermList()){ + json = configTerm.toJson(constructor.getConditionDescription()); constructor.parseKeyword(json, additionalKeywords, exceptRelation, botName); jsonList.add(json); } @@ -203,7 +202,7 @@ public class GameDesignServlet extends HttpServlet { //System.out.println(mergedConfigText.toString()); UserInfoController.buildUserInfo(br, userinfo, true); context.setAttribute(botAccount, userinfo); - ConditionTableController.writeConfigText(botAccount, userinfo); + UserInfoController.writeConfigText(botAccount, userinfo); ldt = LocalDateTime.now(); now = ldt.format(dtf); timeUsedDetect.append("\n发送post请求前:").append(now); @@ -276,7 +275,7 @@ public class GameDesignServlet extends HttpServlet { JSONObject returnMessage = null; JSONObject actionPostData = new JSONObject(); - System.out.println("root"+ root.toJSONString()); + //System.out.println("root"+ root.toJSONString()); startCondition = (String)root.get("conditionName"); actionPostData.put("startCondition", "start_options"); actionPostData.put("botName_yhm", (String)gameElements.get("botName")); @@ -294,7 +293,7 @@ public class GameDesignServlet extends HttpServlet { actionPostData.put("POS", POS.toString() + POS2); - System.out.println(actionPostData.toJSONString()); + //System.out.println(actionPostData.toJSONString()); userInfo.extraInfo.put("activeAction", startCondition); try { @@ -318,7 +317,7 @@ public class GameDesignServlet extends HttpServlet { File file = new File(path); String line, pair[]; - System.out.println(file.getAbsolutePath()); + //System.out.println(file.getAbsolutePath()); if(file.exists()){ FileReader reader = null; try { diff --git a/src/servlet/GetAnswerServlet.java b/src/servlet/GetAnswerServlet.java index 05df31b..ba9bcb1 100644 --- a/src/servlet/GetAnswerServlet.java +++ b/src/servlet/GetAnswerServlet.java @@ -1,7 +1,7 @@ package com.qiwu.chatbotbackend.servlet; +import com.qiwu.chatbotbackend.entity.Action; import com.qiwu.chatbotbackend.entity.ChatCache; -import com.qiwu.chatbotbackend.entity.Condition; import com.qiwu.chatbotbackend.entity.Solution; import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.processing.*; @@ -39,7 +39,7 @@ public class GetAnswerServlet extends HttpServlet { Map historyInfoPoint = null; Solution bestMatch = null; BasicBotUtil botUtil = null; - Condition ansCondition = null; + Action ansAction = null; boolean debugFlag = false; String ansJ = "", return_str = "", state = "", chatKey = "", botType = "", userKey = "", randKey = ""; String botName = receiveParamters.get("bot_name")[0]; @@ -124,22 +124,21 @@ public class GetAnswerServlet extends HttpServlet { //信息点预处理 - QuestionMatcher matcher = new QuestionMatcher(curInfoPoint, historyInfoPoint, logWriter, userinfo, context, chatCache.getGameEnv(), botUtil); + ActionMatcher matcher = new ActionMatcher(curInfoPoint, historyInfoPoint, logWriter, userinfo, context, chatCache.getGameEnv(), botUtil); /*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/ - //process.removeTimeoutChatkey(context); - //System.out.println(userinfo.conditionTable); //测试 - ansCondition = matcher.getBestMatch(userinfo.conditionTable, context, userinfo); - if (state.equals("") && ansCondition.priority == -1) + ansAction = matcher.getBestMatch(userinfo.conditionTable, context, userinfo); + if (state.equals("") && ansAction.priority == -1) state = "我不理解,"; if (state.equals("")) { try { - bestMatch = matcher.getSolution(ansCondition, context, userinfo); + System.out.println("test2"); + bestMatch = matcher.getSolution(ansAction, context, userinfo); - if ((ansCondition.featureMap.containsKey("activate") && ansCondition.featureMap.containsKey("post")) || ansCondition.featureMap.containsKey("activate:after")) { + if ((ansAction.featureMap.containsKey("activate") && ansAction.featureMap.containsKey("post")) || ansAction.featureMap.containsKey("activate:after")) { //如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段 - bestMatch = matcher.postActivate(ansCondition, context, userinfo); + bestMatch = matcher.postActivate(ansAction, bestMatch, context, userinfo); } } catch (ParseException e) { e.printStackTrace(); @@ -149,6 +148,10 @@ public class GetAnswerServlet extends HttpServlet { } + //针对不同游戏类型做后处理 + botUtil.postprocessing(chatKey, context, bestMatch); + + historyInfoPoint.put("lastReply", bestMatch.getAnswer()); if (debugFlag) { matcher.appendDebugInfo(bestMatch, context); } @@ -167,8 +170,7 @@ public class GetAnswerServlet extends HttpServlet { context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); } - //针对不同游戏类型做后处理 - botUtil.postprocessing(chatKey, context, bestMatch); + ansJ = MyFunc.toJson(bestMatch); } else { diff --git a/src/servlet/UpdateServlet.java b/src/servlet/UpdateServlet.java index b22881c..dfa1a0f 100644 --- a/src/servlet/UpdateServlet.java +++ b/src/servlet/UpdateServlet.java @@ -1,6 +1,6 @@ package com.qiwu.chatbotbackend.servlet; -import com.qiwu.chatbotbackend.entity.Condition; +import com.qiwu.chatbotbackend.entity.Action; import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.processing.MyFunc; import com.qiwu.chatbotbackend.processing.UserInfoController; @@ -31,9 +31,9 @@ public class UpdateServlet extends HttpServlet { String botAccount = request.getParameter("botAccount"); UserInfo userinfo = new UserInfo(botAccount); - userinfo.conditionTable = new HashMap>(); + userinfo.conditionTable = new HashMap>(); - List conditionList = null; + List actionList = null; HashSet keyWordSet = null; BufferedReader br = new BufferedReader(new StringReader(request.getParameter("config_string"))); @@ -56,16 +56,16 @@ public class UpdateServlet extends HttpServlet { } //line = MyFunc.convert2Utf8(line.trim()); userinfo.configStr += line + "\n"; - Condition condition = new Condition(); + Action action = new Action(); try { - condition = UserInfoController.buildCondition(condition, line); - conditionList = userinfo.conditionTable.get(condition.indexName); - if (conditionList == null) - conditionList = new ArrayList(); - conditionList.add(condition); - userinfo.conditionTable.put(condition.indexName, conditionList); + action = UserInfoController.buildCondition(action, line); + actionList = userinfo.conditionTable.get(action.indexName); + if (actionList == null) + actionList = new ArrayList(); + actionList.add(action); + userinfo.conditionTable.put(action.indexName, actionList); /* - for(String name:condition.indexName){ + for(String name:action.indexName){ userinfo.conditionTable.put() } */ diff --git a/src/servlet/UpdateSingleConfigServlet.java b/src/servlet/UpdateSingleConfigServlet.java index 04e5b9a..372c0b2 100644 --- a/src/servlet/UpdateSingleConfigServlet.java +++ b/src/servlet/UpdateSingleConfigServlet.java @@ -1,7 +1,6 @@ package com.qiwu.chatbotbackend.servlet; import com.qiwu.chatbotbackend.entity.UserInfo; -import com.qiwu.chatbotbackend.processing.ConditionTableController; import com.qiwu.chatbotbackend.processing.UserInfoController; import javax.servlet.ServletContext; @@ -10,7 +9,10 @@ import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.io.*; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringReader; @WebServlet(name = "UpdateSingleConfigServlet", urlPatterns = {"/update2"}) public class UpdateSingleConfigServlet extends HttpServlet { @@ -26,26 +28,26 @@ public class UpdateSingleConfigServlet extends HttpServlet { if (context.getAttribute(userName) != null) { switch (processType) { case "insert_config": - ConditionTableController.insertConfig(userName, configId, data, context); + UserInfoController.insertConfig(userName, configId, data, context); break; case "update_config": - ConditionTableController.deleteConfig(userName, configId, data, context); - ConditionTableController.insertConfig(userName, configId, data, context); + UserInfoController.deleteConfig(userName, configId, data, context); + UserInfoController.insertConfig(userName, configId, data, context); break; case "delete_config": - ConditionTableController.deleteConfig(userName, configId, data, context); + UserInfoController.deleteConfig(userName, configId, data, context); break; case "insert_variable": - ConditionTableController.updateVariable(userName, configId, data, context); + UserInfoController.updateVariable(userName, configId, data, context); break; case "delete_variable": - ConditionTableController.deleteVariable(userName, configId, data, context); + UserInfoController.deleteVariable(userName, configId, data, context); break; case "update_variable": - ConditionTableController.updateVariable(userName, configId, data, context); + UserInfoController.updateVariable(userName, configId, data, context); break; case "extra_info": - ConditionTableController.updateExtraInfo(userName, data, context); + UserInfoController.updateExtraInfo(userName, data, context); break; case "batch_update": @@ -82,7 +84,7 @@ public class UpdateSingleConfigServlet extends HttpServlet { String returnMessage = ""; UserInfo userinfo = (UserInfo) context.getAttribute(userName); - returnMessage = ConditionTableController.writeConfigText(userName, userinfo); + returnMessage = UserInfoController.writeConfigText(userName, userinfo); return returnMessage; } diff --git a/src/task/utils/BasicBotUtil.java b/src/task/utils/BasicBotUtil.java index 1ee7142..edbbce8 100644 --- a/src/task/utils/BasicBotUtil.java +++ b/src/task/utils/BasicBotUtil.java @@ -1,6 +1,6 @@ package com.qiwu.chatbotbackend.task.utils; -import com.qiwu.chatbotbackend.entity.Condition; +import com.qiwu.chatbotbackend.entity.Action; import com.qiwu.chatbotbackend.entity.Solution; import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.processing.LogWriter; @@ -126,6 +126,7 @@ public class BasicBotUtil { } public boolean postprocessing(String chatKey, ServletContext context, Solution bestMatch){ + return true; } @@ -173,7 +174,7 @@ public class BasicBotUtil { /** * 额外的更新操作 */ - public void extraOperation(Condition ansCondition, Solution solution) throws IOException { + public void extraOperation(Action ansAction, Solution solution) throws IOException { } diff --git a/src/task/utils/GameBotUtil.java b/src/task/utils/GameBotUtil.java index 7b94f41..0537f4c 100644 --- a/src/task/utils/GameBotUtil.java +++ b/src/task/utils/GameBotUtil.java @@ -3,22 +3,21 @@ package com.qiwu.chatbotbackend.task.utils; import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.entity.*; -import com.qiwu.chatbotbackend.gameDesign.PlotConstructor; +import com.qiwu.chatbotbackend.gameDesign.PlotConstructor2; import com.qiwu.chatbotbackend.processing.ChatCacheController; import com.qiwu.chatbotbackend.processing.LogWriter; +import com.qiwu.chatbotbackend.processing.MyFunc; import com.qiwu.chatbotbackend.processing.WorldController; import javax.servlet.ServletContext; import java.io.IOException; import java.sql.SQLException; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; -import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor.ASSISTANT; -import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor.ASSISTANT_EMOTION; -import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor.TALKER_PATTERN; +import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor2.*; +import static com.qiwu.chatbotbackend.processing.FormsPoster.TALKER; public class GameBotUtil extends BasicBotUtil{ @@ -45,26 +44,26 @@ public class GameBotUtil extends BasicBotUtil{ 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), newInfo = curInfoPoint.get(conditionName); - String destination = info.split(":")[1]; - String site = historyInfoPoint.get("site"); - try { - newInfo = info.replace(destination, worldController.findLocationName(gameEnv, destination, site)); - }catch(Exception e){ - e.printStackTrace(); - } - - logWriter.record(conditionName + ": 将’" + info + "‘替换为‘" + newInfo + "'", 1); - curInfoPoint.put(conditionName, newInfo); - } - } - - historyInfoPoint.put("current_plot_site", historyInfoPoint.get("site")); +// 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), newInfo = curInfoPoint.get(conditionName); +// String destination = info.split(":")[1]; +// String site = historyInfoPoint.get("site"); +// try { +// newInfo = info.replace(destination, worldController.findLocationName(gameEnv, destination, site)); +// }catch(Exception e){ +// e.printStackTrace(); +// } +// +// logWriter.record(conditionName + ": 将’" + info + "‘替换为‘" + newInfo + "'", 1); +// curInfoPoint.put(conditionName, newInfo); +// } +// } + +// historyInfoPoint.put("current_plot_site", historyInfoPoint.get("site")); String activeList[] = historyInfoPoint.get("activeList").split("\\|"); if(activeList.length == 0){ @@ -79,30 +78,64 @@ public class GameBotUtil extends BasicBotUtil{ } 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(); - } - } + StringBuffer finalText = new StringBuffer(); + String plotText = bestMatch.getAnswer(); //将自动跳转文本、qa文本、查询文本拼接 - String queryList[] = { "plot_jump_text" ,"common_answer","map_query", "goods_query", "npc_query"}; + String queryList[] = { "plot_jump_text" ,"common_answer","map_query", "goods_query", "npc_query", "plot_text"}; String queryResult; + + historyInfoPoint.put("plot_text", plotText); + + //整合qa问答、地图、npc查询文本和剧情文本 for(String queryName:queryList){ queryResult = historyInfoPoint.get(queryName); - if(queryResult != null && !queryResult.equals("")){ - if(queryName.equals("common_answer") && queryResult.equals("no answer")) + if(queryResult != null){ + if(queryResult.equals("") && !queryName.equals(queryList[queryList.length-1])){ + //剧情可以为空,其他不行 continue; - if(queryName.equals("map_query") || queryName.equals("goods_query") || queryName.equals("npc_query")){ - queryResult = "【" + historyInfoPoint.get(PlotConstructor.ASSISTANT) + "@" + PlotConstructor.ASSISTANT_EMOTION + "】" + queryResult; } - bestMatch.setAnswer(queryResult + bestMatch.getAnswer() + " " ); + + switch (queryName){ + case "common_answer": + if(!queryResult.equals("no answer")) + finalText.append(queryResult); + break; + case "plot_jump_text": + finalText.append(queryResult); + break; + case "map_query": + case "goods_query": + case "npc_query": + queryResult = appendTalker(findRelateTalkers(false).get(0), queryResult, historyInfoPoint, gameEnv, worldController); + finalText.append(queryResult); + break; + case "plot_text": + if(plotText.endsWith("请说开始剧情或者继续剧情")){ //不需要添加人名和情绪 + finalText.setLength(0); + finalText.append(plotText); + } + //文本为空跳过 + else if(plotText.equals("") && finalText.length() != 0){ + System.out.println("sdfs"); + continue; + }else { + + //对剧情文本做处理,或者说对unknown文本做处理 + finalText.append(plotTextFilt(plotText)); + } + + break; + + + } + + historyInfoPoint.put(queryName, ""); } } + bestMatch.setAnswer(finalText.toString()); return true; @@ -201,8 +234,14 @@ public class GameBotUtil extends BasicBotUtil{ } + /** + * 主要用于游戏存档和读档 + * @param ansAction + * @param solution + * @throws IOException + */ @Override - public void extraOperation(Condition ansCondition, Solution solution) throws IOException { + public void extraOperation(Action ansAction, Solution solution) throws IOException { Boolean flag = true; String userKey = curInfoPoint.get("userKey"); String randKey = curInfoPoint.get("randKey"); @@ -214,11 +253,16 @@ public class GameBotUtil extends BasicBotUtil{ try { helper = new SqlHelper(); - if(ansCondition.featureMap.containsKey("newGame")) { + //未登录用户没有存取档的操作 + if(userKey.equals(randKey)) + return; + + if(ansAction.featureMap.containsKey("newGame")) { System.out.println("newGame"); this.chatCache.setGameStart(true); - }else if (ansCondition.featureMap.containsKey("gameBackup")) { + + }else if (ansAction.featureMap.containsKey("gameBackup")) { System.out.println("gameBackup"); if(! userKey.equals(randKey)) { //两者不同时表示用户已登录,才有权限存档 chatCache = new ChatCache(userKey, randKey, gameEnv, historyInfoPoint); @@ -232,13 +276,13 @@ public class GameBotUtil extends BasicBotUtil{ solution.setNext(""); //可能存在问题,估计要一个空格 } - } else if (ansCondition.featureMap.containsKey("loadLastArchive")) { + } else if (ansAction.featureMap.containsKey("loadLastArchive")) { System.out.println("loadLastArchive"); ArchiveInfo archiveInfo = helper.queryUserLastGameArchive(userKey); loading(archiveInfo, solution); this.chatCache.setGameStart(true); - } else if (ansCondition.featureMap.containsKey("loadArchiveBySite")) { + } else if (ansAction.featureMap.containsKey("loadArchiveBySite")) { System.out.println("loadArchiveBySite"); if (curInfoPoint.get(LOAD_BY_SITE_CONDITION) != null) { site = curInfoPoint.get(LOAD_BY_SITE_CONDITION).split(":")[1]; @@ -251,6 +295,7 @@ public class GameBotUtil extends BasicBotUtil{ } } } catch (SQLException e) { + e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); @@ -284,8 +329,8 @@ public class GameBotUtil extends BasicBotUtil{ System.out.println("----------读档中------------"); site = loadCache.getInfoPoint().get("site"); - String nextStep = loadCache.getInfoPoint().get(String.format(PlotConstructor.TASK_CONDITION, site)); - String reply = loadCache.getInfoPoint().get(String.format(PlotConstructor.TASK_REPLY, site)); + String nextStep = loadCache.getInfoPoint().get(String.format(PlotConstructor2.TASK_CONDITION, site)); + String reply = loadCache.getInfoPoint().get(String.format(PlotConstructor2.TASK_REPLY, site)); solution.setAnswer(reply); solution.setNext("nextStep=" + nextStep); @@ -337,4 +382,289 @@ public class GameBotUtil extends BasicBotUtil{ return reply; } + + + + + + public static Matcher findTalker(String reply){ + Pattern findTalker = Pattern.compile(TALKER); + Matcher m = findTalker.matcher(reply); + + return m; + } + static String findFirstTalker(String reply){ + String npc = ""; + Pattern findTalker = Pattern.compile(TALKER); + Matcher m = findTalker.matcher(reply); + + if(m.find()) { + npc = m.group(1); + } + + return npc; + } + + /** + * 查看回答文本的说话这是否在当前地点 + * 0:没有说话者 + * 1:说话者在当前地点 + * 2:说话者不在当前地点或者不能说话 + * @param reply + * @param curInfoPoint + * @param historyInfoPoint + * @param gameEnv + * @param worldController + * @param site + * @param logWriter + * @return + */ + public 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); + location = worldController.worldOperation(gameEnv, "npc_query", "queryLocationByNPCName:" + npc, curInfoPoint, historyInfoPoint); + if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){ + if(gameEnv.queryNpcAttrByNpcName(npc, "能否说话") == null || gameEnv.queryNpcAttrByNpcName(npc, "能否说话").equals("能")){ + flag = 1; + logWriter.record("\"" + reply + "\":匹配", 1); + }else { + flag = 2; + logWriter.record(npc + "不能说话", 1); + } + + }else { + logWriter.record("\"" + reply + "\":" + npc +"不在" + site + ",跳过",1 ); + flag = 2; + } + }else{ + logWriter.record("\"" + reply + "\":没有npc名",1 ); + flag = 0; + } + return flag; + + } + + + /** + * 查看回答文本的说话这是否在当前地点 + * 0:没有说话者 + * 1:说话者在当前地点 + * 2:说话者不在当前地点或者不能说话 + * @param npc + * @param site + * @param onlineDetect npc是在线类型才可以通过 + * @return + */ + public Boolean canTalk(String npc, String site, Boolean onlineDetect){ + String location; + + Boolean flag = false; + location = gameEnv.queryNpcAttrByNpcName(npc, "location"); + if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){ + if(gameEnv.queryNpcAttrByNpcName(npc, "能否说话") == null || gameEnv.queryNpcAttrByNpcName(npc, "能否说话").equals("能")){ + + + + if(onlineDetect){ + if(isOnlineMode(npc, historyInfoPoint)){ + logWriter.record("\"" + npc + "\":匹配", 1); + flag = true; + } + }else { + flag = true; + } + }else { + logWriter.record(npc + "不能说话", 1); + } + }else { + logWriter.record("\"" + npc + "\":" + npc +"不在" + site + ",跳过",1 ); + } + + return flag; + + } + + + public static String appendTalker(String npc, String text, Map historyInfoPoint, GameEnv gameEnv, WorldController worldController){ + + return String.format(TALKER_PATTERN, npc, PlotConstructor2.ASSISTANT_EMOTION) + text; + + } + + + String plotTextFilt(String reply){ + String textType, returnText = "plot text filt error", plotLastTalker; + String site = historyInfoPoint.get("site"); + + + textType = textTypeDetect(reply, site); + System.out.println("textType:" + textType); + + switch(textType){ + case "direct_return": + returnText = reply; + break; + case "less_talker": + return appendTalker(findRelateTalkers(false).get(0), reply, historyInfoPoint, gameEnv, worldController); + case "to_unknown": + Set candidates = new HashSet(); + Map> npcTextMap = null; + String unknownList = "", foundNPC; + String fieldList[] = {"unknownTextList", "finalUnknownText"}; + String lastReply = historyInfoPoint.get("lastReply"); + + plotLastTalker = findTextLastTalker(lastReply, site); + + for(String unknownField:fieldList){ + candidates.clear(); + + if(userinfo.varInitialMap.get(unknownField) != null) { + unknownList = userinfo.varInitialMap.get(unknownField); + npcTextMap = unknownTextClassify(unknownList); + + if(!plotLastTalker.equals("")) { + candidates.add(plotLastTalker); + } + + //先找剧情相关的npc + foundNPC = foundCandidateText(candidates, npcTextMap); + if(!foundNPC.equals("")){ + returnText = MyFunc.randStr(npcTextMap.get(foundNPC)); + break; + }else{ + //再找地点相关的npc + candidates.addAll(findRelateTalkers(true)); + foundNPC = foundCandidateText(candidates, npcTextMap); + if(!foundNPC.equals("")){ + returnText = MyFunc.randStr(npcTextMap.get(foundNPC)); + break; + } + } + } + + } + + break; + } + + + return returnText; + + } + + public String textTypeDetect(String text, String site){ + int code = 0; + String textType = "to_unknown", npc; + + + Boolean flag = true; + + npc = findFirstTalker(text); + + if(text.equals("")){ + textType = "to_unknown"; + }else if(npc.equals("")) { + textType = "less_talker"; + }else if(canTalk(npc, site, false)){ + textType = "direct_return"; + }else{ + textType = "to_unknown"; + } + + + + + return textType; + } + + + + private static Boolean isOnlineMode(String npc, Map historyInfoPoint){ + return historyInfoPoint.get("onlineModeTalkers").contains("," + npc + ","); + } + + + private String findTextLastTalker(String text, String site){ + Matcher m = findTalker(text); + String npc, lastTalker = ""; + while(m.find()) { + //回答unknown文本的npc必须处于在线模式 + npc = m.group(1); + //处于离线模式 可以说话 相同地点 + if(canTalk(npc, site, true)) { + //找到最后一个说话且处于离线模式的npc + lastTalker = npc; + }else{ + System.out.println(npc + "是离线模式"); + } + } + + return lastTalker; + } + + /** + * 找到用来说话的人 + * includeSiteNPC 是否包含当前地点的npc + */ + private List findRelateTalkers(Boolean includeSiteNPC){ + String site = historyInfoPoint.get("site"); + String lastReply = historyInfoPoint.get("lastReply"); + List talkers = new ArrayList(); + + String plotLastTalker = findTextLastTalker(lastReply, site); + if(!plotLastTalker.equals("")){ + talkers.add(plotLastTalker); + } + + if(includeSiteNPC){ + List npcList = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site")); + for(String npc:npcList){ + if(canTalk(npc, site, true)){ + talkers.add(npc); + } + } + } + + if(talkers.size() == 0){ + talkers.add(historyInfoPoint.get(ASSISTANT)); + } + + return talkers; + } + + + + + //从unknown文本中提取npc名字 + private Map> unknownTextClassify(String unknownText){ + String talker; + Map> npcTextMap = new HashMap>(); + + for(String ans:unknownText.split("~")){ + talker = findFirstTalker(ans); + npcTextMap.putIfAbsent(talker, new ArrayList()); + npcTextMap.get(talker).add(ans); + } + + return npcTextMap; + + } + + private String foundCandidateText(Set candidates, Map> npcTextMap){ + String foundNPC = ""; + for(String npc:candidates) { + //先看剧情中最后说话的人有没有unknown文本,如果有就。。。 + if (npcTextMap.get(npc) != null && npcTextMap.get(npc).size() > 0) { + foundNPC = npc; + break; + } + } + + return foundNPC; + } + } -- libgit2 0.27.1