Commit b76cae13 by hxw

条件中的两条condition相同时要生成两个condition

parent 3c0c6f8a
...@@ -271,6 +271,7 @@ public class SqlHelper { ...@@ -271,6 +271,7 @@ public class SqlHelper {
ps.setString(2, String.valueOf(categoryId)); ps.setString(2, String.valueOf(categoryId));
ps.setString(3, json.toJSONString()); ps.setString(3, json.toJSONString());
ps.setString(4, (String)json.get("configName")); ps.setString(4, (String)json.get("configName"));
ps.addBatch(); ps.addBatch();
} }
...@@ -569,6 +570,31 @@ public class SqlHelper { ...@@ -569,6 +570,31 @@ public class SqlHelper {
} }
} }
public List<ArchiveInfo> queryArchiveByUserKey(String userKey){
String sql = "select * from game_archive where user_key = ? order by update_time desc";
List<ArchiveInfo> archiveList = new ArrayList<ArchiveInfo>();
ArchiveInfo archiveInfo = null;
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, userKey);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
archiveInfo = new ArchiveInfo(rs.getString("archive_id"), rs.getString("user_key"),
rs.getString("site"), rs.getString("update_time"), rs.getString("plot"));
archiveList.add(archiveInfo);
}
ps.close();
rs.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return archiveList;
}
......
...@@ -10,25 +10,25 @@ import java.util.LinkedHashMap; ...@@ -10,25 +10,25 @@ import java.util.LinkedHashMap;
* 独立于引擎的另一种condition * 独立于引擎的另一种condition
*/ */
public class Action { public class Action {
public int priority = -1; private int priority = -1;
public int activePriority = 0; //如果本condition被其他condition激活 //public int activePriority = 0; //如果本condition被其他condition激活
public int auxiliaryPriority = 0; //用于priority一样时人为设置的辅助优先级 private int auxiliaryPriority = 0; //用于priority一样时人为设置的辅助优先级
public HashSet<String> keywordSet = new HashSet<String>(); private HashSet<String> keywordSet = new HashSet<String>();
public HashMap<String, HashSet<String>> historyPremise = new HashMap<String, HashSet<String>>(); private HashMap<String, HashSet<String>> historyPremise = new HashMap<String, HashSet<String>>();
public HashMap<String, HashSet<String>> currentPremise = new HashMap<String, HashSet<String>>(); private HashMap<String, HashSet<String>> currentPremise = new HashMap<String, HashSet<String>>();
public HashMap<String, String> updateKnowledge = new LinkedHashMap<String, String>(); private HashMap<String, String> updateKnowledge = new LinkedHashMap<String, String>();
public String[] answer = {"",}; private String[] answer = {"",};
public String nextStep = ""; private String nextStep = "";
public HashMap<String, String> featureMap = new HashMap<String, String>(); private HashMap<String, String> featureMap = new HashMap<String, String>();
public String indexName = ""; private String indexName = "";
public int id = 0; private int id = 0;
public String configName = ""; private String configName = "";
public String status = "waiting"; private String status = "waiting";
//public ArrayList<String> indexName = new ArrayList<String>(); //public ArrayList<String> indexName = new ArrayList<String>();
public Action(int priority) { public Action(int priority) {
this.priority = priority; this.priority = priority;
this.activePriority = priority; //this.activePriority = priority;
} }
/** /**
...@@ -50,7 +50,8 @@ public class Action { ...@@ -50,7 +50,8 @@ public class Action {
this.id = originAction.id; this.id = originAction.id;
this.configName = originAction.configName; this.configName = originAction.configName;
this.status = originAction.status; this.status = originAction.status;
this.activePriority = originAction.activePriority + basePriority + 1; //激活会多一个优先级 //this.activePriority = originAction.activePriority + basePriority + 1; //激活会多一个优先级
this.priority = originAction.priority + basePriority + 1;
//如果激活originAction的action,它的辅助优先级高于originAction,那么。。 //如果激活originAction的action,它的辅助优先级高于originAction,那么。。
...@@ -63,4 +64,107 @@ public class Action { ...@@ -63,4 +64,107 @@ public class Action {
public Action() { public Action() {
} }
public int getPriority() {
return priority;
}
public int getAuxiliaryPriority() {
return auxiliaryPriority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public void setAuxiliaryPriority(int auxiliaryPriority) {
this.auxiliaryPriority = auxiliaryPriority;
}
public HashSet<String> getKeywordSet() {
return keywordSet;
}
public HashMap<String, HashSet<String>> getHistoryPremise() {
return historyPremise;
}
public HashMap<String, HashSet<String>> getCurrentPremise() {
return currentPremise;
}
public HashMap<String, String> getUpdateKnowledge() {
return updateKnowledge;
}
public String[] getAnswer() {
return answer;
}
public String getNextStep() {
return nextStep;
}
public HashMap<String, String> getFeatureMap() {
return featureMap;
}
public String getIndexName() {
return indexName;
}
public int getId() {
return id;
}
public String getConfigName() {
return configName;
}
public String getStatus() {
return status;
}
public void setKeywordSet(HashSet<String> keywordSet) {
this.keywordSet = keywordSet;
}
public void setHistoryPremise(HashMap<String, HashSet<String>> historyPremise) {
this.historyPremise = historyPremise;
}
public void setCurrentPremise(HashMap<String, HashSet<String>> currentPremise) {
this.currentPremise = currentPremise;
}
public void setUpdateKnowledge(HashMap<String, String> updateKnowledge) {
this.updateKnowledge = updateKnowledge;
}
public void setAnswer(String[] answer) {
this.answer = answer;
}
public void setNextStep(String nextStep) {
this.nextStep = nextStep;
}
public void setFeatureMap(HashMap<String, String> featureMap) {
this.featureMap = featureMap;
}
public void setIndexName(String indexName) {
this.indexName = indexName;
}
public void setId(int id) {
this.id = id;
}
public void setConfigName(String configName) {
this.configName = configName;
}
public void setStatus(String status) {
this.status = status;
}
} }
...@@ -11,6 +11,7 @@ import java.util.Map; ...@@ -11,6 +11,7 @@ import java.util.Map;
public class ChatCache implements DisposableBean { public class ChatCache implements DisposableBean {
public String ENV_ERROR = "游戏平台初始化失败";
// private String chatKey = "不知道"; // private String chatKey = "不知道";
private String userKey = ""; private String userKey = "";
private String randKey = ""; private String randKey = "";
...@@ -18,7 +19,8 @@ public class ChatCache implements DisposableBean { ...@@ -18,7 +19,8 @@ public class ChatCache implements DisposableBean {
private Map<String, String> infoPoint = null; private Map<String, String> infoPoint = null;
private GameEnv gameEnv = null; private GameEnv gameEnv = null;
private boolean gameStart = false; private Boolean gameStart = false;
private Boolean reload = false;
public String getBotAccount() { public String getBotAccount() {
...@@ -62,6 +64,14 @@ public class ChatCache implements DisposableBean { ...@@ -62,6 +64,14 @@ public class ChatCache implements DisposableBean {
this.gameStart = gameStart; this.gameStart = gameStart;
} }
public Boolean getReload() {
return reload;
}
public void setReload(Boolean reload) {
this.reload = reload;
}
public GameEnv getGameEnv() { public GameEnv getGameEnv() {
return gameEnv; return gameEnv;
} }
...@@ -86,7 +96,9 @@ public class ChatCache implements DisposableBean { ...@@ -86,7 +96,9 @@ public class ChatCache implements DisposableBean {
try { try {
gameEnv = new GameEnv(userInfo.botAccount); gameEnv = new GameEnv(userInfo.botAccount);
} catch (Exception e) { } catch (Exception e) {
System.out.println("游戏平台初始化失败"); System.out.println(ENV_ERROR);
infoPoint.put("error_message", ENV_ERROR);
e.printStackTrace(); e.printStackTrace();
} }
...@@ -104,5 +116,8 @@ public class ChatCache implements DisposableBean { ...@@ -104,5 +116,8 @@ public class ChatCache implements DisposableBean {
} }
public ChatCache(String userKey, String randKey) {
this.userKey = userKey;
this.randKey = randKey;
}
} }
...@@ -10,7 +10,17 @@ import java.util.Map; ...@@ -10,7 +10,17 @@ import java.util.Map;
public class ConfigTerm implements Cloneable{ public class ConfigTerm implements Cloneable{
static int iterNum = 0; ThreadLocal<Integer> iterNum=new ThreadLocal<Integer>() {
protected Integer initialValue() {
return 0;
}
};
ThreadLocal<Map<String, Integer>> conditionCount = new ThreadLocal<Map<String, Integer>>(){
protected Map<String, Integer> initialValue(){
return new HashMap<String, Integer>();
};
};
private int id = 0; private int id = 0;
private String jCurPremise = ""; private String jCurPremise = "";
...@@ -65,8 +75,11 @@ public class ConfigTerm implements Cloneable{ ...@@ -65,8 +75,11 @@ public class ConfigTerm implements Cloneable{
public void setConfigName(String configName, Boolean append) { public void setConfigName(String configName, Boolean append) {
if(append) { if(append) {
iterNum++;
this.configName = configName + "_" + iterNum; iterNum.set(iterNum.get() + 1);
//iterNum++;
this.configName = configName + "_" + iterNum.get();
}else{ }else{
this.configName = configName; this.configName = configName;
} }
...@@ -218,7 +231,7 @@ public class ConfigTerm implements Cloneable{ ...@@ -218,7 +231,7 @@ public class ConfigTerm implements Cloneable{
} }
public ConfigTerm(List<String> curPremise, List<String> hisPremise, Map<String, String> updateKnowledge, String extraCP, String extraHP, String extraUK, String feature, String reply, String nextStep, String auxiliaryPriority) { public ConfigTerm(List<Premise> curPremise, List<Premise> hisPremise, Map<String, String> updateKnowledge, String extraCP, String extraHP, String extraUK, String feature, String reply, String nextStep, String auxiliaryPriority) {
this.curPremise = appendPremiseStr(curPremise, extraCP); this.curPremise = appendPremiseStr(curPremise, extraCP);
this.hisPremise = appendPremiseStr(hisPremise, extraHP); this.hisPremise = appendPremiseStr(hisPremise, extraHP);
this.updateKnowledge = appendKnowledgeStr(updateKnowledge, extraUK); this.updateKnowledge = appendKnowledgeStr(updateKnowledge, extraUK);
...@@ -228,21 +241,46 @@ public class ConfigTerm implements Cloneable{ ...@@ -228,21 +241,46 @@ public class ConfigTerm implements Cloneable{
this.auxiliaryPriority = auxiliaryPriority; this.auxiliaryPriority = auxiliaryPriority;
} }
public String appendPremiseStr(List<String> premises, String extraPM) { public String appendPremiseStr(List<Premise> premises, String extraPremise) {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
String premiseStr = ""; String premiseStr = "", conditionName;
Map<String ,Integer> nameCount = new HashMap<String , Integer>();
for (Premise premise : premises){
//设置初始值
//System.out.println("nameCount" + nameCount);
conditionName = premise.getConditionName();
nameCount.putIfAbsent(conditionName, 0);
for (String premise : premises) //nameCount加一
sb.append("," + premise); nameCount.put(conditionName, nameCount.get(conditionName) + 1);
//在conditionName后添加count
if(nameCount.get(conditionName) > 1) {
premise.setConditionName(conditionName + nameCount.get(conditionName));
}
sb.append(",");
sb.append(premise.getConditionName());
sb.append("::");
sb.append(premise.getCmpType());
sb.append("-");
sb.append(premise.getOperator());
sb.append("=");
sb.append(premise.getKeyword());
}
if (sb.length() > 0) if (sb.length() > 0)
sb.deleteCharAt(0); //删除第一个逗号 sb.deleteCharAt(0); //删除第一个逗号
if (!extraPM.equals("")) { if (!extraPremise.equals("")) {
if (sb.length() == 0) if (sb.length() == 0)
sb.append(extraPM); sb.append(extraPremise);
else else
sb.append("," + extraPM); sb.append("," + extraPremise);
} else if (sb.length() == 0) { } else if (sb.length() == 0) {
sb.append(" "); sb.append(" ");
} }
...@@ -255,7 +293,7 @@ public class ConfigTerm implements Cloneable{ ...@@ -255,7 +293,7 @@ public class ConfigTerm implements Cloneable{
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
String varName = "", varValue = "", knowledgeStr; String varName = "", varValue = "", knowledgeStr;
Iterator<String> iit = knowledge.keySet().iterator(); Iterator<String> iit = knowledge.keySet().iterator();
Boolean delayUpdateFollowerLocation = false; Boolean delayUpdateFollowerLocation = false; //updateFollowerLocation:更新跟随玩家的NPC的位置,delayUpdateFollowerLocation将更新跟随玩家的角色放在更新答案的最后
String delayUpdateFollowerLocationValue = "", delayUpdateFollowerLocationKey = ""; String delayUpdateFollowerLocationValue = "", delayUpdateFollowerLocationKey = "";
while (iit.hasNext()) { while (iit.hasNext()) {
...@@ -436,18 +474,23 @@ public class ConfigTerm implements Cloneable{ ...@@ -436,18 +474,23 @@ public class ConfigTerm implements Cloneable{
} }
public String toString() { public String toString() {
StringBuffer sb = new StringBuffer();
String text = curPremise + "|" + sb.append(curPremise).append("|");
hisPremise + "|" + sb.append(hisPremise);
feature + "," + updateKnowledge + "," + nextStepStatus + "|" + sb.append("|").append(feature).append(",");
"auxiliaryPriority=" + auxiliaryPriority + "|" + sb.append(updateKnowledge).append(",");
"configName=" + configName + "|=>|" + sb.append(nextStepStatus).append( "|");
reply + "|" + sb.append("auxiliaryPriority=");
"nextStep=" + nextStep + "|" + sb.append(auxiliaryPriority).append("|").append("configName=");
"status=" + status + "|" + sb.append(configName);
"configId="; sb.append("|=>|").append(reply);
sb.append("|").append("nextStep=");
sb.append(nextStep).append("|");
sb.append("status=").append(status);
sb.append("|").append("configId=");
return text; return sb.toString();
} }
public Object clone() { public Object clone() {
...@@ -467,11 +510,6 @@ public class ConfigTerm implements Cloneable{ ...@@ -467,11 +510,6 @@ public class ConfigTerm implements Cloneable{
ConfigTerm configTerm2 = (ConfigTerm) configTerm.clone(); 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("")) if(configTerm2.getUpdateKnowledge().equals(""))
configTerm2.setUpdateKnowledge("process-nextStep:var={临时变量condition-2}"); configTerm2.setUpdateKnowledge("process-nextStep:var={临时变量condition-2}");
...@@ -479,14 +517,12 @@ public class ConfigTerm implements Cloneable{ ...@@ -479,14 +517,12 @@ public class ConfigTerm implements Cloneable{
configTerm2.setUpdateKnowledge(configTerm2.getUpdateKnowledge() + "-<-process-nextStep:var={临时变量condition-2}"); configTerm2.setUpdateKnowledge(configTerm2.getUpdateKnowledge() + "-<-process-nextStep:var={临时变量condition-2}");
configTerm2.setConfigName(name, true); configTerm2.setConfigName(name, true);
//configTermList.add(configTerm);
configTermList.add(configTerm2); configTermList.add(configTerm2);
} }
public static ConfigTerm simpleCopy(ConfigTerm configTerm){ public ConfigTerm simpleCopy(ConfigTerm configTerm){
ConfigTerm configTerm2 = (ConfigTerm) configTerm.clone(); ConfigTerm configTerm2 = (ConfigTerm) configTerm.clone();
......
package com.qiwu.chatbotbackend.entity;
public class Premise {
private String conditionName = "";
private String cmpType = "";
private String operator = "";
private String keyword = "";
public Premise(String conditionName, String cmpType, String operator, String keyword) {
this.conditionName = conditionName;
this.cmpType = cmpType;
this.operator = operator;
this.keyword = keyword;
}
public String getConditionName() {
return conditionName;
}
public void setConditionName(String conditionName) {
this.conditionName = conditionName;
}
public String getCmpType() {
return cmpType;
}
public void setCmpType(String cmpType) {
this.cmpType = cmpType;
}
public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator;
}
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
}
package com.qiwu.chatbotbackend.gameDesign; package com.qiwu.chatbotbackend.gameDesign;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
...@@ -42,6 +40,7 @@ public class GlobalVariableConstructor extends ElementConstructor { ...@@ -42,6 +40,7 @@ public class GlobalVariableConstructor extends ElementConstructor {
varInitialMap.put("botType", "game"); varInitialMap.put("botType", "game");
varInitialMap.put("unknownTextList", (String)gameElements.get("unknownTextList")); varInitialMap.put("unknownTextList", (String)gameElements.get("unknownTextList"));
varInitialMap.put("finalUnknownText", (String)gameElements.get("finalUnknownText")); varInitialMap.put("finalUnknownText", (String)gameElements.get("finalUnknownText"));
varInitialMap.put("CC_URL", keywordMap.get("CC_URL").toString());
JSONObject script = gameElements.getJSONObject("speechcraft"); JSONObject script = gameElements.getJSONObject("speechcraft");
......
...@@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSONArray; ...@@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.ConfigTerm; import com.qiwu.chatbotbackend.entity.ConfigTerm;
import com.qiwu.chatbotbackend.entity.Premise;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import java.util.*; import java.util.*;
...@@ -34,10 +35,14 @@ public class ListeningConstructor extends ElementConstructor{ ...@@ -34,10 +35,14 @@ public class ListeningConstructor extends ElementConstructor{
String feature, nextPlotId, reply = "", nextCondition = "", nextLocation = "", priority; String feature, nextPlotId, reply = "", nextCondition = "", nextLocation = "", priority;
String nTaskLineName, lastTaskCondition, lastTaskReply, nextGameStep; String nTaskLineName, lastTaskCondition, lastTaskReply, nextGameStep;
Boolean autoJump = false; Boolean autoJump = false;
List<String> curPremiseList = new ArrayList<String>(); List<Premise> curPremiseList = new ArrayList<Premise>();
List<String> hisPremiseList = new ArrayList<String>(); List<Premise> hisPremiseList = new ArrayList<Premise>();
JSONArray listeningActions = gameELments.getJSONArray("listeningActions"); JSONArray listeningActions = gameELments.getJSONArray("listeningActions");
JSONObject plotNode = null; JSONObject plotNode = null;
if(listeningActions == null)
return;
size = listeningActions.size(); size = listeningActions.size();
JSONObject config = null; JSONObject config = null;
...@@ -47,8 +52,8 @@ public class ListeningConstructor extends ElementConstructor{ ...@@ -47,8 +52,8 @@ public class ListeningConstructor extends ElementConstructor{
priority = "2"; priority = "2";
feature = "match"; feature = "match";
config = listeningActions.getJSONObject(i); config = listeningActions.getJSONObject(i);
curPremiseList = JSONArray.parseArray(config.getJSONArray("curPremise").toJSONString(), String.class); curPremiseList = JSONArray.parseArray(config.getJSONArray("curPremise").toJSONString(), Premise.class);
hisPremiseList = JSONArray.parseArray(config.getJSONArray("hisPremise").toJSONString(), String.class); hisPremiseList = JSONArray.parseArray(config.getJSONArray("hisPremise").toJSONString(), Premise.class);
Map<String, String> updateKnowledge = JSONObject.parseObject(config.getJSONObject("updateKnowledge").toJSONString(), Map.class); Map<String, String> updateKnowledge = JSONObject.parseObject(config.getJSONObject("updateKnowledge").toJSONString(), Map.class);
nextPlotId = config.getString("nextPlotId"); nextPlotId = config.getString("nextPlotId");
...@@ -71,7 +76,7 @@ public class ListeningConstructor extends ElementConstructor{ ...@@ -71,7 +76,7 @@ public class ListeningConstructor extends ElementConstructor{
if(autoJump){ if(autoJump){
feature = "match,activate:after"; feature = "match,activate:after";
updateKnowledge.put("plot_jump_text", "str+" + reply); updateKnowledge.put("plot_jump_text", "str+" + reply);
nextCondition = "plot_" + nextPlotId + "_*"; nextCondition = "plot_" + nextPlotId;
reply = ""; reply = "";
}else{ }else{
feature = "match"; feature = "match";
......
...@@ -384,6 +384,16 @@ public class MapConstructor extends ElementConstructor { ...@@ -384,6 +384,16 @@ public class MapConstructor extends ElementConstructor {
configTerm.setjStatus(1); configTerm.setjStatus(1);
configTermList.add(configTerm); configTermList.add(configTerm);
//上一个配置文件激活时的默认选项, 地点任务线未开启,则不更新game_step
configTerm = new ConfigTerm(
lastTaskCondition + "::match-Include=null", " ", "", "{" + lastTaskReply + "-2}", " ", "process-nextStep:var={" + lastTaskCondition + "-2}-<-site:" + placeA
+ "-<-npc_update:updateFollowerLocation:" + placeA
);
configTerm.setStatus("sleeping");
configTerm.setConfigName("plot_" + placeA + "_doudi2", false);
configTerm.setjStatus(1);
configTermList.add(configTerm);
} }
...@@ -418,6 +428,21 @@ public class MapConstructor extends ElementConstructor { ...@@ -418,6 +428,21 @@ public class MapConstructor extends ElementConstructor {
configTerm.setConfigName("map", true); configTerm.setConfigName("map", true);
configTermList.add(configTerm); configTermList.add(configTerm);
/**
* 要去的地方不可到达
*/
configTerm = new ConfigTerm(
conditionName + "::match-Include=" + toAllSiteskeywords
+ ",isNeighbour:" + conditionName + "::match-Include=5",
" ",
"match,return-0",
"",
" ",
"map_query:queryPathNotExist:"
);
configTerm.setConfigName("map", true);
configTermList.add(configTerm);
} }
......
...@@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSONArray; ...@@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.ConfigTerm; import com.qiwu.chatbotbackend.entity.ConfigTerm;
import com.qiwu.chatbotbackend.entity.Premise;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import java.io.*; import java.io.*;
...@@ -57,7 +58,6 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -57,7 +58,6 @@ public class PlotConstructor2 extends ElementConstructor {
this.plots = plots; this.plots = plots;
constructAdjList(plots); constructAdjList(plots);
...@@ -87,11 +87,6 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -87,11 +87,6 @@ public class PlotConstructor2 extends ElementConstructor {
message = "开始剧情不存在,请到剧情列表设置"; message = "开始剧情不存在,请到剧情列表设置";
return; return;
} }
} catch(Exception e){ } catch(Exception e){
operationStatus = 0; operationStatus = 0;
message = "剧情接口处理出现异常"; message = "剧情接口处理出现异常";
...@@ -100,7 +95,11 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -100,7 +95,11 @@ public class PlotConstructor2 extends ElementConstructor {
} }
} }
//根据id构造邻接表
/**
* 根据id构造邻接表
* @param plots
*/
public void constructAdjList(JSONArray plots) { public void constructAdjList(JSONArray plots) {
int length = plots.size(), branchSize; int length = plots.size(), branchSize;
String id = "", nextPlotId = "", nextPlotText; String id = "", nextPlotId = "", nextPlotText;
...@@ -143,10 +142,19 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -143,10 +142,19 @@ public class PlotConstructor2 extends ElementConstructor {
} }
} }
/**
* 将条件文本中的一些特殊字符过滤调
* @param premiseList 条件列表
* @return
*/
JSONArray premiseTextFilt(JSONArray premiseList){ JSONArray premiseTextFilt(JSONArray premiseList){
JSONObject premise = null;
int size = premiseList.size(); int size = premiseList.size();
for(int i = 0;i < size;i++){ for(int i = 0;i < size;i++){
premiseList.set(i, premiseList.getString(i).replace("\r\n", "").replace("\n", "").replace("\r", "")); premise = premiseList.getJSONObject(i);
premise.put("keyword", premise.getString("keyword").replace("\r\n", "").replace("\n", "").replace("\r", ""));
premiseList.set(i, premise);
} }
return premiseList; return premiseList;
...@@ -158,8 +166,7 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -158,8 +166,7 @@ public class PlotConstructor2 extends ElementConstructor {
*/ */
public static void varSlotFilt(JSONObject plot, Map<String, StringBuffer> keywordMap){ public static void varSlotFilt(JSONObject plot, Map<String, StringBuffer> keywordMap){
String VARIABLE_SEARCH_PATTERN = "【(.*?)@(.*?)(\\$\\{.*?})", npcName, middleText = "", varSlot = ""; //不加 】,直接替换npcName到变量槽的文本
String VARIABLE_SEARCH_PATTERN = "【(.*?)@(.*?)(\\$\\{.*?})", npcName, middleText = "", varSlot = "";
System.out.println(plot.getString("id")); System.out.println(plot.getString("id"));
Pattern replacePattern = Pattern.compile(VARIABLE_SEARCH_PATTERN); Pattern replacePattern = Pattern.compile(VARIABLE_SEARCH_PATTERN);
Matcher m = replacePattern.matcher(plot.getString("plotText")); Matcher m = replacePattern.matcher(plot.getString("plotText"));
...@@ -197,7 +204,7 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -197,7 +204,7 @@ public class PlotConstructor2 extends ElementConstructor {
int branchSize; int branchSize;
List<String> curPremiseList, historyPremiseList; List<Premise> curPremiseList, historyPremiseList;
root.put("nextUnknownText", varInitialMap.get("unknownText")); root.put("nextUnknownText", varInitialMap.get("unknownText"));
root.put("parentId", "null"); root.put("parentId", "null");
...@@ -232,6 +239,7 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -232,6 +239,7 @@ public class PlotConstructor2 extends ElementConstructor {
Queue<JSONObject> queue = new LinkedList<JSONObject>(); Queue<JSONObject> queue = new LinkedList<JSONObject>();
queue.add(root); queue.add(root);
System.out.println(root.toJSONString());
while (!queue.isEmpty()) { while (!queue.isEmpty()) {
node = queue.remove(); node = queue.remove();
...@@ -454,9 +462,10 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -454,9 +462,10 @@ public class PlotConstructor2 extends ElementConstructor {
} }
} }
//System.out.println(branchNode);
curPremiseList = JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class); curPremiseList = JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), Premise.class);
historyPremiseList = JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class); historyPremiseList = JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), Premise.class);
...@@ -472,7 +481,7 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -472,7 +481,7 @@ public class PlotConstructor2 extends ElementConstructor {
if(doActivatePlot(nextAutoJump, location, nextLocation, moveWithPlot) ){ if(doActivatePlot(nextAutoJump, location, nextLocation, moveWithPlot) ){
appendFeature(extraFT, "activate:after"); appendFeature(extraFT, "activate:after");
nextCondition = "plot_" + nextId + "_*"; nextCondition = "plot_" + nextId;
} }
configTerm = new ConfigTerm( configTerm = new ConfigTerm(
...@@ -482,7 +491,7 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -482,7 +491,7 @@ public class PlotConstructor2 extends ElementConstructor {
"", extraHP.toString(), extraUK.toString(), "", extraHP.toString(), extraUK.toString(),
extraFT.toString(), reply, nextCondition, "1" extraFT.toString(), reply, nextCondition, "1"
); );
configTerm.setConfigName("plot_" + id, true); configTerm.setConfigName("plot_" + id, false);
//当剧情没有条件限制时的操作 ,额外要求上一步剧情不是自动跳转,因为自动跳转的标识放在了上一部剧情的分支里,所以是上上个分支是否存在自动跳转 //当剧情没有条件限制时的操作 ,额外要求上一步剧情不是自动跳转,因为自动跳转的标识放在了上一部剧情的分支里,所以是上上个分支是否存在自动跳转
...@@ -693,11 +702,11 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -693,11 +702,11 @@ public class PlotConstructor2 extends ElementConstructor {
jsonStr = jsonStr.replace("plotStartText", gameElements.getString("plotStartText")); jsonStr = jsonStr.replace("plotStartText", gameElements.getString("plotStartText"));
jsonStr = jsonStr.replace("startId", gameElements.getString("start")); jsonStr = jsonStr.replace("startId", gameElements.getString("start"));
jsonStr = jsonStr.replace("site_list", keywordMap.get("site_list").toString()); jsonStr = jsonStr.replace("site_list", keywordMap.get("site_list").toString());
//System.out.println("JSONSTR ------------------------------\n" + jsonStr);
JSONObject config = JSONObject.parseObject(jsonStr); JSONObject config = JSONObject.parseObject(jsonStr);
//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")); gameElements.getJSONArray("plots").addAll(config.getJSONArray("gameStart"));
gameElements.put("start", "start1"); gameElements.put("start", "start1");
gameElements.put("firstUnknownText", "请说开始游戏或者继续游戏"); gameElements.put("firstUnknownText", "请说开始游戏或者继续游戏");
...@@ -816,67 +825,33 @@ public class PlotConstructor2 extends ElementConstructor { ...@@ -816,67 +825,33 @@ public class PlotConstructor2 extends ElementConstructor {
/** /**
* 当前剧情和下一步剧情不在同一个地点,需要到达地点后才能激活剧情的情况
*/
void arriveActivatePlot(Map<String, String> 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模块的一个剧情处理 * 当前剧情和下一步剧情不在同一个地点,需要到达地点后才能激活剧情的情况,将这块处理当做listening模块的一个剧情处理
*/ */
void arriveActivatePlot2(JSONObject gameElements, String plotId, String nextId, String nextLocation){ void arriveActivatePlot2(JSONObject gameElements, String plotId, String nextId, String nextLocation){
String feature; //String feature;
//如果下一步剧情和当前剧情的地点是不一样的,那么在玩家没有到达下一个地点是剧情还是停留在当前剧情,只有到达目的地后,下一步剧情才会发生变化 //如果下一步剧情和当前剧情的地点是不一样的,那么在玩家没有到达下一个地点是剧情还是停留在当前剧情,只有到达目的地后,下一步剧情才会发生变化
StringBuffer hisPremise = new StringBuffer(); //StringBuffer hisPremise = new StringBuffer();
StringBuffer curPremise = new StringBuffer(); //StringBuffer curPremise = new StringBuffer();
appendPremise(curPremise, "yaobuyao", "match", "Include", nextLocation); // appendPremise(curPremise, "yaobuyao", "match", "Include", nextLocation);
appendPremise(hisPremise, nextLocation + "_activate_by", "match", "Include", plotId); // appendPremise(hisPremise, nextLocation + "_activate_by", "match", "Include", plotId);
appendPremise(hisPremise, nextLocation + "_activate_ready", "match", "Include", "1"); // appendPremise(hisPremise, nextLocation + "_activate_ready", "match", "Include", "1");
appendPremise(hisPremise, "isNeighbour:yaobuyao", "match", "Include", "1+3+4"); // appendPremise(hisPremise, "isNeighbour:yaobuyao", "match", "Include", "1+3+4");
JSONObject updateKnowledge = new JSONObject(); JSONObject updateKnowledge = new JSONObject();
JSONArray curPremiseList = new JSONArray(); JSONArray curPremiseList = new JSONArray();
curPremiseList.add(curPremise.toString()); //curPremiseList.add(curPremise.toString());
JSONArray hisPremiseList = new JSONArray(); JSONArray hisPremiseList = new JSONArray();
hisPremiseList.add(hisPremise.toString()); //hisPremiseList.add(hisPremise.toString());
curPremiseList.add(new Premise("yaobuyao", "match", "Include", nextLocation));
hisPremiseList.add(new Premise(nextLocation + "_activate_by", "match", "Include", plotId));
hisPremiseList.add(new Premise(nextLocation + "_activate_ready", "match", "Include", "1"));
hisPremiseList.add(new Premise("isNeighbour:yaobuyao", "match", "Include", "1+3+4"));
......
...@@ -91,14 +91,17 @@ public class ActionMatcher { ...@@ -91,14 +91,17 @@ public class ActionMatcher {
activateFlag = false; activateFlag = false;
satisfyFlag = false; satisfyFlag = false;
replaceFlag = false; replaceFlag = false;
if (action.status.equals("waiting")){ if (action.getStatus().equals("waiting")){
logWriter.record("-----------------------------------检索到配置条目", 0);
logWriter.record(userinfo.id2config.get(action.getId()), 1);
//是否有激活操作,如果有激活操作且没有提交表单则判断是否满足条件,如果有激活有提交表单,则放在整个操作完成(getSolution)之后再激活 //是否有激活操作,如果有激活操作且没有提交表单则判断是否满足条件,如果有激活有提交表单,则放在整个操作完成(getSolution)之后再激活
if (action.featureMap.get("activate") != null && !action.featureMap.containsKey("post")) { if (action.getFeatureMap().get("activate") != null && !action.getFeatureMap().containsKey("post")) {
activateFlag = true; activateFlag = true;
} }
if((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.priority > bestMatch.priority)){ if(higherPriority(action, bestMatch)){
replaceFlag = true; replaceFlag = true;
} }
...@@ -106,7 +109,7 @@ public class ActionMatcher { ...@@ -106,7 +109,7 @@ public class ActionMatcher {
//没有激活,优先级不够高,直接跳过 //没有激活,优先级不够高,直接跳过
if(!activateFlag && !replaceFlag){ if(!activateFlag && !replaceFlag){
logWriter.record("-----------------------------------优先级不足其没有激活,跳过", 0); logWriter.record("-----------------------------------优先级不足,跳过", 0);
continue; continue;
} }
...@@ -117,11 +120,11 @@ public class ActionMatcher { ...@@ -117,11 +120,11 @@ public class ActionMatcher {
if(satisfyFlag){ if(satisfyFlag){
if(activateFlag){ if(activateFlag){
activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.priority, action.auxiliaryPriority, action.nextStep, context); activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.getPriority(), action.getAuxiliaryPriority(), action.getNextStep(), context);
} }
if(replaceFlag){ if(replaceFlag){
bestMatch = action; bestMatch = action;
logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.id) + "\"", 2); logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.getId()) + "\"", 2);
logWriter.writeln(); logWriter.writeln();
} }
} }
...@@ -211,16 +214,20 @@ public class ActionMatcher { ...@@ -211,16 +214,20 @@ public class ActionMatcher {
parentFlag = false; parentFlag = false;
action = activatedQueue.remove(); action = activatedQueue.remove();
activatedMap.remove(action.id); activatedMap.remove(action.getId());
logWriter.record("-----------------------------------检索到配置条目", 0);
logWriter.record(userinfo.id2config.get(action.getId()), 1);
if((action.auxiliaryPriority > bestMatch.auxiliaryPriority) || (action.auxiliaryPriority == bestMatch.auxiliaryPriority && action.activePriority > bestMatch.activePriority)) if(higherPriority(action, bestMatch))
replaceFlag = true; replaceFlag = true;
if(action.featureMap.get("activate") != null && !action.featureMap.containsKey("post")) if(action.getFeatureMap().get("activate") != null && !action.getFeatureMap().containsKey("post"))
activateFlag = true; activateFlag = true;
if(bestMatch.nextStep.contains(String.valueOf(action.id))) if(bestMatch.getNextStep().contains(String.valueOf(action.getId())))
//现在的condition是被bestMatch这个condition激活的 //现在的condition是被bestMatch这个condition激活的
parentFlag = true; parentFlag = true;
...@@ -228,17 +235,17 @@ public class ActionMatcher { ...@@ -228,17 +235,17 @@ public class ActionMatcher {
//没有激活功能, 优先级不够, condition不是被bestMatch激活,直接跳过 //没有激活功能, 优先级不够, condition不是被bestMatch激活,直接跳过
if(!activateFlag && !replaceFlag && !parentFlag) { if(!activateFlag && !replaceFlag && !parentFlag) {
logWriter.record("-----------------------------------优先级不足,跳过", 0); logWriter.record("-----------------------------------优先级不足,跳过", 0);
logWriter.record(userinfo.id2config.get(action.id), 1); logWriter.record(userinfo.id2config.get(action.getId()), 1);
continue; continue;
} }
if(conditionSatisfy(action)){ if(conditionSatisfy(action)){
if(activateFlag) { if(activateFlag) {
activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.priority, action.auxiliaryPriority, action.nextStep, context); activateCondition(activatedQueue, curInfoPoint.get("bot_name"), action.getPriority(), action.getAuxiliaryPriority(), action.getNextStep(), context);
} }
if(replaceFlag){ if(replaceFlag){
bestMatch = action; bestMatch = action;
logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.id) + "\"", 2); logWriter.record("匹配更新为:\"" + userinfo.id2config.get(action.getId()) + "\"", 2);
logWriter.writeln(); logWriter.writeln();
} }
} }
...@@ -291,11 +298,10 @@ public class ActionMatcher { ...@@ -291,11 +298,10 @@ public class ActionMatcher {
String actionName, keywords, keyword, comparePair[], cmpType, premiseStr; String actionName, keywords, keyword, comparePair[], cmpType, premiseStr;
HashSet<String> keywordSet = null; HashSet<String> keywordSet = null;
logWriter.record("-----------------------------------检索到配置条目", 0);
logWriter.record(userinfo.id2config.get(action.id), 1);
if (action.featureMap.containsKey("match")) {
Iterator<String> it = action.currentPremise.keySet().iterator(); if (action.getFeatureMap().containsKey("match")) {
Iterator<String> it = action.getCurrentPremise().keySet().iterator();
while (flag && it.hasNext()) { while (flag && it.hasNext()) {
premiseStr = it.next(); premiseStr = it.next();
comparePair = premiseStr.split("::"); comparePair = premiseStr.split("::");
...@@ -311,7 +317,7 @@ public class ActionMatcher { ...@@ -311,7 +317,7 @@ public class ActionMatcher {
break; break;
} }
keywordSet = action.currentPremise.get(premiseStr); keywordSet = action.getCurrentPremise().get(premiseStr);
if (!premiseSatisfy(keyword, cmpType, keywordSet)) if (!premiseSatisfy(keyword, cmpType, keywordSet))
flag = false; flag = false;
...@@ -320,18 +326,19 @@ public class ActionMatcher { ...@@ -320,18 +326,19 @@ public class ActionMatcher {
} }
} }
it = action.historyPremise.keySet().iterator(); it = action.getHistoryPremise().keySet().iterator();
while (flag && it.hasNext()) { while (flag && it.hasNext()) {
premiseStr = it.next(); premiseStr = it.next();
comparePair = premiseStr.split("::"); comparePair = premiseStr.split("::");
cmpType = comparePair[1]; cmpType = comparePair[1];
actionName = comparePair[0]; actionName = comparePair[0];
//如果featureMap中包含includeCurInfo,则已知信息中包含啦当前对话中识别的所有信息 //如果featureMap中包含includeCurInfo,则已知信息中包含啦当前对话中识别的所有信息
keyword = botUtil.getKeyword(historyInfoPoint, curInfoPoint, action.featureMap.containsKey("includeCurInfo"), actionName); keyword = botUtil.getKeyword(historyInfoPoint, curInfoPoint, action.getFeatureMap().containsKey("includeCurInfo"), actionName);
if (keyword == null) { if (keyword == null) {
flag = false; flag = false;
if(flag == false){ if(flag == false){
logWriter.record("name:" + actionName + ", value:'" + keyword + "'", 5);
logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln();
} }
break; break;
...@@ -339,11 +346,12 @@ public class ActionMatcher { ...@@ -339,11 +346,12 @@ public class ActionMatcher {
keywordSet = action.historyPremise.get(premiseStr); keywordSet = action.getHistoryPremise().get(premiseStr);
if (!premiseSatisfy(keyword, cmpType, keywordSet)) if (!premiseSatisfy(keyword, cmpType, keywordSet))
flag = false; flag = false;
if(flag == false){ if(flag == false){
logWriter.record("name:" + actionName + ", value:'" + keyword + "'", 5);
logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln(); logWriter.record("-----------------------" + premiseStr + "不匹配,跳过------------------------", 5);logWriter.writeln();
} }
} }
...@@ -464,11 +472,11 @@ public class ActionMatcher { ...@@ -464,11 +472,11 @@ public class ActionMatcher {
} }
} }
candidateA = MyFunc.transferToMillisecond(keyword); candidateA = SimpleUtil.transferToMillisecond(keyword);
for (String k : keywordSet) { for (String k : keywordSet) {
if (!k.equals("")) { if (!k.equals("")) {
candidateB = MyFunc.transferToMillisecond(k); candidateB = SimpleUtil.transferToMillisecond(k);
break; break;
} }
} }
...@@ -539,8 +547,8 @@ public class ActionMatcher { ...@@ -539,8 +547,8 @@ public class ActionMatcher {
} else if(keyword1.contains("年") && keyword1.contains("月") && keyword1.contains("日") } else if(keyword1.contains("年") && keyword1.contains("月") && keyword1.contains("日")
&& keyword2.contains("年") && keyword2.contains("月") && keyword2.contains("日")){ && keyword2.contains("年") && keyword2.contains("月") && keyword2.contains("日")){
long candidateA = MyFunc.transferToMillisecond(keyword1); long candidateA = SimpleUtil.transferToMillisecond(keyword1);
long candidateB = MyFunc.transferToMillisecond(keyword2); long candidateB = SimpleUtil.transferToMillisecond(keyword2);
if (operator.equals("Bigger")) if (operator.equals("Bigger"))
flag = candidateA > candidateB; flag = candidateA > candidateB;
...@@ -579,8 +587,8 @@ public class ActionMatcher { ...@@ -579,8 +587,8 @@ public class ActionMatcher {
} else if(keyword.contains("年") && keyword.contains("月") && keyword.contains("日") } else if(keyword.contains("年") && keyword.contains("月") && keyword.contains("日")
&& conditionValue2.contains("年") && conditionValue2.contains("月") && conditionValue2.contains("日")){ && conditionValue2.contains("年") && conditionValue2.contains("月") && conditionValue2.contains("日")){
long candidateA = MyFunc.transferToMillisecond(keyword); long candidateA = SimpleUtil.transferToMillisecond(keyword);
long candidateB = MyFunc.transferToMillisecond(conditionValue2); long candidateB = SimpleUtil.transferToMillisecond(conditionValue2);
if (operator.equals("Bigger")) if (operator.equals("Bigger"))
flag = candidateA > candidateB; flag = candidateA > candidateB;
...@@ -611,14 +619,21 @@ public class ActionMatcher { ...@@ -611,14 +619,21 @@ public class ActionMatcher {
} }
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
System.out.println("配置文件格式有误"); System.out.println("配置文件格式有误");
logWriter.record(e.getCause() + "\n条件比较时,keyword:" + keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString(), 0);
System.out.println(e.getCause() + "\n条件比较时,variableName:" +keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString());
flag = false; flag = false;
e.printStackTrace(); e.printStackTrace();
} catch (ParseException e) { } catch (ParseException e) {
System.out.println("时间解析错误"); System.out.println("时间解析错误");
historyInfoPoint.put("error_message", "解析出错:" + keyword);
System.out.println(e.getCause() + "\n条件比较时,variableName:" +keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString());
e.printStackTrace(); e.printStackTrace();
flag = false; flag = false;
} catch (Exception e) { } catch (Exception e) {
System.out.println("操作符有误"); System.out.println("操作符有误");
logWriter.record(e.getCause() + "\n条件比较时,keyword:" + keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString(), 0);
System.out.println(e.getCause() + "\n条件比较时,variableName:" +keyword + ", cmpType:" + cmpType + ", keywordSet:" + keywordSet.toString());
e.printStackTrace(); e.printStackTrace();
flag = false; flag = false;
} }
...@@ -644,7 +659,7 @@ public class ActionMatcher { ...@@ -644,7 +659,7 @@ public class ActionMatcher {
//System.out.println(ans.getAnswer()); //System.out.println(ans.getAnswer());
//post关键字 //post关键字
if (ansAction.featureMap.containsKey("post")) { if (ansAction.getFeatureMap().containsKey("post")) {
logWriter.record("---------------------进入表单结束",1); logWriter.record("---------------------进入表单结束",1);
ans = postToServer(ans, ansAction); ans = postToServer(ans, ansAction);
logWriter.record("---------------------提交表单结束",1); logWriter.record("---------------------提交表单结束",1);
...@@ -655,7 +670,7 @@ public class ActionMatcher { ...@@ -655,7 +670,7 @@ public class ActionMatcher {
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
//updateKnowledge关键字 //updateKnowledge关键字
if (ansAction.featureMap.containsKey("updateKnowledge")) { if (ansAction.getFeatureMap().containsKey("updateKnowledge")) {
logWriter.record("---------------------进入更新答案【略】",1); logWriter.record("---------------------进入更新答案【略】",1);
updateKnowledge(ansAction); updateKnowledge(ansAction);
logWriter.record("---------------------更新答案结束",1); logWriter.record("---------------------更新答案结束",1);
...@@ -665,12 +680,12 @@ public class ActionMatcher { ...@@ -665,12 +680,12 @@ public class ActionMatcher {
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
if (ansAction.featureMap.containsKey("newNext")) { if (ansAction.getFeatureMap().containsKey("newNext")) {
logWriter.record("---------------------进入判断下一步【略】",1); logWriter.record("---------------------进入判断下一步【略】",1);
ans = findNewNext(ans, ansAction); ans = findNewNext(ans, ansAction);
logWriter.record("---------------------判断下一步结束",1); logWriter.record("---------------------判断下一步结束",1);
//上一步 //上一步
} else if (ansAction.featureMap.containsKey("return-1")) { } else if (ansAction.getFeatureMap().containsKey("return-1")) {
String activeList[] = historyInfoPoint.get("activeList").split("\\|"); String activeList[] = historyInfoPoint.get("activeList").split("\\|");
if (activeList.length == 1) if (activeList.length == 1)
ans.setNext("nextStep=" + activeList[activeList.length - 1]); ans.setNext("nextStep=" + activeList[activeList.length - 1]);
...@@ -678,14 +693,14 @@ public class ActionMatcher { ...@@ -678,14 +693,14 @@ public class ActionMatcher {
ans.setNext("nextStep=" + activeList[activeList.length - 2]); ans.setNext("nextStep=" + activeList[activeList.length - 2]);
} }
//停留 //停留
} else if (ansAction.featureMap.containsKey("return-0")) { } else if (ansAction.getFeatureMap().containsKey("return-0")) {
String activeList[] = historyInfoPoint.get("activeList").split("\\|"); String activeList[] = historyInfoPoint.get("activeList").split("\\|");
if(activeList.length > 0) if(activeList.length > 0)
ans.setNext("nextStep=" + activeList[activeList.length - 1]); ans.setNext("nextStep=" + activeList[activeList.length - 1]);
else else
ans.setNext("nextStep= "); ans.setNext("nextStep= ");
//激活 //激活
} else if (ansAction.featureMap.containsKey("activate") || ansAction.featureMap.containsKey("activate:after")) { } else if (ansAction.getFeatureMap().containsKey("activate") || ansAction.getFeatureMap().containsKey("activate:after")) {
String activeList[] = historyInfoPoint.get("activeList").split("\\|"); String activeList[] = historyInfoPoint.get("activeList").split("\\|");
if (activeList.length == 1) if (activeList.length == 1)
ans.setNext("nextStep=" + activeList[activeList.length - 1]); ans.setNext("nextStep=" + activeList[activeList.length - 1]);
...@@ -700,9 +715,8 @@ public class ActionMatcher { ...@@ -700,9 +715,8 @@ public class ActionMatcher {
try { try {
reply = MyFunc.randStr(ansAction.answer); reply = SimpleUtil.randStr(ansAction.getAnswer());
reply = botUtil.varSlotReplace(reply); reply = botUtil.varSlotReplace(reply);
//reply = ResponseFilter.filt(curInfoPoint,historyInfoPoint,gameEnv,worldController, reply, userinfo, ansAction, logWriter);
ans.setAnswer(reply); ans.setAnswer(reply);
...@@ -714,7 +728,7 @@ public class ActionMatcher { ...@@ -714,7 +728,7 @@ public class ActionMatcher {
if (ans.getNext().equals("")) { if (ans.getNext().equals("")) {
ans.setNext("nextStep=" + ansAction.nextStep); ans.setNext("nextStep=" + ansAction.getNextStep());
} }
} catch (Exception e) { } catch (Exception e) {
...@@ -752,11 +766,6 @@ public class ActionMatcher { ...@@ -752,11 +766,6 @@ public class ActionMatcher {
} }
}; };
// if (debugFlag)
// lastReply = ans.getAnswer().split(")")[2];
// else
// lastReply = ans.getAnswer();
// historyInfoPoint.put("lastReply", lastReply);
try { try {
String keyword1, keyword2; String keyword1, keyword2;
...@@ -781,9 +790,6 @@ public class ActionMatcher { ...@@ -781,9 +790,6 @@ public class ActionMatcher {
//context.setAttribute("chat_key+"+userinfo.botAccount,historyInfoPoint);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
...@@ -871,7 +877,7 @@ public class ActionMatcher { ...@@ -871,7 +877,7 @@ public class ActionMatcher {
} }
}; };
elem = ansAction.featureMap.get("post").split("\\|"); elem = ansAction.getFeatureMap().get("post").split("\\|");
url = elem[0]; url = elem[0];
postType = elem[1]; postType = elem[1];
...@@ -889,7 +895,7 @@ public class ActionMatcher { ...@@ -889,7 +895,7 @@ public class ActionMatcher {
} }
public Solution findNewNext(Solution ans, Action ansAction) { public Solution findNewNext(Solution ans, Action ansAction) {
String nextOptions[] = ansAction.nextStep.split(","); String nextOptions[] = ansAction.getNextStep().split(",");
String conditionName, premises[], cpPair[]; String conditionName, premises[], cpPair[];
boolean flag = true; boolean flag = true;
...@@ -940,13 +946,13 @@ public class ActionMatcher { ...@@ -940,13 +946,13 @@ public class ActionMatcher {
Iterator<String> iit = action.updateKnowledge.keySet().iterator(); Iterator<String> iit = action.getUpdateKnowledge().keySet().iterator();
while (iit.hasNext()) { while (iit.hasNext()) {
variableName = iit.next(); variableName = iit.next();
keyword = botUtil.getKeyword(historyInfoPoint, curInfoPoint, false, variableName); keyword = botUtil.getKeyword(historyInfoPoint, curInfoPoint, false, variableName);
updateValue = botUtil.knowledgeProcess(variableName, action.updateKnowledge.get(variableName)); updateValue = botUtil.knowledgeProcess(variableName, action.getUpdateKnowledge().get(variableName));
try { try {
...@@ -955,9 +961,9 @@ public class ActionMatcher { ...@@ -955,9 +961,9 @@ public class ActionMatcher {
if (keyword == null || keyword.equals("")) if (keyword == null || keyword.equals(""))
keyword = "0"; keyword = "0";
if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) {
long time = MyFunc.transferToMillisecond(keyword); long time = SimpleUtil.transferToMillisecond(keyword);
int offset = Integer.parseInt(updateValue.substring(1)); int offset = Integer.parseInt(updateValue.substring(1));
updateValue = MyFunc.transferToStandardTime(time + (1000 * offset)); updateValue = SimpleUtil.transferToStandardTime(time + (1000 * offset));
} else if (StringUtils.isNumeric(keyword)) { } else if (StringUtils.isNumeric(keyword)) {
int number = Integer.parseInt(keyword); int number = Integer.parseInt(keyword);
int offset = Integer.parseInt(updateValue.substring(1)); int offset = Integer.parseInt(updateValue.substring(1));
...@@ -968,9 +974,9 @@ public class ActionMatcher { ...@@ -968,9 +974,9 @@ public class ActionMatcher {
if (keyword == null || keyword.equals("")) if (keyword == null || keyword.equals(""))
keyword = "0"; keyword = "0";
if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) {
long time = MyFunc.transferToMillisecond(keyword); long time = SimpleUtil.transferToMillisecond(keyword);
int offset = Integer.parseInt(updateValue.substring(1)); int offset = Integer.parseInt(updateValue.substring(1));
updateValue = MyFunc.transferToStandardTime(time - (1000 * offset)); updateValue = SimpleUtil.transferToStandardTime(time - (1000 * offset));
} else if (StringUtils.isNumeric(keyword)) { } else if (StringUtils.isNumeric(keyword)) {
int number = Integer.parseInt(keyword); int number = Integer.parseInt(keyword);
int offset = Integer.parseInt(updateValue.substring(1)); int offset = Integer.parseInt(updateValue.substring(1));
...@@ -991,9 +997,9 @@ public class ActionMatcher { ...@@ -991,9 +997,9 @@ public class ActionMatcher {
if (keyword == null || keyword.equals("")) if (keyword == null || keyword.equals(""))
keyword = "0"; keyword = "0";
if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) {
long time = MyFunc.transferToMillisecond(keyword); long time = SimpleUtil.transferToMillisecond(keyword);
int offset = Integer.parseInt(updateValue.substring(1)); int offset = Integer.parseInt(updateValue.substring(1));
updateValue = MyFunc.transferToStandardTime(time + (1000 * offset)); updateValue = SimpleUtil.transferToStandardTime(time + (1000 * offset));
} else if (StringUtils.isNumeric(keyword)) { } else if (StringUtils.isNumeric(keyword)) {
int number = Integer.parseInt(keyword); int number = Integer.parseInt(keyword);
int offset = Integer.parseInt(updateValue.substring(5)); int offset = Integer.parseInt(updateValue.substring(5));
...@@ -1004,9 +1010,9 @@ public class ActionMatcher { ...@@ -1004,9 +1010,9 @@ public class ActionMatcher {
if (keyword == null || keyword.equals("")) if (keyword == null || keyword.equals(""))
keyword = "0"; keyword = "0";
if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) { if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) {
long time = MyFunc.transferToMillisecond(keyword); long time = SimpleUtil.transferToMillisecond(keyword);
int offset = Integer.parseInt(updateValue.substring(5)); int offset = Integer.parseInt(updateValue.substring(5));
updateValue = MyFunc.transferToStandardTime(time - (1000 * offset)); updateValue = SimpleUtil.transferToStandardTime(time - (1000 * offset));
} else if (StringUtils.isNumeric(keyword)) { } else if (StringUtils.isNumeric(keyword)) {
int number = Integer.parseInt(keyword); int number = Integer.parseInt(keyword);
int offset = Integer.parseInt(updateValue.substring(1)); int offset = Integer.parseInt(updateValue.substring(1));
...@@ -1042,14 +1048,14 @@ public class ActionMatcher { ...@@ -1042,14 +1048,14 @@ public class ActionMatcher {
//提取配置条目的下一步 //提取配置条目的下一步
} else if (updateValue.endsWith("nextStep-3}")) { } else if (updateValue.endsWith("nextStep-3}")) {
updateValue = action.nextStep; updateValue = action.getNextStep();
//提取配置条目的回答 //提取配置条目的回答
} else if (updateValue.endsWith("reply-3}")) { } else if (updateValue.endsWith("reply-3}")) {
updateValue = MyFunc.randStr(action.answer); updateValue = SimpleUtil.randStr(action.getAnswer());
} }
//如果变量名叫做process-nextStep,那么下一个激活的condition就是updateValue //如果变量名叫做process-nextStep,那么下一个激活的condition就是updateValue
if (variableName.startsWith("process-nextStep")) { if (variableName.startsWith("process-nextStep")) {
action.nextStep = updateValue; action.setNextStep(updateValue);
updateValue = ""; updateValue = "";
} }
...@@ -1057,7 +1063,9 @@ public class ActionMatcher { ...@@ -1057,7 +1063,9 @@ public class ActionMatcher {
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); logWriter.record(e.getCause() + "\n更新答案时,variableName:" + variableName + ", keyword:" + keyword + ", updateValue:" + updateValue, 0);
System.out.println(e.getCause() + "\n更新答案时,variableName:" + variableName + ", keyword:" + keyword + ", updateValue:" + updateValue);
//e.printStackTrace();
continue; continue;
} }
...@@ -1117,7 +1125,7 @@ public class ActionMatcher { ...@@ -1117,7 +1125,7 @@ public class ActionMatcher {
originAction = action; originAction = action;
try { try {
configId = originAction.id; configId = originAction.getId();
newAction = new Action(originAction, basePriority, baseAuxiliaryPriority); newAction = new Action(originAction, basePriority, baseAuxiliaryPriority);
//action = ActionMatcher.buildCondition(action, configStr); //action = ActionMatcher.buildCondition(action, configStr);
...@@ -1126,17 +1134,19 @@ public class ActionMatcher { ...@@ -1126,17 +1134,19 @@ public class ActionMatcher {
//如果这条配置文件已经被其他配置文件激活了,处于activatedMap,那么就需要比较优先级是否更高,如果更高则优先级做替换,配置文件的内容不变 //如果这条配置文件已经被其他配置文件激活了,处于activatedMap,那么就需要比较优先级是否更高,如果更高则优先级做替换,配置文件的内容不变
if (activatedMap.containsKey(configId)) { if (activatedMap.containsKey(configId)) {
if(newAction.auxiliaryPriority > activatedMap.get(configId).auxiliaryPriority) if(higherPriority(newAction, activatedMap.get(configId)))
activatedMap.get(configId).auxiliaryPriority = newAction.auxiliaryPriority; activatedMap.put(configId, newAction);
if(newAction.activePriority > activatedMap.get(configId).activePriority) // if(newAction.getAuxiliaryPriority() > activatedMap.get(configId).getAuxiliaryPriority())
activatedMap.get(configId).activePriority = newAction.activePriority; // activatedMap.get(configId).auxiliaryPriority = newAction.auxiliaryPriority;
// if(newAction.priority > activatedMap.get(configId).priority)
// activatedMap.get(configId).priority = newAction.priority;
} else if (!activatedMap.containsKey(configId)) { } else if (!activatedMap.containsKey(configId)) {
activatedMap.put(configId, newAction); activatedMap.put(configId, newAction);
activatedQueue.add(newAction); activatedQueue.add(newAction);
} }
}catch (Exception e) { }catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
logWriter.record("----------激活失败:" + action.configName, 5); logWriter.record("----------激活失败:" + action.getConfigName(), 5);
} }
} }
...@@ -1164,9 +1174,9 @@ public class ActionMatcher { ...@@ -1164,9 +1174,9 @@ public class ActionMatcher {
while ((newAction1.featureMap.containsKey("activate") && newAction1.featureMap.containsKey("post")) || newAction1.featureMap.containsKey("activate:after")) { while ((newAction1.getFeatureMap().containsKey("activate") && newAction1.getFeatureMap().containsKey("post")) || newAction1.getFeatureMap().containsKey("activate:after")) {
//如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段 //如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段
activateCondition(activatedQueue, userinfo.botAccount, newAction1.priority, newAction1.auxiliaryPriority, newAction1.nextStep, context); activateCondition(activatedQueue, userinfo.botAccount, newAction1.getPriority(), newAction1.getAuxiliaryPriority(), newAction1.getNextStep(), context);
newAction2 = activatedQueueMatching(newAction1, activatedQueue, context); newAction2 = activatedQueueMatching(newAction1, activatedQueue, context);
...@@ -1185,5 +1195,9 @@ public class ActionMatcher { ...@@ -1185,5 +1195,9 @@ public class ActionMatcher {
} }
public Boolean higherPriority(Action action1, Action action2){
return ((action1.getAuxiliaryPriority() > action2.getAuxiliaryPriority()) || (action1.getAuxiliaryPriority() == action2.getAuxiliaryPriority() && action1.getPriority() > action2.getPriority()));
}
} }
...@@ -7,6 +7,7 @@ import com.qiwu.chatbotbackend.db.SqlHelper; ...@@ -7,6 +7,7 @@ import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.ArchiveInfo; import com.qiwu.chatbotbackend.entity.ArchiveInfo;
import com.qiwu.chatbotbackend.entity.ChatCache; import com.qiwu.chatbotbackend.entity.ChatCache;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import com.qiwu.chatbotbackend.task.utils.FileFinder;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import java.io.*; import java.io.*;
...@@ -76,7 +77,8 @@ public class ChatCacheController { ...@@ -76,7 +77,8 @@ public class ChatCacheController {
} catch (Exception e) { } catch (Exception e) {
//可整合 //可整合
e.printStackTrace(); e.printStackTrace();
chatCache = new ChatCache(userinfo, userKey, randKey);
//chatCache = new ChatCache(userinfo, userKey, randKey);
chatCacheMap.put(userKey, chatCache); chatCacheMap.put(userKey, chatCache);
} }
...@@ -92,6 +94,10 @@ public class ChatCacheController { ...@@ -92,6 +94,10 @@ public class ChatCacheController {
String nowTime = now .format(format), userId, botAccount, keyElem[]; String nowTime = now .format(format), userId, botAccount, keyElem[];
Boolean opFlag, destroy = false; Boolean opFlag, destroy = false;
if(!chatCache.isGameStart() || chatCache.getUserKey().equals(chatCache.getRandKey()))
return true;
System.out.println("游戏存档中"); System.out.println("游戏存档中");
String userKey = chatCache.getUserKey(); String userKey = chatCache.getUserKey();
...@@ -249,21 +255,29 @@ public class ChatCacheController { ...@@ -249,21 +255,29 @@ public class ChatCacheController {
SqlHelper helper; SqlHelper helper;
Map<String, String> infoPoints = new HashMap<String, String>(); Map<String, String> infoPoints = new HashMap<String, String>();
try { try {
helper = new SqlHelper();
if (context.getAttribute("chatCache") != null) {
if (context.getAttribute("chatCache") == null) { chatCacheMap = (HashMap<String, ChatCache>)context.getAttribute("chatCache");
chatCacheMap = new HashMap<String, ChatCache>();
if (chatCacheMap.containsKey(userKey)) { if (chatCacheMap.containsKey(userKey)) {
chatCache = chatCacheMap.get(userKey); chatCache = chatCacheMap.get(userKey);
findFlag = !(chatCache.getUserKey().endsWith(chatCache.getRandKey())); //userKey和randKey不同表示存在用户id,如果相同则没有登录只是试玩
// //保存到本地,并从chatCacheMap中删除
if(!chatCache.getUserKey().endsWith(chatCache.getRandKey()) && chatCache.isGameStart()){
findFlag = true;
saveChatCache(chatCache, helper);
chatCacheMap.remove(userKey);
}
} }
} }
System.out.println("findFlag" + findFlag);
if (!findFlag) { if (!findFlag) {
helper = new SqlHelper();
archiveInfo = helper.queryUserLastGameArchive(userKey); archiveInfo = helper.queryUserLastGameArchive(userKey);
helper.destroy(); helper.destroy();
...@@ -280,4 +294,13 @@ public class ChatCacheController { ...@@ -280,4 +294,13 @@ public class ChatCacheController {
} }
public static Boolean deleteChatCache(SqlHelper helper, String botAccount){
Boolean sqlDeleteFlag = helper.deleteArchiveByBotAccount(botAccount);
Boolean fileDeleteFlag = FileFinder.deleteGameArchive(CHAT_CACHE_DIR, botAccount);
return sqlDeleteFlag && fileDeleteFlag;
}
} }
...@@ -86,7 +86,7 @@ public class FormsPoster { ...@@ -86,7 +86,7 @@ public class FormsPoster {
logWriter.record("提交表单的数据:<br>" + pairList.toString(), 2); logWriter.record("提交表单的数据:<br>" + pairList.toString(), 2);
JSONObject jobj = MyFunc.postFORM(URL, pairList); JSONObject jobj = SimpleUtil.postFORM(URL, pairList);
logWriter.record("提交表单接收到的数据:<br>" + jobj.toJSONString(), 2); logWriter.record("提交表单接收到的数据:<br>" + jobj.toJSONString(), 2);
if((Integer)jobj.get("post_status") == 1){ if((Integer)jobj.get("post_status") == 1){
Iterator<String> kit = jobj.keySet().iterator(); Iterator<String> kit = jobj.keySet().iterator();
...@@ -133,14 +133,14 @@ public class FormsPoster { ...@@ -133,14 +133,14 @@ public class FormsPoster {
pairList.add(new BasicNameValuePair("chat_key", curInfoPoint.get("chat_key"))); pairList.add(new BasicNameValuePair("chat_key", curInfoPoint.get("chat_key")));
pairList.add(new BasicNameValuePair("action_name", curInfoPoint.get("action_name"))); pairList.add(new BasicNameValuePair("action_name", curInfoPoint.get("action_name")));
pairList.add(new BasicNameValuePair("bot_name", curInfoPoint.get("bot_name"))); pairList.add(new BasicNameValuePair("bot_name", curInfoPoint.get("bot_name")));
k_iter = ansAction.currentPremise.keySet().iterator(); k_iter = ansAction.getCurrentPremise().keySet().iterator();
while (k_iter.hasNext()) { while (k_iter.hasNext()) {
key = k_iter.next().split("::")[0]; key = k_iter.next().split("::")[0];
if (curInfoPoint.get(key) != null && !curInfoPoint.equals("")) if (curInfoPoint.get(key) != null && !curInfoPoint.equals(""))
pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key))); pairList.add(new BasicNameValuePair(key, curInfoPoint.get(key)));
} }
k_iter = ansAction.historyPremise.keySet().iterator(); k_iter = ansAction.getHistoryPremise().keySet().iterator();
while (k_iter.hasNext()) { while (k_iter.hasNext()) {
key = k_iter.next().split("::")[0]; key = k_iter.next().split("::")[0];
if(!historyInfoPoint.get(key).equals("")) { if(!historyInfoPoint.get(key).equals("")) {
...@@ -154,7 +154,7 @@ public class FormsPoster { ...@@ -154,7 +154,7 @@ public class FormsPoster {
logWriter.record("提交表单的数据:<br>" + pairList.toString(), 2); logWriter.record("提交表单的数据:<br>" + pairList.toString(), 2);
JSONObject jobj = MyFunc.postFORM(URL, pairList); JSONObject jobj = SimpleUtil.postFORM(URL, pairList);
logWriter.record("提交表单接收到的数据:<br>" + jobj.toJSONString(), 2); logWriter.record("提交表单接收到的数据:<br>" + jobj.toJSONString(), 2);
if((Integer)jobj.get("post_status") == 1){ if((Integer)jobj.get("post_status") == 1){
Iterator<String> kit = jobj.keySet().iterator(); Iterator<String> kit = jobj.keySet().iterator();
...@@ -202,9 +202,15 @@ public class FormsPoster { ...@@ -202,9 +202,15 @@ public class FormsPoster {
pairList.add(new BasicNameValuePair("query_text", curInfoPoint.get("query_text"))); pairList.add(new BasicNameValuePair("query_text", curInfoPoint.get("query_text")));
pairList.add(new BasicNameValuePair("qa_threshold", threshold)); pairList.add(new BasicNameValuePair("qa_threshold", threshold));
//设置初始值
historyInfoPoint.put("common_answer", "");
historyInfoPoint.put("qa_score", "0");
historyInfoPoint.put("qa_status", "OK");
logWriter.record("提交表单的数据:<br>" + pairList.toString(), 2); logWriter.record("提交表单的数据:<br>" + pairList.toString(), 2);
JSONObject jobj = MyFunc.postFORM(URL, pairList); JSONObject jobj = SimpleUtil.postFORM(URL, pairList);
logWriter.record("提交表单接收到的数据:<br>" + jobj.toJSONString(), 2); logWriter.record("提交表单接收到的数据:<br>" + jobj.toJSONString(), 2);
...@@ -212,10 +218,7 @@ public class FormsPoster { ...@@ -212,10 +218,7 @@ public class FormsPoster {
System.out.println(jobj.toJSONString()); System.out.println(jobj.toJSONString());
if((Integer)jobj.get("post_status") == 1){ if((Integer)jobj.get("post_status") == 1){
if(jobj.getJSONArray("qa_candidates") != null && jobj.get("qa_status").equals("OK")){ if(jobj.getJSONArray("qa_candidates") != null && jobj.get("qa_status").equals("OK")){
//设置初始值
historyInfoPoint.put("common_answer", "");
historyInfoPoint.put("qa_score", "0");
historyInfoPoint.put("qa_status", "OK");
List<JSONArray> candidates = JSON.toJavaObject(jobj.getJSONArray("qa_candidates"), List.class); List<JSONArray> candidates = JSON.toJavaObject(jobj.getJSONArray("qa_candidates"), List.class);
for(JSONArray pair:candidates){ for(JSONArray pair:candidates){
...@@ -230,31 +233,24 @@ public class FormsPoster { ...@@ -230,31 +233,24 @@ public class FormsPoster {
if (m.find()) { if (m.find()) {
npc = m.group(1); npc = m.group(1);
if ((GameBotUtil.sameLocation((String)textscore.get(0), curInfoPoint, historyInfoPoint, gameEnv, worldController, historyInfoPoint.get("site"), logWriter) == 1)) { if ((GameBotUtil.sameLocation((String)textscore.get(0), curInfoPoint, historyInfoPoint, gameEnv, historyInfoPoint.get("site"), logWriter) == 1)) {
historyInfoPoint.put("common_answer", (String)textscore.get(0)); historyInfoPoint.put("common_answer", (String)textscore.get(0));
historyInfoPoint.put("qa_score", String.valueOf(textscore.get(1))); historyInfoPoint.put("qa_score", String.valueOf(textscore.get(1)));
break; break;
} }
} }
} }
} }
}else{
historyInfoPoint.put("common_answer", (String)jobj.get("common_answer"));
historyInfoPoint.put("qa_score", "0");
historyInfoPoint.put("qa_status", (String)jobj.get("qa_status"));
} }
}else { }else {
ans.setAnswer("提交表单出现异常"); historyInfoPoint.put("error_message", jobj.getString("error_message"));
} }
} }
public void postGameQA(Map<String ,String> curInfoPoint, Map<String ,String> historyInfoPoint, Solution ans,GameEnv gameEnv, WorldController worldController, String URL, UserInfo userInfo) throws UnsupportedEncodingException { public void postGameQA(Map<String ,String> curInfoPoint, Map<String ,String> historyInfoPoint, Solution ans,GameEnv gameEnv, WorldController worldController, String URL, UserInfo userInfo) throws UnsupportedEncodingException {
postGameQA1(historyInfoPoint.get("game_step"), curInfoPoint, historyInfoPoint,ans, gameEnv, worldController, URL, userInfo); postGameQA1(historyInfoPoint.get("game_step"), curInfoPoint, historyInfoPoint,ans, gameEnv, worldController, URL, userInfo);
if(historyInfoPoint.get("common_answer").equals("") || historyInfoPoint.get("common_answer").equals("no answer")){ if(historyInfoPoint.get("common_answer") != null && (historyInfoPoint.get("common_answer").equals("") || historyInfoPoint.get("common_answer").equals("no answer"))){
postGameQA1(curInfoPoint.get("bot_name"), curInfoPoint, historyInfoPoint, ans, gameEnv, worldController, URL, userInfo); postGameQA1(curInfoPoint.get("bot_name"), curInfoPoint, historyInfoPoint, ans, gameEnv, worldController, URL, userInfo);
} }
......
...@@ -27,7 +27,7 @@ ...@@ -27,7 +27,7 @@
// String site = historyInfoPoint.get("site"); // String site = historyInfoPoint.get("site");
// //
// //
// reply = MyFunc.randStr(reply.split("~")); // reply = SimpleUtil.randStr(reply.split("~"));
// //
// if(reply.endsWith("请说开始剧情或者继续剧情")){ //不需要添加人名和情绪 // if(reply.endsWith("请说开始剧情或者继续剧情")){ //不需要添加人名和情绪
// return reply; // return reply;
...@@ -75,7 +75,7 @@ ...@@ -75,7 +75,7 @@
// } // }
// } // }
// if (unknownList.size() > 0) { // if (unknownList.size() > 0) {
// return MyFunc.randStr(unknownList); // return SimpleUtil.randStr(unknownList);
// } // }
// //
// } // }
...@@ -97,7 +97,7 @@ ...@@ -97,7 +97,7 @@
// } // }
// } // }
// if(finalUnknownList.size() > 0){ // if(finalUnknownList.size() > 0){
// return MyFunc.randStr(finalUnknownList); // return SimpleUtil.randStr(finalUnknownList);
// //
// } // }
// } // }
...@@ -181,7 +181,7 @@ ...@@ -181,7 +181,7 @@
// } // }
// } // }
// if(filtedNpcList.size() != 0) // if(filtedNpcList.size() != 0)
// npc = MyFunc.randStr(filtedNpcList); // npc = SimpleUtil.randStr(filtedNpcList);
// else // else
// npc = historyInfoPoint.get(PlotConstructor.ASSISTANT); // npc = historyInfoPoint.get(PlotConstructor.ASSISTANT);
// //
......
package com.qiwu.chatbotbackend.processing;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.entity.Solution;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class SimpleUtil {
/**
* 将后台返回的数据转成json格式
*/
public static String toJson(Solution ans) {
JSONObject jobj = new JSONObject();
jobj.put("solution", ans.getAnswer());
jobj.put("status", ans.getStatus());
jobj.put("process", ans.getNext());
return jobj.toString();
}
public static String toJson(String returnStr) {
JSONObject jobj = new JSONObject();
jobj.put("returnString", returnStr);
return jobj.toString();
}
/**
* 当请求中的数据是json格式时,该函数用于提取request中的json数据
*
* @param request
* @return json字符串
*/
public static String readJSONString(HttpServletRequest request) {
StringBuffer json = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) {
json.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return json.toString();
}
/**
* 通过get方法传递参数时需要对参数的编码进行转换
*/
public static String convert2Utf8(String s) {
if (s == null) return null;
try {
s = new String(s.getBytes("iso-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
public static long transferToMillisecond(String keyword) throws ParseException {
long time;
System.out.println(keyword);
String timeSeries[] = {"时", "分", "秒"};
for (String f : timeSeries) {
if (!keyword.contains(f))
keyword += "0" + f;
}
SimpleDateFormat format = new SimpleDateFormat("yyyy年M月d日H时m分s秒");
time = format.parse(keyword).getTime();
return time;
}
public static String transferToStandardTime(long time) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy年M月d日H时m分s秒");
Date date = new Date(time);
return format.format(date);
}
public static boolean isInteger(String str){
return true;
}
public static JSONObject postJSON(String url, JSON data, String auth) throws UnsupportedEncodingException {
JSONObject jobj = new JSONObject();
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault();
String respContent = null;
String keyName = null;
StringEntity entity = new StringEntity(data.toJSONString(), "utf-8");
entity.setContentType("application/json; charset=utf-8");
httpPost.setEntity(entity);
if(auth != null){
httpPost.setHeader("Authorization", auth);
}
try {
HttpResponse resp = client.execute(httpPost);
if (resp.getStatusLine().getStatusCode() == 200) {
HttpEntity he = resp.getEntity();
respContent = EntityUtils.toString(he, "UTF-8");
jobj = JSONObject.parseObject(respContent);
jobj.put("post_status", 1);
} else {
jobj.put("post_status", 0);
jobj.put("parameter", "接收请求的程序出现异常:" + resp.getStatusLine().getReasonPhrase());
}
} catch (Exception e) {
e.printStackTrace();
}
return jobj;
}
public static JSONObject postFORM(String url, List<BasicNameValuePair> pairList) throws UnsupportedEncodingException {
HttpPost httpPost = new HttpPost(url);
CloseableHttpClient client = HttpClients.createDefault();
String respContent = null;
String keyName = null;
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "utf-8");
entity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(entity);
JSONObject jobj = new JSONObject();
try {
System.out.println("url为:" + url);
HttpResponse resp = client.execute(httpPost);
if (resp.getStatusLine().getStatusCode() == 200) {
HttpEntity he = resp.getEntity();
respContent = EntityUtils.toString(he, "UTF-8");
jobj = JSONObject.parseObject(respContent);
jobj.put("post_status", 1);
} else {
jobj.put("post_status", 0);
jobj.put("error_message", "目标程序处理失败:" + url + ", 错误码:" + resp.getStatusLine().getStatusCode());
}
} catch (Exception e) {
jobj.put("error_message", "提交表单时出错:" + e.getMessage());
jobj.put("post_status", 0);
}
return jobj;
}
public static String randStr(String strList[]){
String reply;
int randNum = (int) (Math.random() * strList.length);
reply = strList[randNum];
return reply;
}
public static String randStr(List<String> strList){
String reply;
int randNum = (int) (Math.random() * strList.size());
reply = strList.get(randNum);
return reply;
}
}
\ No newline at end of file
...@@ -103,25 +103,25 @@ public class UserInfoController { ...@@ -103,25 +103,25 @@ public class UserInfoController {
history_premises = premises[1].split(","); history_premises = premises[1].split(",");
if (premises.length < 4) if (premises.length < 4)
action.auxiliaryPriority = 0; action.setAuxiliaryPriority(0);
else else
action.auxiliaryPriority = Integer.parseInt(premises[3].split("=", 2)[1]); action.setAuxiliaryPriority(Integer.parseInt(premises[3].split("=", 2)[1]));
if(premises.length < 5) if(premises.length < 5)
action.configName = ""; action.setConfigName("");
else else
action.configName = premises[4].split("=", 2)[1]; action.setConfigName(premises[4].split("=", 2)[1]);
next = element[1].split("\\|"); next = element[1].split("\\|");
if (next.length < 4) if (next.length < 4)
return action; return action;
action.answer = next[0].split("~"); action.setAnswer(next[0].split("~"));
//action.nextStep = next[1]; //action.nextStep = next[1];
//第二处 //第二处
action.nextStep = next[1].split("=", 2)[1]; action.setNextStep(next[1].split("=", 2)[1]);
action.id = Integer.parseInt(next[3].split("=")[1]); action.setId(Integer.parseInt(next[3].split("=")[1]));
action.status = next[2].split("=")[1]; action.setStatus(next[2].split("=")[1]);
//featureMap的构建 //featureMap的构建
...@@ -132,31 +132,31 @@ public class UserInfoController { ...@@ -132,31 +132,31 @@ public class UserInfoController {
} else if (feat.startsWith("updateKnowledge")) { } else if (feat.startsWith("updateKnowledge")) {
String[] knowledge = feat.split("-<-"); String[] knowledge = feat.split("-<-");
int length = knowledge.length; int length = knowledge.length;
action.featureMap.put("updateKnowledge", ""); action.getFeatureMap().put("updateKnowledge", "");
for (int i = 1; i < length; i++) { for (int i = 1; i < length; i++) {
if (knowledge[i].equals("") || knowledge[i].equals(" ")) if (knowledge[i].equals("") || knowledge[i].equals(" "))
continue; continue;
pair = knowledge[i].split(":", 2); pair = knowledge[i].split(":", 2);
action.updateKnowledge.put(pair[0], pair[1]); action.getUpdateKnowledge().put(pair[0], pair[1]);
} }
} else if (feat.startsWith("post")) { } else if (feat.startsWith("post")) {
pair = feat.split("\\(", 2); pair = feat.split("\\(", 2);
url = pair[1]; url = pair[1];
url = url.substring(0, url.length() - 1); url = url.substring(0, url.length() - 1);
pair = pair[0].split("::"); pair = pair[0].split("::");
action.featureMap.put("post", url + "|" + pair[1]); action.getFeatureMap().put("post", url + "|" + pair[1]);
} else { } else {
action.featureMap.put(feat, ""); action.getFeatureMap().put(feat, "");
} }
} }
insertPremise(action.currentPremise, cur_premises); insertPremise(action.getCurrentPremise(), cur_premises);
insertPremise(action.historyPremise, history_premises); insertPremise(action.getHistoryPremise(), history_premises);
//满足条件越多,优先级越大 //满足条件越多,优先级越大
action.priority = action.historyPremise.size() + action.currentPremise.size(); action.setPriority(action.getHistoryPremise().size() + action.getCurrentPremise().size());
action.activePriority = action.priority; //action.activePriority = action.priority;
/* /*
for(String premise:cur_premises){ for(String premise:cur_premises){
pair = premise.split("="); pair = premise.split("=");
...@@ -165,9 +165,9 @@ public class UserInfoController { ...@@ -165,9 +165,9 @@ public class UserInfoController {
*/ */
firstCnditionName = cur_premises[0]; firstCnditionName = cur_premises[0];
if (firstCnditionName.equals(" ")) if (firstCnditionName.equals(" "))
action.indexName = "emptySet"; action.setIndexName("emptySet");
else else
action.indexName = firstCnditionName.split("=")[0].split("::")[0]; action.setIndexName(firstCnditionName.split("=")[0].split("::")[0]);
} catch (IndexOutOfBoundsException e) { } catch (IndexOutOfBoundsException e) {
e.printStackTrace(); e.printStackTrace();
System.out.println(line); System.out.println(line);
...@@ -220,17 +220,17 @@ public class UserInfoController { ...@@ -220,17 +220,17 @@ public class UserInfoController {
} else { } else {
Action action = new Action(); Action action = new Action();
action = buildCondition(action, line); action = buildCondition(action, line);
actionList = conditionTable.get(action.indexName); actionList = conditionTable.get(action.getIndexName());
if (actionList == null) if (actionList == null)
actionList = new ArrayList<Action>(); actionList = new ArrayList<Action>();
actionList.add(action); actionList.add(action);
conditionTable.put(action.indexName, actionList); conditionTable.put(action.getIndexName(), actionList);
if (action.id != 0) { if (action.getId() != 0) {
if(!action.configName.equals("")){ if(!action.getConfigName().equals("")){
userinfo.name2condition.put(action.configName, action); userinfo.name2condition.put(action.getConfigName(), action);
} }
userinfo.id2config.put(action.id, line); userinfo.id2config.put(action.getId(), line);
userinfo.id2condition.put(action.id, action); userinfo.id2condition.put(action.getId(), action);
} }
} }
...@@ -326,7 +326,7 @@ public class UserInfoController { ...@@ -326,7 +326,7 @@ public class UserInfoController {
//------------------- //-------------------
try { try {
conditionName = oldAction.indexName; conditionName = oldAction.getIndexName();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
...@@ -337,13 +337,13 @@ public class UserInfoController { ...@@ -337,13 +337,13 @@ public class UserInfoController {
Iterator<Action> condIter = userInfo.conditionTable.get(conditionName).iterator(); Iterator<Action> condIter = userInfo.conditionTable.get(conditionName).iterator();
while (condIter.hasNext()) { while (condIter.hasNext()) {
Action c = condIter.next(); Action c = condIter.next();
if (c.id == id) { if (c.getId() == id) {
condIter.remove(); condIter.remove();
} }
} }
} }
userInfo.name2condition.remove(oldAction.configName); userInfo.name2condition.remove(oldAction.getConfigName());
userInfo.id2config.remove(id); userInfo.id2config.remove(id);
userInfo.id2condition.remove(id); userInfo.id2condition.remove(id);
} else { } else {
...@@ -362,7 +362,7 @@ public class UserInfoController { ...@@ -362,7 +362,7 @@ public class UserInfoController {
Action oldAction = userInfo.id2condition.get(configId); Action oldAction = userInfo.id2condition.get(configId);
try { try {
conditionName = oldAction.indexName; conditionName = oldAction.getIndexName();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
...@@ -373,13 +373,13 @@ public class UserInfoController { ...@@ -373,13 +373,13 @@ public class UserInfoController {
Iterator<Action> condIter = userInfo.conditionTable.get(conditionName).iterator(); Iterator<Action> condIter = userInfo.conditionTable.get(conditionName).iterator();
while (condIter.hasNext()) { while (condIter.hasNext()) {
Action c = condIter.next(); Action c = condIter.next();
if (c.id == configId) { if (c.getId() == configId) {
condIter.remove(); condIter.remove();
} }
} }
} }
userInfo.name2condition.remove(oldAction.configName); userInfo.name2condition.remove(oldAction.getConfigName());
userInfo.id2config.remove(configId); userInfo.id2config.remove(configId);
userInfo.id2condition.remove(configId); userInfo.id2condition.remove(configId);
} else { } else {
...@@ -408,15 +408,15 @@ public class UserInfoController { ...@@ -408,15 +408,15 @@ public class UserInfoController {
} }
UserInfo userinfo = (UserInfo) context.getAttribute(userName); UserInfo userinfo = (UserInfo) context.getAttribute(userName);
if (userinfo.conditionTable.get(action.indexName) == null) { if (userinfo.conditionTable.get(action.getIndexName()) == null) {
List<Action> actionList = new ArrayList<Action>(); List<Action> actionList = new ArrayList<Action>();
userinfo.conditionTable.put(action.indexName, actionList); userinfo.conditionTable.put(action.getIndexName(), actionList);
} }
if(!action.configName.equals("")){ if(!action.getConfigName().equals("")){
userinfo.name2condition.put(action.configName, action); userinfo.name2condition.put(action.getConfigName(), action);
} }
userinfo.conditionTable.get(action.indexName).add(action); userinfo.conditionTable.get(action.getIndexName()).add(action);
userinfo.id2config.put(id, configLine); userinfo.id2config.put(id, configLine);
userinfo.id2condition.put(id, action); userinfo.id2condition.put(id, action);
......
...@@ -11,8 +11,6 @@ import java.util.List; ...@@ -11,8 +11,6 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor2.ASSISTANT_EMOTION;
public class WorldController { public class WorldController {
public LogWriter logWriter = null; public LogWriter logWriter = null;
public UserInfo userInfo = null; public UserInfo userInfo = null;
...@@ -223,7 +221,7 @@ public class WorldController { ...@@ -223,7 +221,7 @@ public class WorldController {
lastTalker = m.group(1); lastTalker = m.group(1);
} }
returnStr = String.format(PlotConstructor2.TALKER_PATTERN, lastTalker, ASSISTANT_EMOTION) + userInfo.varInitialMap.get("WHO_YOU_ARE").replace("[人名]", lastTalker); returnStr = userInfo.varInitialMap.get("WHO_YOU_ARE").replace("[人名]", lastTalker);
break; break;
...@@ -387,6 +385,10 @@ public class WorldController { ...@@ -387,6 +385,10 @@ public class WorldController {
} }
} }
break; break;
case "queryPathNotExist":
returnStr = userInfo.varInitialMap.get("PATH_NOT_EXIST") + destination;
break;
case "queryAroundPlace": case "queryAroundPlace":
if(userInfo.varInitialMap.containsKey("AROUND_PLACE")) { if(userInfo.varInitialMap.containsKey("AROUND_PLACE")) {
format = userInfo.varInitialMap.get("AROUND_PLACE"); format = userInfo.varInitialMap.get("AROUND_PLACE");
......
...@@ -5,9 +5,9 @@ import com.qiwu.chatbotbackend.db.SqlHelper; ...@@ -5,9 +5,9 @@ import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.ConfigTerm; import com.qiwu.chatbotbackend.entity.ConfigTerm;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import com.qiwu.chatbotbackend.gameDesign.*; import com.qiwu.chatbotbackend.gameDesign.*;
import com.qiwu.chatbotbackend.processing.MyFunc; import com.qiwu.chatbotbackend.processing.ChatCacheController;
import com.qiwu.chatbotbackend.processing.SimpleUtil;
import com.qiwu.chatbotbackend.processing.UserInfoController; import com.qiwu.chatbotbackend.processing.UserInfoController;
import com.qiwu.chatbotbackend.task.utils.FileFinder;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import javax.servlet.ServletException; import javax.servlet.ServletException;
...@@ -21,8 +21,6 @@ import java.time.LocalDateTime; ...@@ -21,8 +21,6 @@ import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.*; import java.util.*;
import static com.qiwu.chatbotbackend.processing.ChatCacheController.CHAT_CACHE_DIR;
@WebServlet(name = "GameDesignServlet", urlPatterns = {"/gameDesign"}) @WebServlet(name = "GameDesignServlet", urlPatterns = {"/gameDesign"})
public class GameDesignServlet extends HttpServlet { public class GameDesignServlet extends HttpServlet {
...@@ -79,7 +77,7 @@ public class GameDesignServlet extends HttpServlet { ...@@ -79,7 +77,7 @@ public class GameDesignServlet extends HttpServlet {
} }
//读取并解析json数据 //读取并解析json数据
String jsonStr = MyFunc.readJSONString(request); String jsonStr = SimpleUtil.readJSONString(request);
if (jsonStr != null && !jsonStr.equals("")) { if (jsonStr != null && !jsonStr.equals("")) {
...@@ -217,10 +215,6 @@ public class GameDesignServlet extends HttpServlet { ...@@ -217,10 +215,6 @@ public class GameDesignServlet extends HttpServlet {
} }
} }
if(returnStatus == 1){
deleteOldArchive(helper, botAccount);
}
helper.destroy(); helper.destroy();
...@@ -267,7 +261,7 @@ public class GameDesignServlet extends HttpServlet { ...@@ -267,7 +261,7 @@ public class GameDesignServlet extends HttpServlet {
boolean deleteVariableFlag = helper.deleteVariableByBotId(botId); boolean deleteVariableFlag = helper.deleteVariableByBotId(botId);
boolean deleteCategoryFlag = helper.deleteCategoryByBotId(botId); boolean deleteCategoryFlag = helper.deleteCategoryByBotId(botId);
boolean batchInsertCategoryFlag = helper.batchInsertCategoryByBotId(botId, categoryMap); boolean batchInsertCategoryFlag = helper.batchInsertCategoryByBotId(botId, categoryMap);
boolean deleteArchiveFlag = deleteOldArchive(helper, botAccount); boolean deleteArchiveFlag = ChatCacheController.deleteChatCache(helper, botAccount);
return deleteConfigFlag && deleteVariableFlag; return deleteConfigFlag && deleteVariableFlag;
...@@ -286,40 +280,44 @@ public class GameDesignServlet extends HttpServlet { ...@@ -286,40 +280,44 @@ public class GameDesignServlet extends HttpServlet {
actionPostData.put("botName", botName); actionPostData.put("botName", botName);
actionPostData.put("botId", (Integer)gameElements.get("botId")); actionPostData.put("botId", (Integer)gameElements.get("botId"));
actionPostData.put("type", "game_plot_init"); actionPostData.put("type", "game_plot_init");
actionPostData.put("welcome", "欢迎来到" + (String)gameElements.get("botName") + ",请说开始剧情或者重新开始"); actionPostData.put("welcome", "欢迎来到" + (String)gameElements.get("botName") + ",请说继续剧情或者重新开始");
actionPostData.put("relationKeywords", additionalKeywords); actionPostData.put("relationKeywords", additionalKeywords);
actionPostData.put("auth", gameElements.get("auth")); actionPostData.put("auth", gameElements.get("auth"));
if (gameElements.containsKey("POS")) if (gameElements.containsKey("POS"))
POS2 = (String)gameElements.get("POS"); POS2 = (String)gameElements.get("POS");
actionPostData.put("POS", POS.toString() + POS2); actionPostData.put("POS", POS.toString() + POS2);
System.out.println(actionPostData.toJSONString());
userInfo.extraInfo.put("activeAction", startCondition); userInfo.extraInfo.put("activeAction", startCondition);
try { try {
returnMessage = MyFunc.postJSON(POST_URL, actionPostData, (String)gameElements.get("auth")); returnMessage = SimpleUtil.postJSON(POST_URL, actionPostData, (String)gameElements.get("auth"));
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
e.printStackTrace(); e.printStackTrace();
} }
if((Integer)returnMessage.get("post_status") == 1 && (Integer)returnMessage.get("status") == 1 ) { if(returnMessage.getInteger("post_status") == 1 && returnMessage.getInteger("status") != null && returnMessage.getInteger("status") == 1 ) {
return "success"; return "success";
}else { }else {
System.out.println(returnMessage.get("parameter")); System.out.println(returnMessage.get("parameter"));
System.out.println("语义关系修改失败"); System.out.println("语义关系生成失败");
return (String)returnMessage.get("parameter"); return (String)returnMessage.get("parameter");
} }
} }
//从配置文件中读取生成状态表所需要的关键词
public void readKeywords(Map<String, StringBuffer> keywordsMap, String path){ public void readKeywords(Map<String, StringBuffer> keywordsMap, String path){
File file = new File(path); File file = new File(path);
String line, pair[]; String line, pair[];
//System.out.println(file.getAbsolutePath());
if(file.exists()){ if(file.exists()){
FileReader reader = null; FileReader reader = null;
try { try {
...@@ -342,13 +340,7 @@ public class GameDesignServlet extends HttpServlet { ...@@ -342,13 +340,7 @@ public class GameDesignServlet extends HttpServlet {
} }
} }
public Boolean deleteOldArchive(SqlHelper helper, String botAccount){
Boolean sqlDeleteFlag = helper.deleteArchiveByBotAccount(botAccount);
Boolean fileDeleteFlag = FileFinder.deleteGameArchive(CHAT_CACHE_DIR, botAccount);
return sqlDeleteFlag && fileDeleteFlag;
}
......
...@@ -122,14 +122,16 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -122,14 +122,16 @@ public class GetAnswerServlet extends HttpServlet {
/*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/ /*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/
ansAction = matcher.getBestMatch(userinfo.conditionTable, context, userinfo); ansAction = matcher.getBestMatch(userinfo.conditionTable, context, userinfo);
if (state.equals("") && ansAction.priority == -1) if (state.equals("") && ansAction.getPriority()== -1)
state = "我不理解,"; state = "我不理解,";
if (state.equals("")) { if (state.equals("")) {
try { try {
System.out.println("test2");
bestMatch = matcher.getSolution(ansAction, context, userinfo); bestMatch = matcher.getSolution(ansAction, context, userinfo);
if ((ansAction.featureMap.containsKey("activate") && ansAction.featureMap.containsKey("post")) || ansAction.featureMap.containsKey("activate:after")) {
//读档成功不应该再激活
//if(matcher.)
if ((ansAction.getFeatureMap().containsKey("activate") && ansAction.getFeatureMap().containsKey("post")) || ansAction.getFeatureMap().containsKey("activate:after")) {
//如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段 //如果当前condition包含激活和提交表单两个操作,那么在所有操作操作完成之后会再激活一次待激活列表,简称后激活阶段
bestMatch = matcher.postActivate(ansAction, bestMatch, context, userinfo); bestMatch = matcher.postActivate(ansAction, bestMatch, context, userinfo);
} }
...@@ -165,7 +167,7 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -165,7 +167,7 @@ public class GetAnswerServlet extends HttpServlet {
ansJ = MyFunc.toJson(bestMatch); ansJ = SimpleUtil.toJson(bestMatch);
} else { } else {
ansJ = "找不到配置文件"; ansJ = "找不到配置文件";
} }
......
...@@ -2,7 +2,7 @@ package com.qiwu.chatbotbackend.servlet; ...@@ -2,7 +2,7 @@ package com.qiwu.chatbotbackend.servlet;
import com.qiwu.chatbotbackend.entity.Action; import com.qiwu.chatbotbackend.entity.Action;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import com.qiwu.chatbotbackend.processing.MyFunc; import com.qiwu.chatbotbackend.processing.SimpleUtil;
import com.qiwu.chatbotbackend.processing.UserInfoController; import com.qiwu.chatbotbackend.processing.UserInfoController;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
...@@ -54,16 +54,16 @@ public class UpdateServlet extends HttpServlet { ...@@ -54,16 +54,16 @@ public class UpdateServlet extends HttpServlet {
userinfo.configStr += line + "\n"; userinfo.configStr += line + "\n";
continue; continue;
} }
//line = MyFunc.convert2Utf8(line.trim()); //line = SimpleUtil.convert2Utf8(line.trim());
userinfo.configStr += line + "\n"; userinfo.configStr += line + "\n";
Action action = new Action(); Action action = new Action();
try { try {
action = UserInfoController.buildCondition(action, line); action = UserInfoController.buildCondition(action, line);
actionList = userinfo.conditionTable.get(action.indexName); actionList = userinfo.conditionTable.get(action.getIndexName());
if (actionList == null) if (actionList == null)
actionList = new ArrayList<Action>(); actionList = new ArrayList<Action>();
actionList.add(action); actionList.add(action);
userinfo.conditionTable.put(action.indexName, actionList); userinfo.conditionTable.put(action.getIndexName(), actionList);
/* /*
for(String name:action.indexName){ for(String name:action.indexName){
userinfo.conditionTable.put() userinfo.conditionTable.put()
...@@ -84,7 +84,7 @@ public class UpdateServlet extends HttpServlet { ...@@ -84,7 +84,7 @@ public class UpdateServlet extends HttpServlet {
response.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");
response.setContentType("text/plain"); response.setContentType("text/plain");
PrintWriter out = response.getWriter(); PrintWriter out = response.getWriter();
String returnStr = MyFunc.toJson("更新失败,以下行有误:" + errorStr + "\\\n"); String returnStr = SimpleUtil.toJson("更新失败,以下行有误:" + errorStr + "\\\n");
out.println("更新失败,以下行有误: "); out.println("更新失败,以下行有误: ");
for (String error : errorList) for (String error : errorList)
out.println("---" + error); out.println("---" + error);
......
...@@ -31,14 +31,23 @@ public class BasicBotUtil { ...@@ -31,14 +31,23 @@ public class BasicBotUtil {
} }
public boolean preprocessing(Map<String, String[]> receiveParameters, ServletContext context) throws IOException { public boolean preprocessing(Map<String, String[]> receiveParameters, ServletContext context) throws IOException {
return infoPointPreprocessing(receiveParameters, context); return infoPointPreprocessing(receiveParameters, context, true);
} }
//在接收到请求后对数据做处理,转化为系统可以处理的数据 //在接收到请求后对数据做处理,转化为系统可以处理的数据
public boolean infoPointPreprocessing(Map<String, String[]> receiveParameters, ServletContext context) throws IOException {
/**
*
* @param receiveParameters
* @param context
* @param setUnknown 如果什么都没识别到就将上一个激活的condition设为unknown
* @return
* @throws IOException
*/
public boolean infoPointPreprocessing(Map<String, String[]> receiveParameters, ServletContext context, Boolean setUnknown) throws IOException {
String return_str = "", k, botType = ""; String return_str = "", k, botType = "";
String receiveParameterStr = ""; String receiveParameterStr = "";
...@@ -71,12 +80,8 @@ public class BasicBotUtil { ...@@ -71,12 +80,8 @@ public class BasicBotUtil {
String values[] = receiveParameters.get(k); String values[] = receiveParameters.get(k);
// for (String v : values) {
// receiveParameterStr += v + " ";
// }
receiveParameterStr += values[0] + " " + "<br>"; receiveParameterStr += values[0] + " " + "<br>";
if (values[0].equals(":")) { if (values[0].equals(":")) {
curInfoPoint.put(k, ""); curInfoPoint.put(k, "");
} }
...@@ -86,7 +91,7 @@ public class BasicBotUtil { ...@@ -86,7 +91,7 @@ public class BasicBotUtil {
//如果引擎什么信息都没识别到,那就将上一轮的nextStep(也就是当前轮的actionName)设为unknown //如果引擎什么信息都没识别到,那就将上一轮的nextStep(也就是当前轮的actionName)设为unknown
iit = curInfoPoint.keySet().iterator(); iit = curInfoPoint.keySet().iterator();
boolean unknown_flag = true; boolean unknown_flag = setUnknown;
while (iit.hasNext()) { while (iit.hasNext()) {
k = iit.next(); k = iit.next();
String values = curInfoPoint.get(k); String values = curInfoPoint.get(k);
...@@ -126,6 +131,10 @@ public class BasicBotUtil { ...@@ -126,6 +131,10 @@ public class BasicBotUtil {
} }
public boolean postprocessing(String chatKey, ServletContext context, Solution bestMatch){ public boolean postprocessing(String chatKey, ServletContext context, Solution bestMatch){
if(historyInfoPoint.get("error_message") != null && historyInfoPoint.get("error_message") != ""){
bestMatch.setAnswer(bestMatch.getAnswer() + historyInfoPoint.get("error_message"));
}
return true; return true;
} }
......
package com.qiwu.chatbotbackend.task.utils;
import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.processing.SimpleUtil;
import java.io.UnsupportedEncodingException;
public class DataDeliver extends Thread {
JSONObject data = null;
String url = "";
public void setData(JSONObject data) {
this.data = data;
}
public void setUrl(String url) {
this.url = url;
}
public void run()
{
System.out.println("线程开始");
System.out.println(url);
try {
SimpleUtil.postJSON(url, data, null);
System.out.println("线程完成");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
package com.qiwu.chatbotbackend.task.utils; package com.qiwu.chatbotbackend.task.utils;
import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; import com.qiwu.chatbotbackend.GameEnvironment.GameEnv;
import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.*; import com.qiwu.chatbotbackend.entity.*;
import com.qiwu.chatbotbackend.gameDesign.PlotConstructor2; import com.qiwu.chatbotbackend.gameDesign.PlotConstructor2;
import com.qiwu.chatbotbackend.processing.ChatCacheController; import com.qiwu.chatbotbackend.processing.ChatCacheController;
import com.qiwu.chatbotbackend.processing.LogWriter; import com.qiwu.chatbotbackend.processing.LogWriter;
import com.qiwu.chatbotbackend.processing.MyFunc; import com.qiwu.chatbotbackend.processing.SimpleUtil;
import com.qiwu.chatbotbackend.processing.WorldController; import com.qiwu.chatbotbackend.processing.WorldController;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
...@@ -33,15 +34,15 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -33,15 +34,15 @@ public class GameBotUtil extends BasicBotUtil{
this.historyInfoPoint = historyInfoPoint; this.historyInfoPoint = historyInfoPoint;
this.userinfo = userinfo; this.userinfo = userinfo;
this.logWriter = logWriter; this.logWriter = logWriter;
this.worldController = worldController;
this.gameEnv = gameEnv; this.gameEnv = gameEnv;
this.chatCache = chatCache; this.chatCache = chatCache;
this.worldController = worldController;
} }
@Override @Override
public boolean preprocessing(Map<String, String[]> receiveParameters, ServletContext context) throws IOException { public boolean preprocessing(Map<String, String[]> receiveParameters, ServletContext context) throws IOException {
Boolean debugFlag = infoPointPreprocessing(receiveParameters, context); Boolean debugFlag = infoPointPreprocessing(receiveParameters, context, false);
//将要去的地点的别名替换为真名 //将要去的地点的别名替换为真名
// String conditionList[] = {"yaobuyao", "want_know_zenmezuo"}; // String conditionList[] = {"yaobuyao", "want_know_zenmezuo"};
...@@ -83,8 +84,14 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -83,8 +84,14 @@ public class GameBotUtil extends BasicBotUtil{
StringBuffer finalText = new StringBuffer(); StringBuffer finalText = new StringBuffer();
String plotText = bestMatch.getAnswer(); String plotText = bestMatch.getAnswer();
//将自动跳转文本、qa文本、查询文本拼接 //将自动跳转文本、qa文本、查询文本拼接
String queryList[] = { "plot_jump_text" ,"common_answer","map_query", "goods_query", "npc_query", "plot_text"}; String queryList[] = { "plot_jump_text" ,"common_answer","map_query", "goods_query", "npc_query", "plot_text", "error_message"};
String queryResult; String queryResult;
Set<String> keepNoSpeaker = new HashSet<String>(){
{
add("sendData:archiveList");
add("请说开始剧情或者继续剧情");
}
};
historyInfoPoint.put("plot_text", plotText); historyInfoPoint.put("plot_text", plotText);
...@@ -92,7 +99,7 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -92,7 +99,7 @@ public class GameBotUtil extends BasicBotUtil{
for(String queryName:queryList){ for(String queryName:queryList){
queryResult = historyInfoPoint.get(queryName); queryResult = historyInfoPoint.get(queryName);
if(queryResult != null){ if(queryResult != null){
if(queryResult.equals("") && !queryName.equals(queryList[queryList.length-1])){ if(queryResult.equals("") && !queryName.equals(queryList[queryList.length-2])){ //不为剧情文本
//剧情可以为空,其他不行 //剧情可以为空,其他不行
continue; continue;
} }
...@@ -108,17 +115,17 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -108,17 +115,17 @@ public class GameBotUtil extends BasicBotUtil{
case "map_query": case "map_query":
case "goods_query": case "goods_query":
case "npc_query": case "npc_query":
queryResult = appendTalker(findRelateTalkers(false).get(0), queryResult, historyInfoPoint, gameEnv, worldController); case "error_message":
queryResult = appendTalker(findRelateTalkers(false).get(0), queryResult, historyInfoPoint, gameEnv);
finalText.append(queryResult); finalText.append(queryResult);
break; break;
case "plot_text": case "plot_text":
if(plotText.endsWith("请说开始剧情或者继续剧情")){ //不需要添加人名和情绪 if(keepNoSpeaker.contains(plotText)){ //不需要添加人名和情绪
finalText.setLength(0); finalText.setLength(0);
finalText.append(plotText); finalText.append(plotText);
} }
//文本为空跳过 //文本为空跳过
else if(plotText.equals("") && finalText.length() != 0){ else if(plotText.equals("") && finalText.length() != 0){
System.out.println("sdfs");
continue; continue;
}else { }else {
...@@ -130,9 +137,8 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -130,9 +137,8 @@ public class GameBotUtil extends BasicBotUtil{
} }
historyInfoPoint.put(queryName, ""); historyInfoPoint.put(queryName, "");
} }
} }
bestMatch.setAnswer(finalText.toString()); bestMatch.setAnswer(finalText.toString());
...@@ -163,13 +169,11 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -163,13 +169,11 @@ public class GameBotUtil extends BasicBotUtil{
} }
}else if (actionName.startsWith("goods_")) { }else if (actionName.startsWith("goods_")) {
if (nameSeries.length == 4) { nameSeries[2] = nameSeries[2].replace("所属角色", "owner");
keyword = gameEnv.queryGoodsAttrByGoodsName(nameSeries[2], nameSeries[3]);
System.out.println("return" + keyword);
}else if (nameSeries.length == 3){
keyword = gameEnv.queryGoodsAttrByGoodsName(nameSeries[1], nameSeries[2]); keyword = gameEnv.queryGoodsAttrByGoodsName(nameSeries[1], nameSeries[2]);
//System.out.println("return" + keyword);
}
}else if(actionName.startsWith("isNeighbour")){ }else if(actionName.startsWith("isNeighbour")){
String opPair[] = actionName.split(":"); String opPair[] = actionName.split(":");
if(!curInfoPoint.containsKey(opPair[1]) || curInfoPoint.get(opPair[1]).equals("unknown") || curInfoPoint.get(opPair[1]).equals("")){ if(!curInfoPoint.containsKey(opPair[1]) || curInfoPoint.get(opPair[1]).equals("unknown") || curInfoPoint.get(opPair[1]).equals("")){
...@@ -205,12 +209,14 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -205,12 +209,14 @@ public class GameBotUtil extends BasicBotUtil{
String namePair[] = variableName.split("_"); String namePair[] = variableName.split("_");
//如果变量名开头为NPC或者item,就专门交给world处理
//如果变量名开头为NPC或者item,就专门交给游戏环境处理
if ((namePair[0].equals("npc") || namePair[0].equals("goods") || namePair[0].equals("map") || namePair[0].equals("place"))) { if ((namePair[0].equals("npc") || namePair[0].equals("goods") || namePair[0].equals("map") || namePair[0].equals("place"))) {
try { try {
if (!updateValue.startsWith("query") && !updateValue.startsWith("update")) { if (!updateValue.startsWith("query") && !updateValue.startsWith("update")) {
updateValue = "update:" + updateValue; updateValue = "update:" + updateValue;
} }
variableName = variableName.replace("所属玩家", "owner");
String returnStr = worldController.worldOperation(gameEnv, variableName, updateValue, curInfoPoint, historyInfoPoint); String returnStr = worldController.worldOperation(gameEnv, variableName, updateValue, curInfoPoint, historyInfoPoint);
updateValue = returnStr; updateValue = returnStr;
} catch (Exception e) { } catch (Exception e) {
...@@ -257,32 +263,35 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -257,32 +263,35 @@ public class GameBotUtil extends BasicBotUtil{
if(userKey.equals(randKey)) if(userKey.equals(randKey))
return; return;
if(ansAction.featureMap.containsKey("newGame")) { if(ansAction.getFeatureMap().containsKey("newGame")) {
System.out.println("newGame"); System.out.println("newGame");
this.chatCache.setGameStart(true); this.chatCache.setGameStart(true);
}else if (ansAction.featureMap.containsKey("gameBackup")) { }else if (ansAction.getFeatureMap().containsKey("gameBackup")) {
System.out.println("gameBackup"); System.out.println("gameBackup");
if(! userKey.equals(randKey)) { //两者不同时表示用户已登录,才有权限存档
chatCache = new ChatCache(userKey, randKey, gameEnv, historyInfoPoint); chatCache = new ChatCache(userKey, randKey, gameEnv, historyInfoPoint);
flag = ChatCacheController.saveChatCache(chatCache, null); flag = ChatCacheController.saveChatCache(chatCache, null);
if(flag) if(flag)
solution.setAnswer(String.format(TALKER_PATTERN, historyInfoPoint.get(ASSISTANT), ASSISTANT_EMOTION) + "存档成功"); solution.setAnswer(String.format(TALKER_PATTERN, historyInfoPoint.get(ASSISTANT), ASSISTANT_EMOTION) + "存档成功");
else else
solution.setAnswer(String.format(TALKER_PATTERN, historyInfoPoint.get(ASSISTANT), ASSISTANT_EMOTION) + "存档失败"); solution.setAnswer(String.format(TALKER_PATTERN, historyInfoPoint.get(ASSISTANT), ASSISTANT_EMOTION) + "存档失败");
}else{
solution.setAnswer("体验作品时无法存档哦,请下载我们的app体验更多功能");
solution.setNext(""); //可能存在问题,估计要一个空格
}
} else if (ansAction.featureMap.containsKey("loadLastArchive")) { } else if (ansAction.getFeatureMap().containsKey("loadLastArchive")) {
System.out.println("loadLastArchive"); System.out.println("loadLastArchive");
ArchiveInfo archiveInfo = helper.queryUserLastGameArchive(userKey); ArchiveInfo archiveInfo = helper.queryUserLastGameArchive(userKey);
if(archiveInfo != null){
System.out.println("存档Id" + archiveInfo.getArchiveId());
}else{
System.out.println("没有找到存档");
}
loading(archiveInfo, solution); loading(archiveInfo, solution);
this.chatCache.setGameStart(true); this.chatCache.setGameStart(true);
} else if (ansAction.featureMap.containsKey("loadArchiveBySite")) { } else if (ansAction.getFeatureMap().containsKey("loadArchiveBySite")) {
System.out.println("loadArchiveBySite"); System.out.println("loadArchiveBySite");
if (curInfoPoint.get(LOAD_BY_SITE_CONDITION) != null) { if (curInfoPoint.get(LOAD_BY_SITE_CONDITION) != null) {
site = curInfoPoint.get(LOAD_BY_SITE_CONDITION).split(":")[1]; site = curInfoPoint.get(LOAD_BY_SITE_CONDITION).split(":")[1];
...@@ -293,9 +302,22 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -293,9 +302,22 @@ public class GameBotUtil extends BasicBotUtil{
}else{ }else{
System.out.println("没有识别到" + LOAD_BY_SITE_CONDITION); System.out.println("没有识别到" + LOAD_BY_SITE_CONDITION);
} }
} else if(ansAction.featureMap.containsKey("sendArchiveList")){ } else if(ansAction.getFeatureMap().containsKey("sendArchiveList")){
System.out.println("sendArchiveList");
DataDeliver dataDeliver = new DataDeliver();
dataDeliver.setUrl(userinfo.varInitialMap.get("CC_URL"));
JSONObject data = new JSONObject();
List<ArchiveInfo> archiveList = helper.queryArchiveByUserKey(userKey);
data.put("data", JSONObject.toJSON(archiveList));
data.put("dataType", "archiveList");
data.put("userKey", userKey);
dataDeliver.setData(data);
dataDeliver.start();
solution.setAnswer("sendData:archiveList:"); //两个冒号,取第二个
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
...@@ -324,6 +346,7 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -324,6 +346,7 @@ public class GameBotUtil extends BasicBotUtil{
solution.setAnswer("从本地加载存档失败"); solution.setAnswer("从本地加载存档失败");
e.printStackTrace(); e.printStackTrace();
} }
//this.chatCache = new ChatCache(this.chatCache.getUserKey(), this.chatCache.getRandKey(), loadCache.getGameEnv(), loadCache.getInfoPoint());
this.chatCache.setInfoPoint(loadCache.getInfoPoint()); this.chatCache.setInfoPoint(loadCache.getInfoPoint());
this.chatCache.setGameEnv(loadCache.getGameEnv()); this.chatCache.setGameEnv(loadCache.getGameEnv());
...@@ -335,6 +358,7 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -335,6 +358,7 @@ public class GameBotUtil extends BasicBotUtil{
String reply = loadCache.getInfoPoint().get(String.format(PlotConstructor2.TASK_REPLY, site)); String reply = loadCache.getInfoPoint().get(String.format(PlotConstructor2.TASK_REPLY, site));
solution.setAnswer(reply); solution.setAnswer(reply);
solution.setNext("nextStep=" + nextStep); solution.setNext("nextStep=" + nextStep);
this.chatCache.setReload(true);
}else{ }else{
System.out.println("没有找到该存档"); System.out.println("没有找到该存档");
...@@ -416,19 +440,18 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -416,19 +440,18 @@ public class GameBotUtil extends BasicBotUtil{
* @param curInfoPoint * @param curInfoPoint
* @param historyInfoPoint * @param historyInfoPoint
* @param gameEnv * @param gameEnv
* @param worldController
* @param site * @param site
* @param logWriter * @param logWriter
* @return * @return
*/ */
public static Integer sameLocation(String reply, Map<String ,String> curInfoPoint, Map<String ,String> historyInfoPoint, GameEnv gameEnv, WorldController worldController, String site, LogWriter logWriter){ public static Integer sameLocation(String reply, Map<String ,String> curInfoPoint, Map<String ,String> historyInfoPoint, GameEnv gameEnv, String site, LogWriter logWriter){
String npc, location; String npc, location;
Matcher m = findTalker(reply); Matcher m = findTalker(reply);
int flag = 1; int flag = 1;
if(m.find()) { if(m.find()) {
npc = m.group(1); npc = m.group(1);
location = worldController.worldOperation(gameEnv, "npc_query", "queryLocationByNPCName:" + npc, curInfoPoint, historyInfoPoint); location = gameEnv.queryNpcAttrByNpcName(npc, "location");
if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){ if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){
if(gameEnv.queryNpcAttrByNpcName(npc, "能否说话") == null || gameEnv.queryNpcAttrByNpcName(npc, "能否说话").equals("能")){ if(gameEnv.queryNpcAttrByNpcName(npc, "能否说话") == null || gameEnv.queryNpcAttrByNpcName(npc, "能否说话").equals("能")){
flag = 1; flag = 1;
...@@ -466,6 +489,9 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -466,6 +489,9 @@ public class GameBotUtil extends BasicBotUtil{
Boolean flag = false; Boolean flag = false;
location = gameEnv.queryNpcAttrByNpcName(npc, "location"); location = gameEnv.queryNpcAttrByNpcName(npc, "location");
if( location == null){
return false;
}
if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){ if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){
if(gameEnv.queryNpcAttrByNpcName(npc, "能否说话") == null || gameEnv.queryNpcAttrByNpcName(npc, "能否说话").equals("能")){ if(gameEnv.queryNpcAttrByNpcName(npc, "能否说话") == null || gameEnv.queryNpcAttrByNpcName(npc, "能否说话").equals("能")){
...@@ -491,7 +517,7 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -491,7 +517,7 @@ public class GameBotUtil extends BasicBotUtil{
} }
public static String appendTalker(String npc, String text, Map<String ,String> historyInfoPoint, GameEnv gameEnv, WorldController worldController){ public static String appendTalker(String npc, String text, Map<String ,String> historyInfoPoint, GameEnv gameEnv){
return String.format(TALKER_PATTERN, npc, PlotConstructor2.ASSISTANT_EMOTION) + text; return String.format(TALKER_PATTERN, npc, PlotConstructor2.ASSISTANT_EMOTION) + text;
...@@ -511,7 +537,7 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -511,7 +537,7 @@ public class GameBotUtil extends BasicBotUtil{
returnText = reply; returnText = reply;
break; break;
case "less_talker": case "less_talker":
return appendTalker(findRelateTalkers(false).get(0), reply, historyInfoPoint, gameEnv, worldController); return appendTalker(findRelateTalkers(false).get(0), reply, historyInfoPoint, gameEnv);
case "to_unknown": case "to_unknown":
Set<String> candidates = new HashSet<String>(); Set<String> candidates = new HashSet<String>();
Map<String, List<String>> npcTextMap = null; Map<String, List<String>> npcTextMap = null;
...@@ -535,14 +561,14 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -535,14 +561,14 @@ public class GameBotUtil extends BasicBotUtil{
//先找剧情相关的npc //先找剧情相关的npc
foundNPC = foundCandidateText(candidates, npcTextMap); foundNPC = foundCandidateText(candidates, npcTextMap);
if(!foundNPC.equals("")){ if(!foundNPC.equals("")){
returnText = MyFunc.randStr(npcTextMap.get(foundNPC)); returnText = SimpleUtil.randStr(npcTextMap.get(foundNPC));
break; break;
}else{ }else{
//再找地点相关的npc //再找地点相关的npc
candidates.addAll(findRelateTalkers(true)); candidates.addAll(findRelateTalkers(true));
foundNPC = foundCandidateText(candidates, npcTextMap); foundNPC = foundCandidateText(candidates, npcTextMap);
if(!foundNPC.equals("")){ if(!foundNPC.equals("")){
returnText = MyFunc.randStr(npcTextMap.get(foundNPC)); returnText = SimpleUtil.randStr(npcTextMap.get(foundNPC));
break; break;
} }
} }
...@@ -615,8 +641,12 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -615,8 +641,12 @@ public class GameBotUtil extends BasicBotUtil{
private List<String> findRelateTalkers(Boolean includeSiteNPC){ private List<String> findRelateTalkers(Boolean includeSiteNPC){
String site = historyInfoPoint.get("site"); String site = historyInfoPoint.get("site");
String lastReply = historyInfoPoint.get("lastReply"); String lastReply = historyInfoPoint.get("lastReply");
List<String> talkers = new ArrayList<String>(); List<String> talkers = new ArrayList<String>();
if(lastReply == null) lastReply = "";
String plotLastTalker = findTextLastTalker(lastReply, site); String plotLastTalker = findTextLastTalker(lastReply, site);
if(!plotLastTalker.equals("")){ if(!plotLastTalker.equals("")){
talkers.add(plotLastTalker); talkers.add(plotLastTalker);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment