Commit 0a43d064 by hxw

添加激活多个剧情

parent 3d56c4c5
...@@ -18,7 +18,7 @@ public class ChatCache implements DisposableBean { ...@@ -18,7 +18,7 @@ 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 reloading = false; private boolean gameStart = false;
public String getBotAccount() { public String getBotAccount() {
...@@ -29,9 +29,6 @@ public class ChatCache implements DisposableBean { ...@@ -29,9 +29,6 @@ public class ChatCache implements DisposableBean {
this.botAccount = botAccount; this.botAccount = botAccount;
} }
public boolean isReloading() {
return reloading;
}
public String getUserKey() { public String getUserKey() {
return userKey; return userKey;
...@@ -49,10 +46,6 @@ public class ChatCache implements DisposableBean { ...@@ -49,10 +46,6 @@ public class ChatCache implements DisposableBean {
this.randKey = randKey; this.randKey = randKey;
} }
public void setReloading(boolean reloading) {
this.reloading = reloading;
}
public Map<String, String> getInfoPoint() { public Map<String, String> getInfoPoint() {
return infoPoint; return infoPoint;
} }
...@@ -61,6 +54,14 @@ public class ChatCache implements DisposableBean { ...@@ -61,6 +54,14 @@ public class ChatCache implements DisposableBean {
this.infoPoint = infoPoint; this.infoPoint = infoPoint;
} }
public boolean isGameStart() {
return gameStart;
}
public void setGameStart(boolean gameStart) {
this.gameStart = gameStart;
}
public GameEnv getGameEnv() { public GameEnv getGameEnv() {
return gameEnv; return gameEnv;
} }
......
...@@ -121,7 +121,9 @@ public class CharacterConstructor extends ElementConstructor { ...@@ -121,7 +121,9 @@ public class CharacterConstructor extends ElementConstructor {
} }
} }
keywordMap.put("onlineModeTalkers", onlineModeTalkers);
varInitialMap.put("onlineModeTalkers", onlineModeTalkers.toString()); varInitialMap.put("onlineModeTalkers", onlineModeTalkers.toString());
//System.out.println("onlineModeTalkers" + varInitialMap.get("onlineModeTalkers"));
conditionDescription.put("onlineModeTalkers", "所有在线npc"); conditionDescription.put("onlineModeTalkers", "所有在线npc");
//根据根据NPC的名字查询地点 //根据根据NPC的名字查询地点
......
...@@ -37,17 +37,26 @@ public class MapConstructor extends ElementConstructor { ...@@ -37,17 +37,26 @@ public class MapConstructor extends ElementConstructor {
JSONObject jobj = null; JSONObject jobj = null;
int locationId, index; int locationId, index;
String locationName; String locationName, taskLineName = "";
//ArrayList<ArrayList<Integer>> matrix= new ArrayList<ArrayList<Integer>>();
//ArrayList<Integer> vec1d = new ArrayList<Integer>();
locationNum = locations.size(); locationNum = locations.size();
StringBuffer nameSet = null; StringBuffer nameSet = null;
keywordMap.putIfAbsent("site_list", new StringBuffer());
for (int i = 0; i < locationNum; i++) { for (int i = 0; i < locationNum; i++) {
jobj = locations.getJSONObject(i); jobj = locations.getJSONObject(i);
jobj.put("index", i); jobj.put("index", i);
locationName = (String) jobj.get("name"); locationName = (String) jobj.get("name");
keywordMap.get("site_list").append("+").append(locationName);
taskLineName = String.format(PlotConstructor.TASK_LINE, locationName);
if (!varInitialMap.containsKey(taskLineName)) {
conditionDescription.put(taskLineName, taskLineName);
varInitialMap.put(taskLineName, "");
}
nameSet = new StringBuffer(); nameSet = new StringBuffer();
nameSet.append(locationName); nameSet.append(locationName);
...@@ -211,8 +220,6 @@ public class MapConstructor extends ElementConstructor { ...@@ -211,8 +220,6 @@ public class MapConstructor extends ElementConstructor {
/** /**
* 生成‘怎么去哪里’所需要的配置文件 * 生成‘怎么去哪里’所需要的配置文件
*/ */
...@@ -220,23 +227,19 @@ public class MapConstructor extends ElementConstructor { ...@@ -220,23 +227,19 @@ public class MapConstructor extends ElementConstructor {
String conditionName = "want_know_zenmezuo"; String conditionName = "want_know_zenmezuo";
StringBuffer placeKeywords = new StringBuffer(); StringBuffer placeKeywords = new StringBuffer();
String placeA, placeB, descriptionB, text, pathNode; String nameSet;
for (int i = 0; i < locationNum; i++) { for (int i = 0; i < locationNum; i++) {
placeA = (String) locations.getJSONObject(i).get("nameSet"); nameSet = (String) locations.getJSONObject(i).get("nameSet");
placeKeywords.append("+" + placeA); placeKeywords.append("+").append(nameSet);
} }
for (int j = 0; j < locationNum; j++) {
placeB = (String) locations.getJSONObject(j).get("nameSet");
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Include=" + placeKeywords conditionName + "::match-Include=" + placeKeywords
+ ",isNeighbour:"+ conditionName + "::match-Include=0", + ",isNeighbour:"+ conditionName + "::match-Include=0",
"site::match-Include=" + placeB , " ",
"match,return-0", "match,return-0",
"", "",
" ", " ",
...@@ -248,12 +251,10 @@ public class MapConstructor extends ElementConstructor { ...@@ -248,12 +251,10 @@ public class MapConstructor extends ElementConstructor {
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Include=" + placeKeywords conditionName + "::match-Include=" + placeKeywords
+ ",isNeighbour:"+ conditionName + "::match-Include=1+3+4", + ",isNeighbour:"+ conditionName + "::match-Include=1+3+4",
"site::match-Include=" + placeB , " " ,
"match,return-0", "match,return-0",
"", "",
" ", " ",
...@@ -269,7 +270,7 @@ public class MapConstructor extends ElementConstructor { ...@@ -269,7 +270,7 @@ public class MapConstructor extends ElementConstructor {
jConfig = new JConfig( jConfig = new JConfig(
conditionName + "::match-Include=" + placeKeywords conditionName + "::match-Include=" + placeKeywords
+ ",isNeighbour:"+ conditionName + "::match-Include=2", + ",isNeighbour:"+ conditionName + "::match-Include=2",
"site::match-Include=" + placeB , " " ,
"match,return-0", "match,return-0",
"", "",
" ", " ",
...@@ -279,7 +280,7 @@ public class MapConstructor extends ElementConstructor { ...@@ -279,7 +280,7 @@ public class MapConstructor extends ElementConstructor {
jConfig.setAuxiliaryPriority("1"); jConfig.setAuxiliaryPriority("1");
JConfig.activateCopy(jConfig, jConfigList, "map"); JConfig.activateCopy(jConfig, jConfigList, "map");
}
} }
......
...@@ -25,7 +25,8 @@ public class PlotConstructor extends ElementConstructor { ...@@ -25,7 +25,8 @@ public class PlotConstructor extends ElementConstructor {
JSONArray plots = null; JSONArray plots = null;
HashMap<String, ArrayList<String>> adjList = new HashMap<String, ArrayList<String>>(); HashMap<String, ArrayList<String>> adjList = new HashMap<String, ArrayList<String>>();
HashMap<String, ArrayList<String>> revAdjList = new HashMap<String, ArrayList<String>>(); HashMap<String, ArrayList<String>> revAdjList = new HashMap<String, ArrayList<String>>();
private HashMap<String, JSONObject> id2j = new HashMap<String, JSONObject>(); private HashMap<String, JSONObject> plotIndex = new HashMap<String, JSONObject>();
private HashMap<String, String> plotTextIndex = new HashMap<String, String>();
HashMap<String, Boolean> visited = new HashMap<String, Boolean>(); HashMap<String, Boolean> visited = new HashMap<String, Boolean>();
...@@ -33,9 +34,6 @@ public class PlotConstructor extends ElementConstructor { ...@@ -33,9 +34,6 @@ public class PlotConstructor extends ElementConstructor {
public static String TASK_CONDITION = "任务线%s最后一个condition"; public static String TASK_CONDITION = "任务线%s最后一个condition";
public static String TASK_REPLY = "任务线%s最后的回答"; public static String TASK_REPLY = "任务线%s最后的回答";
public HashMap<String, JSONObject> getId2j() {
return id2j;
}
public PlotConstructor(SqlHelper helper, int botId, String botAccount, Map<String, StringBuffer> keywordMap, HashSet<String> exceptRelation, StringBuffer POS) { public PlotConstructor(SqlHelper helper, int botId, String botAccount, Map<String, StringBuffer> keywordMap, HashSet<String> exceptRelation, StringBuffer POS) {
super(); super();
...@@ -62,8 +60,8 @@ public class PlotConstructor extends ElementConstructor { ...@@ -62,8 +60,8 @@ public class PlotConstructor extends ElementConstructor {
this.plots = plots; this.plots = plots;
constructAdjList(plots); constructAdjList(plots);
if (id2j.containsKey(start)) { if (plotIndex.containsKey(start)) {
String taskLineName = "任务线_" + id2j.get(start).get("place") + "进度"; String taskLineName = "任务线_" + plotIndex.get(start).get("place") + "进度";
conditionDescription.put(taskLineName, taskLineName); conditionDescription.put(taskLineName, taskLineName);
if(jsonObject.get("firstUnknownText") == null) if(jsonObject.get("firstUnknownText") == null)
...@@ -72,11 +70,11 @@ public class PlotConstructor extends ElementConstructor { ...@@ -72,11 +70,11 @@ public class PlotConstructor extends ElementConstructor {
varInitialMap.put("unknownText", (String)jsonObject.get("firstUnknownText")); varInitialMap.put("unknownText", (String)jsonObject.get("firstUnknownText"));
varInitialMap.put("game_step", String.format(GAME_STEP_FORMAT, botAccount, (String) id2j.get(start).get("id"))); varInitialMap.put("game_step", String.format(GAME_STEP_FORMAT, botAccount, (String) plotIndex.get(start).get("id")));
conditionDescription.put("unknownText", "对于无法识别的问题做出的回答"); conditionDescription.put("unknownText", "对于无法识别的问题做出的回答");
conditionDescription.put("game_step", "QA问答游戏进度"); conditionDescription.put("game_step", "QA问答游戏进度");
BFSGenerate4(id2j.get(start), userinfo, jsonObject); BFSGenerate4(plotIndex.get(start), userinfo, jsonObject);
varInitialMap.put(start, "1"); varInitialMap.put(start, "1");
...@@ -101,7 +99,7 @@ public class PlotConstructor extends ElementConstructor { ...@@ -101,7 +99,7 @@ public class PlotConstructor extends ElementConstructor {
//根据id构造邻接表 //根据id构造邻接表
public void constructAdjList(JSONArray plots) { public void constructAdjList(JSONArray plots) {
int length = plots.size(), branchSize; int length = plots.size(), branchSize;
String id = "", nextPlotId = ""; String id = "", nextPlotId = "", nextPlotText;
JSONObject plot = null; JSONObject plot = null;
JSONArray branch = null; JSONArray branch = null;
...@@ -119,15 +117,17 @@ public class PlotConstructor extends ElementConstructor { ...@@ -119,15 +117,17 @@ public class PlotConstructor extends ElementConstructor {
branchSize = branch.size(); branchSize = branch.size();
for (int j = 0; j < branchSize; j++) { for (int j = 0; j < branchSize; j++) {
nextPlotId = (String) branch.getJSONObject(j).get("nextPlotId"); nextPlotId = (String) branch.getJSONObject(j).get("nextPlotId");
nextPlotText = branch.getJSONObject(j).getString("reply");
plotTextIndex.put(nextPlotId, nextPlotText);
if (revAdjList.get(nextPlotId) == null) { if (revAdjList.get(nextPlotId) == null) {
revAdjList.put(nextPlotId, new ArrayList<>()); revAdjList.put(nextPlotId, new ArrayList<>());
} }
varSlotFilt(branch.getJSONObject(j), varInitialMap); varSlotFilt(branch.getJSONObject(j), keywordMap);
adjList.get(id).add(nextPlotId); adjList.get(id).add(nextPlotId);
revAdjList.get(nextPlotId).add(id); revAdjList.get(nextPlotId).add(id);
} }
id2j.put(id, plot); plotIndex.put(id, plot);
} }
} }
...@@ -135,7 +135,7 @@ public class PlotConstructor extends ElementConstructor { ...@@ -135,7 +135,7 @@ public class PlotConstructor extends ElementConstructor {
* 如果剧情文本中出现变量槽,那么需要判断这个剧情的npc是不是在线模式,如果不是在线模式,就需要把变量槽过滤掉 * 如果剧情文本中出现变量槽,那么需要判断这个剧情的npc是不是在线模式,如果不是在线模式,就需要把变量槽过滤掉
* @param branchNode * @param branchNode
*/ */
public static void varSlotFilt(JSONObject branchNode, Map<String, String> varInitialMap){ public static void varSlotFilt(JSONObject branchNode, Map<String, StringBuffer> keywordMap){
String VARIABLE_SEARCH_PATTERN = "【(.*?)@(.*?)(\\$\\{.*?})", npcName, middleText = "", varSlot = ""; String VARIABLE_SEARCH_PATTERN = "【(.*?)@(.*?)(\\$\\{.*?})", npcName, middleText = "", varSlot = "";
...@@ -144,7 +144,9 @@ public class PlotConstructor extends ElementConstructor { ...@@ -144,7 +144,9 @@ public class PlotConstructor extends ElementConstructor {
while (m.find()) { while (m.find()) {
npcName = m.group(1); npcName = m.group(1);
//onlineModeTalkers, 在CharecterConstructor中定义,q前面加一个逗号是为了防止出现子串匹配的问题 //onlineModeTalkers, 在CharecterConstructor中定义,q前面加一个逗号是为了防止出现子串匹配的问题
if(!varInitialMap.get("onlineModeTalkers").contains("," + npcName)) { //System.out.println("npcName" + npcName);
//System.out.println("varInitialMap.get(\"onlineModeTalkers\")" + varInitialMap.get("onlineModeTalkers"));
if(keywordMap.get("onlineModeTalkers").indexOf("," + npcName + ",") == -1) {
varSlot = m.group(3); varSlot = m.group(3);
middleText = m.group(2); middleText = m.group(2);
branchNode.put("reply", branchNode.getString("reply").replace(npcName + "@" + middleText + varSlot, npcName + "@" + middleText)); branchNode.put("reply", branchNode.getString("reply").replace(npcName + "@" + middleText + varSlot, npcName + "@" + middleText));
...@@ -223,9 +225,6 @@ public class PlotConstructor extends ElementConstructor { ...@@ -223,9 +225,6 @@ public class PlotConstructor extends ElementConstructor {
branch = node.getJSONArray("branch"); branch = node.getJSONArray("branch");
branchSize = branch.size(); branchSize = branch.size();
...@@ -239,22 +238,22 @@ public class PlotConstructor extends ElementConstructor { ...@@ -239,22 +238,22 @@ public class PlotConstructor extends ElementConstructor {
branchNode = branch.getJSONObject(i); branchNode = branch.getJSONObject(i);
Map<String, String> updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class); Map<String, String> updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class);
System.out.println("id:" + id + "剧情分支:" + branchNode.toJSONString()); //System.out.println("id:" + id + "剧情分支:" + branchNode.toJSONString());
nextUnknownText = updateKnowledge.get("unknownText"); nextUnknownText = updateKnowledge.get("unknownText");
System.out.println(id + "分支内" +nextUnknownText); //System.out.println(id + "分支内" +nextUnknownText);
nextId = (String)branchNode.get("nextPlotId"); nextId = (String)branchNode.get("nextPlotId");
//skipText.append(); //skipText.append();
if(nextId == null || nextId.equals("") || !id2j.containsKey(nextId)){ if(nextId == null || nextId.equals("") || !plotIndex.containsKey(nextId)){
nextId = id + "_end"; nextId = id + "_end";
branchNode.put("nextPlotId", nextId); branchNode.put("nextPlotId", nextId);
createEndNode(node, id, nextId, curUnknownText); createEndNode(node, id, nextId, curUnknownText);
} }
//保留下一步剧情的地点 //保留下一步剧情的地点
beforeJumpLocatin = ((String)id2j.get(nextId).get("place")).split("\\+")[0]; beforeJumpLocatin = ((String)plotIndex.get(nextId).get("place")).split("\\+")[0];
autoJumpUpdateKnowledge.clear(); autoJumpUpdateKnowledge.clear();
/** /**
...@@ -263,7 +262,7 @@ public class PlotConstructor extends ElementConstructor { ...@@ -263,7 +262,7 @@ public class PlotConstructor extends ElementConstructor {
*/ */
while(branchNode.get("autoJump") != null && (boolean)branchNode.get("autoJump") && branchNode.get("nextPlotId") != null && !branchNode.get("nextPlotId").equals("")){ while(branchNode.get("autoJump") != null && (boolean)branchNode.get("autoJump") && branchNode.get("nextPlotId") != null && !branchNode.get("nextPlotId").equals("")){
nextId = (String)branchNode.get("nextPlotId"); nextId = (String)branchNode.get("nextPlotId");
JSONObject jumpNextNode = id2j.get(nextId); JSONObject jumpNextNode = plotIndex.get(nextId);
JSONObject jumpBranchNode = jumpNextNode.getJSONArray("branch").getJSONObject(0); JSONObject jumpBranchNode = jumpNextNode.getJSONArray("branch").getJSONObject(0);
skipText.append((String)branchNode.get("reply")); skipText.append((String)branchNode.get("reply"));
...@@ -279,10 +278,10 @@ public class PlotConstructor extends ElementConstructor { ...@@ -279,10 +278,10 @@ public class PlotConstructor extends ElementConstructor {
jumpNextNextId = (String)jumpBranchNode.get("nextPlotId"); jumpNextNextId = (String)jumpBranchNode.get("nextPlotId");
//如果下一步剧情存在 //如果下一步剧情存在
if(jumpNextNextId != null && !jumpNextNextId.equals("") && id2j.containsKey(jumpNextNextId)){ if(jumpNextNextId != null && !jumpNextNextId.equals("") && plotIndex.containsKey(jumpNextNextId)){
System.out.println(jumpNextNextId); System.out.println(jumpNextNextId);
System.out.println(id2j.get(jumpNextNextId)); System.out.println(plotIndex.get(jumpNextNextId));
jumpNextNextLocation = (String)id2j.get(jumpNextNextId).get("place"); jumpNextNextLocation = (String)plotIndex.get(jumpNextNextId).get("place");
autoJumpUpdateKnowledge.put("site", jumpNextNextLocation); autoJumpUpdateKnowledge.put("site", jumpNextNextLocation);
autoJumpUpdateKnowledge.put("npc_update", "updateFollowerLocation:" + jumpNextNextLocation); autoJumpUpdateKnowledge.put("npc_update", "updateFollowerLocation:" + jumpNextNextLocation);
...@@ -309,11 +308,11 @@ public class PlotConstructor extends ElementConstructor { ...@@ -309,11 +308,11 @@ public class PlotConstructor extends ElementConstructor {
//如果存在下一剧情,就将下一步剧情的condition设为下一个激活的conditin,把地点更新为下一步剧情的地点,并更新任务线进度 //如果存在下一剧情,就将下一步剧情的condition设为下一个激活的conditin,把地点更新为下一步剧情的地点,并更新任务线进度
nextCondition = (String) id2j.get(nextId).get("conditionName"); nextCondition = (String) plotIndex.get(nextId).get("conditionName");
if(nextCondition.equals("")) if(nextCondition.equals(""))
nextCondition = "yaobuyao"; nextCondition = "yaobuyao";
nextLocation = ((String) id2j.get(nextId).get("place")).split("\\+")[0]; nextLocation = ((String) plotIndex.get(nextId).get("place")).split("\\+")[0];
//任务线 //任务线
nTaskLineName = String.format(TASK_LINE, nextLocation); nTaskLineName = String.format(TASK_LINE, nextLocation);
...@@ -354,7 +353,7 @@ public class PlotConstructor extends ElementConstructor { ...@@ -354,7 +353,7 @@ public class PlotConstructor extends ElementConstructor {
* 如果当前条件不为空,则需要满足条件才能进入下一步剧情 * 如果当前条件不为空,则需要满足条件才能进入下一步剧情
* *
* 3. 下一部剧情是否为空 * 3. 下一部剧情是否为空
* 如果下一部剧情为空,剧情编号、任务线、地点、不变,condition改为yaobuyao,reply改为当前unknown文本,主角不随剧情移动 *
* *
* 4. 有没有说去XX * 4. 有没有说去XX
* *
...@@ -368,15 +367,31 @@ public class PlotConstructor extends ElementConstructor { ...@@ -368,15 +367,31 @@ public class PlotConstructor extends ElementConstructor {
* 3. 自动跳转完成后的地点 * 3. 自动跳转完成后的地点
*/ */
//自动跳转前的剧情也要记下来 /**
* 自动跳转前的剧情也要记下来,这里是自动跳转前需要更新的变量(无论是否包含自动跳转都会更新)
* 1. 将自动跳转剧情的关联地点最后被激活的condition更新为yaobuyao (其实这一步是非必须的,)
* 2. 自动跳转剧情文本保存到beforeJumpTaskReply
* 3. 当前剧情和下一步剧情更新状态
*/
String beforeJumpTaskCondition = String.format(TASK_CONDITION, beforeJumpLocatin); String beforeJumpTaskCondition = String.format(TASK_CONDITION, beforeJumpLocatin);
String beforeJumpTaskReply = String.format(TASK_REPLY, beforeJumpLocatin); String beforeJumpTaskReply = String.format(TASK_REPLY, beforeJumpLocatin);
String beforeJumpUK = "-<-" + beforeJumpTaskCondition + ":yaobuyao" + "-<-" + beforeJumpTaskReply + ":" + skipText + "-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1" ; String beforeJumpUK = "-<-" + beforeJumpTaskCondition + ":yaobuyao" + "-<-" + beforeJumpTaskReply + ":" + skipText + "-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1" ;
//如果主角的位置随着剧情移动 if(branchNode.containsKey("activateExtraPlot")) {
//激活除了下一步剧情以外的剧情
beforeJumpUK = extraActivatedPlot(beforeJumpUK, nextLocation, JSONArray.parseArray(branchNode.getJSONArray("activateExtraPlot").toJSONString(), String.class));
}
//如果主角的位置随着剧情移动或者下一步剧情地点和当前剧情相同,主角地点和game_step要做相应更新
if((!branchNode.containsKey("moveWithPlot") || (Boolean)branchNode.get("moveWithPlot")) || location.equals(beforeJumpLocatin)) { if((!branchNode.containsKey("moveWithPlot") || (Boolean)branchNode.get("moveWithPlot")) || location.equals(beforeJumpLocatin)) {
extraUK = beforeJumpUK + "-<-" + extraUK + "-<-site:" + nextLocation + "-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextGameStep); extraUK = beforeJumpUK + "-<-" + extraUK + "-<-site:" + nextLocation + "-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextGameStep);
//自动跳转剧情如果有更新属性,这些数据也需要更新
updateKnowledge.putAll(autoJumpUpdateKnowledge); updateKnowledge.putAll(autoJumpUpdateKnowledge);
}else { }else {
...@@ -390,7 +405,7 @@ public class PlotConstructor extends ElementConstructor { ...@@ -390,7 +405,7 @@ public class PlotConstructor extends ElementConstructor {
* 注意,比较的是当前地点和跳转前的地点 * 注意,比较的是当前地点和跳转前的地点
* 地点更新为跳转后的地点 * 地点更新为跳转后的地点
*/ */
//如果在剧情中存在自动跳转的情况,那么应该比较自动跳转完成后的地点喝下一步剧情的地点是否相同 //可能因为不存在自动跳转或者地点不同,所以执行现在的代码,如果在剧情中存在自动跳转的情况,那么应该比较自动跳转完成后的地点喝下一步剧情的地点是否相同
if(!location.equals(beforeJumpLocatin)){ if(!location.equals(beforeJumpLocatin)){
//System.out.println(id + "报异常" + curUnknownText); //System.out.println(id + "报异常" + curUnknownText);
if(curUnknownText.equals("")) { if(curUnknownText.equals("")) {
...@@ -469,9 +484,9 @@ public class PlotConstructor extends ElementConstructor { ...@@ -469,9 +484,9 @@ public class PlotConstructor extends ElementConstructor {
//将子结点加入队列 //将子结点加入队列
adjId = (String) branchNode.get("nextPlotId"); adjId = (String) branchNode.get("nextPlotId");
if (visited.get(adjId) == null && id2j.get(adjId) != null) { if (visited.get(adjId) == null && plotIndex.get(adjId) != null) {
visited.put(adjId, true); visited.put(adjId, true);
adjNode = id2j.get(adjId); adjNode = plotIndex.get(adjId);
adjNode.put("parentId", id); adjNode.put("parentId", id);
//System.out.println("下一个剧情id:" + adjId + ",nextUnknownText:" + nextUnknownText); //System.out.println("下一个剧情id:" + adjId + ",nextUnknownText:" + nextUnknownText);
...@@ -543,7 +558,6 @@ public class PlotConstructor extends ElementConstructor { ...@@ -543,7 +558,6 @@ public class PlotConstructor extends ElementConstructor {
jConfig.setAuxiliaryPriority("0"); jConfig.setAuxiliaryPriority("0");
jConfigList.add(jConfig); jConfigList.add(jConfig);
System.out.println("qa_URL" + keywordMap.get("QA_URL"));
jConfig = new JConfig( jConfig = new JConfig(
...@@ -669,70 +683,13 @@ public class PlotConstructor extends ElementConstructor { ...@@ -669,70 +683,13 @@ public class PlotConstructor extends ElementConstructor {
endNode.put("updateKnowledge", new ArrayList()); endNode.put("updateKnowledge", new ArrayList());
id2j.put(nextId, endNode); plotIndex.put(nextId, endNode);
visited.put(nextId, true); visited.put(nextId, true);
} }
void addGameStartPlot(JSONObject gameElements, Map<String, StringBuffer> keywordMap){ void addGameStartPlot(JSONObject gameElements, Map<String, StringBuffer> keywordMap){
// JSONObject startPlot = new JSONObject();
// startPlot.put("id", "start");
// startPlot.put("conditionName", "start_options");
// startPlot.put("place", "哪呢? 还没开始呢");
// startPlot.put("branch", new JSONArray());
//
// JSONObject branch1 = new JSONObject();
// branch1.put("curPremise", new JSONArray(){
// {
// add("start_options::match-Include=+重新开始");
// }
// });
//
// branch1.put("higherPriority", true);
// branch1.put("hisPremise", new JSONArray());
// branch1.put("extraFeature", "newGame");
// branch1.put("reply", gameElements.get("plotStartText"));
// branch1.put("updateKnowledge", new JSONObject(){
// {
// put("unknownText", gameElements.get("firstUnknownText"));
// }
// });
// branch1.put("nextPlotId", gameElements.get("start"));
// branch1.put("includeCurInfo", false);
//
//
//
// startPlot.getJSONArray("branch").add(branch1);
//
//
// JSONObject branch2 = new JSONObject();
// branch2.put("curPremise", new JSONArray(){
// {
// add("start_options::match-Include=+开始+开始游戏+继续游戏+继续");
// }
// });
//
// branch2.put("higherPriority", true);
// branch2.put("hisPremise", new JSONArray());
// branch2.put("reply", gameElements.get("plotStartText"));
// branch2.put("updateKnowledge", new JSONObject(){
// {
// put("unknownText", gameElements.get("firstUnknownText"));
// }
// });
// branch2.put("extraFeature", "loadLastArchive");
// branch2.put("nextPlotId", gameElements.get("start"));
// branch2.put("includeCurInfo", false);
// if(gameElements.get("startAutoJump") != null)
// branch2.put("autoJump", gameElements.get("startAutoJump"));
// else
// branch2.put("autoJump", false);
// startPlot.getJSONArray("branch").add(branch2);
//
//
// gameElements.getJSONArray("plots").add(startPlot);
// gameElements.put("start", "start");
// gameElements.put("firstUnknownText", "请说开始游戏或者继续游戏");
File file = null; File file = null;
FileReader fr = null; FileReader fr = null;
...@@ -807,6 +764,27 @@ public class PlotConstructor extends ElementConstructor { ...@@ -807,6 +764,27 @@ public class PlotConstructor extends ElementConstructor {
} }
public String extraActivatedPlot(String updateKnowledge, String nextPlotLocation, List<String> activateExtraPlot){
JSONObject plot = null;
String location = "", lastTaskCondition = "", lastTaskReply = "", plotText = "", conditionName = "";
StringBuffer newUK = new StringBuffer(updateKnowledge);
for(String plotId:activateExtraPlot){
plot = plotIndex.get(plotId);
conditionName = plot.getString("conditionName");
location = plot.getString("location");
plotText = plotTextIndex.get(plotId);
lastTaskCondition = String.format(TASK_CONDITION, location);
lastTaskReply = String.format(TASK_REPLY, location);
newUK.append("-<-").append(lastTaskCondition).append(":").append(conditionName).append("-<-").append(lastTaskReply).append(":").append(plotText);
}
return newUK.toString();
}
} }
package com.qiwu.chatbotbackend.gameDesign;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.JConfig;
import com.qiwu.chatbotbackend.entity.UserInfo;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PlotConstructor2 extends ElementConstructor {
public static String ASSISTANT = "globalVariable_智能助手";
public static String ASSISTANT_EMOTION = "正常";
public static String TASK_DESCRIPTION = "globalVariable_任务";
public static String TALKER_PATTERN = "【%s@%s】";
String GAME_STEP_FORMAT = "%s_plot_%s";
JSONArray plots = null;
HashMap<String, ArrayList<String>> adjList = new HashMap<String, ArrayList<String>>();
HashMap<String, ArrayList<String>> revAdjList = new HashMap<String, ArrayList<String>>();
private HashMap<String, JSONObject> id2j = new HashMap<String, JSONObject>();
HashMap<String, Boolean> visited = new HashMap<String, Boolean>();
public static String TASK_LINE = "任务线_%s进度";
public static String TASK_CONDITION = "任务线%s最后一个condition";
public static String TASK_REPLY = "任务线%s最后的回答";
public HashMap<String, JSONObject> getId2j() {
return id2j;
}
public PlotConstructor2(SqlHelper helper, int botId, String botAccount, Map<String, StringBuffer> keywordMap, HashSet<String> exceptRelation, StringBuffer POS) {
super();
this.helper = helper;
this.botId = botId;
this.botAccount = botAccount;
this.exceptRelation = exceptRelation;
this.keywordMap = keywordMap;
this.POS = POS;
}
public void construct(JSONObject jsonObject, UserInfo userinfo) {
try {
addGameStartPlot(jsonObject, keywordMap);
JSONArray plots = jsonObject.getJSONArray("plots");
String start = (String) jsonObject.get("start"), startCondition;
JSONObject returnMessage = null;
this.plots = plots;
constructAdjList(plots);
if (id2j.containsKey(start)) {
String taskLineName = "任务线_" + id2j.get(start).get("place") + "进度";
conditionDescription.put(taskLineName, taskLineName);
if(jsonObject.get("firstUnknownText") == null)
varInitialMap.put("unknownText", "你说啥?");
else
varInitialMap.put("unknownText", (String)jsonObject.get("firstUnknownText"));
varInitialMap.put("game_step", String.format(GAME_STEP_FORMAT, botAccount, (String) id2j.get(start).get("id")));
conditionDescription.put("unknownText", "对于无法识别的问题做出的回答");
conditionDescription.put("game_step", "QA问答游戏进度");
BFSGenerate4(id2j.get(start), userinfo, jsonObject);
varInitialMap.put(start, "1");
} else {
System.out.println("start剧情不存在");
operationStatus = 0;
message = "开始剧情不存在,请到剧情列表设置";
return;
}
} catch(Exception e){
operationStatus = 0;
message = "剧情接口处理出现异常";
e.printStackTrace();
return;
}
}
//根据id构造邻接表
public void constructAdjList(JSONArray plots) {
int length = plots.size(), branchSize;
String id = "", nextPlotId = "";
JSONObject plot = null;
JSONArray branch = null;
for (int i = 0; i < length; i++) {
plot = plots.getJSONObject(i);
id = (String) plot.get("id");
plot.put("index", i);
if (adjList.get(id) == null) {
adjList.put(id, new ArrayList<>());
}
//添加branch中的下一个plot
branch = plot.getJSONArray("branch");
branchSize = branch.size();
for (int j = 0; j < branchSize; j++) {
nextPlotId = (String) branch.getJSONObject(j).get("nextPlotId");
if (revAdjList.get(nextPlotId) == null) {
revAdjList.put(nextPlotId, new ArrayList<>());
}
varSlotFilt(branch.getJSONObject(j), keywordMap);
adjList.get(id).add(nextPlotId);
revAdjList.get(nextPlotId).add(id);
}
id2j.put(id, plot);
}
}
/**
* 如果剧情文本中出现变量槽,那么需要判断这个剧情的npc是不是在线模式,如果不是在线模式,就需要把变量槽过滤掉
* @param branchNode
*/
public static void varSlotFilt(JSONObject branchNode, Map<String, StringBuffer> keywordMap){
String VARIABLE_SEARCH_PATTERN = "【(.*?)@(.*?)(\\$\\{.*?})", npcName, middleText = "", varSlot = "";
Pattern replacePattern = Pattern.compile(VARIABLE_SEARCH_PATTERN);
Matcher m = replacePattern.matcher(branchNode.getString("reply"));
while (m.find()) {
npcName = m.group(1);
//onlineModeTalkers, 在CharecterConstructor中定义,q前面加一个逗号是为了防止出现子串匹配的问题
//System.out.println("npcName" + npcName);
//System.out.println("varInitialMap.get(\"onlineModeTalkers\")" + varInitialMap.get("onlineModeTalkers"));
if(keywordMap.get("onlineModeTalkers").indexOf("," + npcName + ",") == -1) {
varSlot = m.group(3);
middleText = m.group(2);
branchNode.put("reply", branchNode.getString("reply").replace(npcName + "@" + middleText + varSlot, npcName + "@" + middleText));
}
}
}
/**
* 将所有剧情根据地点分为多条剧情线,每一条剧情线都有一个计数器,记录当前地点的剧情到了第几步。
* 加上剧情计数器, null时未激活,大于等于1时表示已激活
* @param root
* @param userinfo
*/
public void BFSGenerate4(JSONObject root, UserInfo userinfo, JSONObject jsonObject) {
String id, rootId = (String) root.get("id"), adjId, nextId, conditionName = "yaobuyao",
nextUnknownText, curUnknownText, nextCondition, location, nextLocation, nextGameStep, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition, reply;
String beforeJumpLocatin, jumpNextNextId, jumpNextNextLocation, extraBeforeJumpUK;
JSONObject node = null, branchNode = null, adjNode = null;
StringBuffer skipText = new StringBuffer();
String extraHP = "", extraUK = "", extraFT = "";
JSONArray branch = null;
int branchSize;
List<String> curPremiseList, historyPremiseList;
root.put("nextUnknownText", varInitialMap.get("unknownText"));
root.put("parentId", "null");
jsonObject.put("plotStartText", ((String)jsonObject.get("plotStartText")).replace("\n", "").replace(",", ","));
if(root.get("conditionName") != null && !root.get("conditionName").equals(""))
conditionName = (String)root.get("conditionName");
else{
conditionName = "yaobuyao";
root.put("conditionName", conditionName);
}
String startPlace = ((String)root.get("place")).split("\\+")[0];
String startTaskLine = String.format(PlotConstructor2.TASK_LINE, startPlace);
String startTaskCondition = String.format(PlotConstructor2.TASK_CONDITION, startPlace);
String startTaskReply = String.format(PlotConstructor2.TASK_REPLY, startPlace);
varInitialMap.put("site", startPlace);
varInitialMap.put(startTaskLine, rootId);
varInitialMap.put(startTaskCondition, "");
varInitialMap.put(startTaskReply, "");
conditionDescription.put(startTaskLine, startTaskLine);
conditionDescription.put(startTaskCondition,startTaskCondition);
conditionDescription.put(startTaskReply, startTaskReply);
//generateStartGame(root, jsonObject, startPlace, conditionName);
Queue<JSONObject> queue = new LinkedList<JSONObject>();
Map<String, String> autoJumpUpdateKnowledge = new HashMap<String, String >();
queue.add(root);
while (!queue.isEmpty()) {
node = queue.remove();
id = (String) node.get("id");
location = ((String) node.get("place")).split("\\+")[0];
conditionName = (String) node.get("conditionName");
curUnknownText = (String) node.get("nextUnknownText");
taskLineName = String.format(PlotConstructor2.TASK_LINE, location);
conditionDescription.put(id, "剧情" + id + "状态");
varInitialMap.put(id ,"");
//本任务线的最后一个condition和本任务线的最后一个回答
branch = node.getJSONArray("branch");
branchSize = branch.size();
for (int i = 0; i < branchSize; i++) {
System.out.println("branch:" + i);
skipText.setLength(0);
branchNode = branch.getJSONObject(i);
Map<String, String> updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class);
//System.out.println("id:" + id + "剧情分支:" + branchNode.toJSONString());
nextUnknownText = updateKnowledge.get("unknownText");
//System.out.println(id + "分支内" +nextUnknownText);
nextId = (String)branchNode.get("nextPlotId");
//skipText.append();
if(nextId == null || nextId.equals("") || !id2j.containsKey(nextId)){
nextId = id + "_end";
branchNode.put("nextPlotId", nextId);
createEndNode(node, id, nextId, curUnknownText);
}
//保留下一步剧情的地点
beforeJumpLocatin = ((String)id2j.get(nextId).get("place")).split("\\+")[0];
autoJumpUpdateKnowledge.clear();
/**
* 自动跳转到下一个剧情,因为有可能存在多步自动跳转,所以要用一个while来处理,
* 如果下一步剧情是自动跳转,那么把下一步剧情的更新答案(属性)移到当前剧情,并将下一步剧情id改为下下步剧情id
*/
while(branchNode.get("autoJump") != null && (boolean)branchNode.get("autoJump") && branchNode.get("nextPlotId") != null && !branchNode.get("nextPlotId").equals("")){
nextId = (String)branchNode.get("nextPlotId");
JSONObject jumpNextNode = id2j.get(nextId);
JSONObject jumpBranchNode = jumpNextNode.getJSONArray("branch").getJSONObject(0);
skipText.append((String)branchNode.get("reply"));
branchNode.put("reply", jumpBranchNode.get("reply"));
Map newUpdateKnowledge = jumpBranchNode.getJSONObject("updateKnowledge");
autoJumpUpdateKnowledge.putAll(newUpdateKnowledge);
nextUnknownText = (String)newUpdateKnowledge.get("unknownText");
System.out.println("循环内" +nextUnknownText);
//updateKnowledge.putAll(newUpdateKnowledge);
jumpNextNextId = (String)jumpBranchNode.get("nextPlotId");
//如果下一步剧情存在
if(jumpNextNextId != null && !jumpNextNextId.equals("") && id2j.containsKey(jumpNextNextId)){
System.out.println(jumpNextNextId);
System.out.println(id2j.get(jumpNextNextId));
jumpNextNextLocation = (String)id2j.get(jumpNextNextId).get("place");
autoJumpUpdateKnowledge.put("site", jumpNextNextLocation);
autoJumpUpdateKnowledge.put("npc_update", "updateFollowerLocation:" + jumpNextNextLocation);
branchNode.put("autoJump", jumpBranchNode.get("autoJump"));
}else {
jumpNextNextId = nextId + "_end";
jumpBranchNode.put("nextPlotId", jumpNextNextId);
createEndNode(node, nextId, jumpNextNextId, curUnknownText);
branchNode.put("autoJump", false);
}
branchNode.put("nextPlotId", jumpNextNextId);
}
nextId = (String) branchNode.get("nextPlotId");
reply = (String)branchNode.get("reply");
if(reply.equals(""))
reply = curUnknownText;
//如果存在下一剧情,就将下一步剧情的condition设为下一个激活的conditin,把地点更新为下一步剧情的地点,并更新任务线进度
nextCondition = (String) id2j.get(nextId).get("conditionName");
if(nextCondition.equals(""))
nextCondition = "yaobuyao";
nextLocation = ((String) id2j.get(nextId).get("place")).split("\\+")[0];
//任务线
nTaskLineName = String.format(TASK_LINE, nextLocation);
//任务线最后一个condition
lastTaskCondition = String.format(TASK_CONDITION, nextLocation);
lastTaskReply = String.format(TASK_REPLY, nextLocation);
/**
* 额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情
* 如果某个地点的剧情已经到结尾啦,那么有两种解决方法:
* 1: 将剧情停留在最后一步剧情
* 2. 设一个专门的剧情表示剧情的结尾
*/
//现在暂时放开下一步剧情未发生过的限制条件
//extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1 + "," + nextId + "::match-Include=null";
extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1;
extraUK = nTaskLineName + ":" + nextId + "-<-" + lastTaskCondition + ":" + nextCondition + "-<-" + lastTaskReply + ":" + reply +
"-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1" + "-<-plot_jump_text:" + skipText;
if(!beforeJumpLocatin.equals(nextLocation)) {
//extraBeforeJumpUK =
}
if(nextId.endsWith("_end"))
nextGameStep = id;
else
nextGameStep = nextId;
/**
* 1. 主角是否随剧情移动
* 如果随剧情移动,则更新地点和game_step
* 如果不随剧情移动,则不更新地点和game_step,添加中间配置"去XX",设高优先级,并更新状态
*
* 2. 当前条件是否为空
* 如果当前条件为空,则提交qa激活并进入下一步剧情
* 如果当前条件不为空,则需要满足条件才能进入下一步剧情
*
* 3. 下一部剧情是否为空
*
*
* 4. 有没有说去XX
*
* 主角不随剧情移动+当前条件为空+去沙滩
* 1、沙滩无剧情
* 2、沙滩有剧情
*
* 5. 地点变化
* 1. 当前所处地点
* 2. 下一步剧情所处地点(包含自动跳转的情况)
* 3. 自动跳转完成后的地点
*/
/**
* 自动跳转前的剧情也要记下来,这里是自动跳转前需要更新的变量(无论是否包含自动跳转都会更新)
* 1. 将自动跳转剧情的关联地点最后被激活的condition更新为yaobuyao (其实这一步是非必须的,)
* 2. 自动跳转剧情文本保存到beforeJumpTaskReply
* 3. 当前剧情和下一步剧情更新状态
*/
String beforeJumpTaskCondition = String.format(TASK_CONDITION, beforeJumpLocatin);
String beforeJumpTaskReply = String.format(TASK_REPLY, beforeJumpLocatin);
String beforeJumpUK = "-<-" + beforeJumpTaskCondition + ":yaobuyao" + "-<-" + beforeJumpTaskReply + ":" + skipText + "-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1" ;
//如果主角的位置随着剧情移动或者下一步剧情地点和当前剧情相同,主角地点和game_step要做相应更新
if((!branchNode.containsKey("moveWithPlot") || (Boolean)branchNode.get("moveWithPlot")) || location.equals(beforeJumpLocatin)) {
extraUK = beforeJumpUK + "-<-" + extraUK + "-<-site:" + nextLocation + "-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextGameStep);
//自动跳转剧情如果有更新属性,这些数据也需要更新
updateKnowledge.putAll(autoJumpUpdateKnowledge);
}else {
//任务线最后一个condition
/**
* 注意,比较的是当前地点和跳转前的地点
* 地点更新为跳转后的地点
*/
//可能因为不存在自动跳转或者地点不同,所以执行现在的代码,如果在剧情中存在自动跳转的情况,那么应该比较自动跳转完成后的地点喝下一步剧情的地点是否相同
if(!location.equals(beforeJumpLocatin)){
//System.out.println(id + "报异常" + curUnknownText);
if(curUnknownText.equals("")) {
reply = "请到" + beforeJumpLocatin;
//如果当前地点和下一步剧情地点不同,要提示
}else {
reply = curUnknownText;
}
//如果下一步剧情和当前剧情的地点是不一样的,那么在玩家没有到达下一个地点是剧情还是停留在当前剧情,只有到达目的地后,下一步剧情才会发生变化
jConfig = new JConfig(
"yaobuyao::match-Keyword=+" + beforeJumpLocatin,
"game_step::match-Include=" + String.format(GAME_STEP_FORMAT, botAccount, id) + "," + id + "::number-BiggerOrEqual=" + 1,
"match", (String)branchNode.get("reply"), (String) nextCondition,
extraUK + "-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextGameStep)
+ "-<-unknownText:" + nextUnknownText + "-<-site:" + nextLocation + "-<-npc_update:updateFollowerLocation:"+ nextLocation, autoJumpUpdateKnowledge
);
jConfig.setStatus("sleeping");
jConfig.setConfigName("plot_" + beforeJumpLocatin + "_" + id,false);
jConfig.setjStatus(1);
jConfigList.add(jConfig);
//如果当前剧情所在地喝下一步剧情所在地不一样,那么unknown文本
//只有到达下一步剧情所在地时才会更新
updateKnowledge.remove("unknownText");
updateKnowledge.remove("site");
extraUK = beforeJumpUK;
//如果下一步剧情不在同一地点,那么即使有跳转剧情,也是在下一个地点才说
skipText.setLength(0);
//必须在上一个jConfig添加完之后
//extraUK = extraUK.replace("-<-" + nextId + ":" + "+1", "");
}
}
curPremiseList = JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class);
historyPremiseList = JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class);
extraFT = "";
//是否将当前识别到的数据加入到已知数据列表
if((Boolean)branchNode.get("includeCurInfo")){
extraFT += ",includeCurInfo";
}
if(branchNode.get("extraFeature") != null){
extraFT += "," + branchNode.getString("extraFeature");
}
jConfig = new JConfig(
curPremiseList,
historyPremiseList,
updateKnowledge,
"", extraHP, extraUK,
"match"+extraFT, reply, (String) nextCondition, "1"
);
//当剧情没有条件限制时的操作
if (curPremiseList.size() == 0 && historyPremiseList.size() == 0){
unconditionalPlotProcess(jConfig, nextCondition);
}
if (branchNode.getBoolean("higherPriority") != null && branchNode.getBoolean("higherPriority"))
jConfig.setAuxiliaryPriority("3");
jConfigList.add(jConfig);
//将子结点加入队列
adjId = (String) branchNode.get("nextPlotId");
if (visited.get(adjId) == null && id2j.get(adjId) != null) {
visited.put(adjId, true);
adjNode = id2j.get(adjId);
adjNode.put("parentId", id);
//System.out.println("下一个剧情id:" + adjId + ",nextUnknownText:" + nextUnknownText);
adjNode.put("nextUnknownText", nextUnknownText);
queue.add(adjNode);
} else {
conditionDescription.put(adjId, "剧情" + adjId + "进度");
varInitialMap.put(adjId, "");
}
}
}
/**
* ----------------------------------------------------------------------------------------------------
* 不设剧情不设条件时的处理
* 1. 如果qa返回大于90则回答common_answer+ 剧情回答,并进入下一步剧情,这里的下一步condition是从激活之前保存的临时变量中读取出来的
* 2. 如果qa返回小于90则只回答剧情文本
* 3. 如果qa返回not_found则只回答剧情文本
* 4. 无论哪种情况都会跳下一步剧情
*/
jConfig = new JConfig(
" ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}"
);
jConfig.setStatus("sleeping");
jConfig.setConfigName("queryskip1",false);
jConfig.setjStatus(1);
jConfig.setAuxiliaryPriority("0");
jConfigList.add(jConfig);
jConfig = new JConfig(
" ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}"
);
jConfig.setStatus("sleeping");
jConfig.setConfigName("queryskip2",false);
jConfig.setjStatus(1);
jConfig.setAuxiliaryPriority("0");
jConfigList.add(jConfig);
jConfig = new JConfig(
" ", "qa_status::match-Include=not_found", "match", "{临时变量reply-2}", " ", "process-nextStep:var={临时变量condition-2}"
);
jConfig.setStatus("sleeping");
jConfig.setConfigName("queryskip3",false);
jConfig.setjStatus(1);
jConfig.setAuxiliaryPriority("0");
jConfigList.add(jConfig);
/**
* ----------------------------------------------------------------------------------------------------
* 待激活列表,用于qa问答
*/
//处于激活状态,其他的属于待激活状态,jStatus这一条不设为1,而是0
jConfig = new JConfig(" ", " ", "activate,post::gameQA(" + keywordMap.get("QA_URL").toString()+ ")", "", "unknown4,unknown3,unknown2,unknown1,common_answer", "");
jConfig.setNextStepStatus("active");
jConfig.setAuxiliaryPriority("0");
jConfigList.add(jConfig);
jConfig = new JConfig(
" ", "qa_status::match-Include=not_found", "match,return-0", "{unknownText-2}", " ", ""
);
jConfig.setStatus("sleeping");
jConfig.setConfigName("unknown1",false);
jConfig.setjStatus(1);
jConfig.setAuxiliaryPriority("0");
jConfigList.add(jConfig);
jConfig = new JConfig(
" ", "qa_status::match-Include=not_found,unknownText::match-Include=null", "match,return-0",
"不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧",
" ", ""
);
jConfig.setStatus("sleeping");
jConfig.setConfigName("unknown2",false);
jConfig.setjStatus(1);
jConfig.setAuxiliaryPriority("0");
jConfigList.add(jConfig);
jConfig = new JConfig(
" ", "qa_status::match-Include=OK,qa_score::number-Smaller=90,unknownText::match-Include=null", "match,return-0",
"不好意思,我没听懂你刚才说的话,请换个别的问题试试吧~哎呀,刚才开了小差,没理解你的意思,请换个问题吧~请根据上文信息,认真回答吧,谢谢~我们好像不在一个频道上,换个问题试试,希望我们能够接轨上吧",
" ", ""
);
jConfig.setStatus("sleeping");
jConfig.setConfigName("unknown3",false);
jConfig.setjStatus(1);
jConfig.setAuxiliaryPriority("0");
jConfigList.add(jConfig);
jConfig = new JConfig(
" ", "qa_status::match-Include=OK,qa_score::number-Smaller=90", "match,return-0", "{unknownText-2}", " ", ""
);
jConfig.setStatus("sleeping");
jConfig.setConfigName("unknown4",false);
jConfig.setjStatus(1);
jConfig.setAuxiliaryPriority("0");
jConfigList.add(jConfig);
//由于剧情跳转时地点可能发生变化, qa问答的句子可能因为npc不再同一位置而被过滤掉,所以将common_answer的字符串合并放在postprocessing中
jConfig = new JConfig(
" ", "qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=90", "match,return-0", "" ," ", ""
);
jConfig.setStatus("sleeping");
jConfig.setConfigName("common_answer",false);
jConfig.setjStatus(1);
jConfig.setAuxiliaryPriority("0");
jConfigList.add(jConfig);
//---------------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------------
/**
* ----------------------------------------------------------------------------------------------------
* 用于存档
*/
jConfig = new JConfig(
"save_game::match-Include=+要:存档", " ", "match,return-0,gameBackup", "{archiveOperation-2}" ," ", ""
);
jConfig.setAuxiliaryPriority("4");
jConfigList.add(jConfig);
}
/**
* 游戏开始的配置
*/
public void generateStartGame(JSONObject root, JSONObject jsonObject, String startPlace, String conditionName){
//用于开始游戏的配置
jConfig = new JConfig(
"start_options::match-Include=+开始+开始游戏+继续游戏+继续+重新开始",
"任务线" + startPlace + "最后一个condition::match-Include=+null",
"match",
(String)jsonObject.get("plotStartText"),
conditionName,
"任务线" + startPlace + "最后一个condition:" + conditionName + "-<-" + root.get("id") + ":+1" +
"-<-任务线" + startPlace + "最后的回答:" + (String)jsonObject.get("plotStartText") + "-<-" + String.format(TASK_LINE, startPlace) + ":" + root.get("id")
);
jConfig.setAuxiliaryPriority("2");
jConfigList.add(jConfig);
jConfig = new JConfig(
" ",
"任务线" + startPlace + "最后一个condition::match-Include=+null",
"match",
"请说开始游戏或者继续游戏",
"start_options",
""
);
jConfig.setAuxiliaryPriority("2");
jConfigList.add(jConfig);
}
@Override
public void postProcessing(List<Integer> idList, int categoryId){
}
public void createEndNode(JSONObject node, String id, String nextId, String nextUnknownText){
String condition = (String) node.get("conditionName");
String location = ((String) node.get("place")).split("\\+")[0];
String nextCondition = condition;
String nextLocation = location;
String nTaskLineName = String.format(TASK_LINE, nextCondition);
JSONObject endNode = new JSONObject();
endNode.put("place", location);
endNode.put("conditionName", condition);
endNode.put("id", nextId);
endNode.put("reply", nextUnknownText);
endNode.put("includeCurInfo", true);
endNode.put("updateKnowledge", new ArrayList());
id2j.put(nextId, endNode);
visited.put(nextId, true);
}
void addGameStartPlot(JSONObject gameElements, Map<String, StringBuffer> keywordMap){
// JSONObject startPlot = new JSONObject();
// startPlot.put("id", "start");
// startPlot.put("conditionName", "start_options");
// startPlot.put("place", "哪呢? 还没开始呢");
// startPlot.put("branch", new JSONArray());
//
// JSONObject branch1 = new JSONObject();
// branch1.put("curPremise", new JSONArray(){
// {
// add("start_options::match-Include=+重新开始");
// }
// });
//
// branch1.put("higherPriority", true);
// branch1.put("hisPremise", new JSONArray());
// branch1.put("extraFeature", "newGame");
// branch1.put("reply", gameElements.get("plotStartText"));
// branch1.put("updateKnowledge", new JSONObject(){
// {
// put("unknownText", gameElements.get("firstUnknownText"));
// }
// });
// branch1.put("nextPlotId", gameElements.get("start"));
// branch1.put("includeCurInfo", false);
//
//
//
// startPlot.getJSONArray("branch").add(branch1);
//
//
// JSONObject branch2 = new JSONObject();
// branch2.put("curPremise", new JSONArray(){
// {
// add("start_options::match-Include=+开始+开始游戏+继续游戏+继续");
// }
// });
//
// branch2.put("higherPriority", true);
// branch2.put("hisPremise", new JSONArray());
// branch2.put("reply", gameElements.get("plotStartText"));
// branch2.put("updateKnowledge", new JSONObject(){
// {
// put("unknownText", gameElements.get("firstUnknownText"));
// }
// });
// branch2.put("extraFeature", "loadLastArchive");
// branch2.put("nextPlotId", gameElements.get("start"));
// branch2.put("includeCurInfo", false);
// if(gameElements.get("startAutoJump") != null)
// branch2.put("autoJump", gameElements.get("startAutoJump"));
// else
// branch2.put("autoJump", false);
// startPlot.getJSONArray("branch").add(branch2);
//
//
// gameElements.getJSONArray("plots").add(startPlot);
// gameElements.put("start", "start");
// gameElements.put("firstUnknownText", "请说开始游戏或者继续游戏");
File file = null;
FileReader fr = null;
BufferedReader br = null;
try {
file = new File("gameconfig.txt");
fr = new FileReader(file);
br = new BufferedReader(fr);
String jsonStr = br.readLine();
jsonStr = jsonStr.replace("startAutoJump", gameElements.getString("startAutoJump"));
jsonStr = jsonStr.replace("firstUnknownText", gameElements.getString("firstUnknownText"));
jsonStr = jsonStr.replace("plotStartText", gameElements.getString("plotStartText"));
jsonStr = jsonStr.replace("startId", gameElements.getString("start"));
jsonStr = jsonStr.replace("site_list", keywordMap.get("site_list").toString());
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.put("start", "start1");
gameElements.put("firstUnknownText", "请说开始游戏或者继续游戏");
br.close();
fr.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//如果是无条件剧情,那么需要跟着一个激活操作
public void unconditionalPlotProcess(JConfig jConfig, String nextCondition){
jConfig.setFeature(jConfig.getFeature() + ",activate,post::gameQA(" + keywordMap.get("QA_URL").toString() + ")");
jConfig.setNextStep("queryskip*,map*,item*,npc*");
jConfig.setUpdateKnowledge(jConfig.getUpdateKnowledge() + "-<-临时变量condition:"+ nextCondition +"-<-临时变量reply:var={reply-3}");
jConfig.setNextStepStatus("active");
}
public void appendPremise(StringBuffer premiseStr, String conditionName, String cmpType, String operator, String value){
int strLen = premiseStr.length();
if(strLen == 0 || strLen == 1){
premiseStr = new StringBuffer();
}else{
premiseStr.append(",");
}
premiseStr.append(conditionName);
premiseStr.append("::");
premiseStr.append(cmpType);
premiseStr.append("-");
premiseStr.append(operator);
premiseStr.append("=");
premiseStr.append(value);
}
public void appendKnowledge(StringBuffer knowledgeStr, String key, String value){
knowledgeStr.append("-<-");
knowledgeStr.append(key);
knowledgeStr.append(":");
knowledgeStr.append(value);
}
}
package com.qiwu.chatbotbackend.processing; package com.qiwu.chatbotbackend.processing;
import com.qiwu.chatbotbackend.GameEnvironment.GameEnv;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.qiwu.chatbotbackend.GameEnvironment.GameEnv;
import com.qiwu.chatbotbackend.GameEnvironment.ObjectFileUtil; import com.qiwu.chatbotbackend.GameEnvironment.ObjectFileUtil;
import com.qiwu.chatbotbackend.entity.ChatCache3; import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.ArchiveInfo;
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.*;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.*; import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class ChatCacheController { public class ChatCacheController {
public static long TIME_OUT = 300000; public static long TIME_OUT = 300000;
private static String CHAT_CACHE_DIR = "ChatCache"; private static String CHAT_CACHE_DIR = "ChatCache/";
//private static String ENV_PATH = CHAT_CACHE_DIR + "%s-%s-%s-env.data";
//private static String INFO_PATH = CHAT_CACHE_DIR + "%s-%s-%s-info.data";
private static String ENV_PATH = CHAT_CACHE_DIR + "%s-env.data";
private static String INFO_PATH = CHAT_CACHE_DIR + "%s-info.data";
public static synchronized boolean saveChatCache(String chatKey, ChatCache3 chatCache) throws IOException { private static String ARCHIVE_NAME = "%s-%s-%s";
LocalDateTime now = LocalDateTime.now(); private static String ENV_PATH = CHAT_CACHE_DIR + "%s-%s-%s-env.data";
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); private static String INFO_PATH = CHAT_CACHE_DIR + "%s-%s-%s-info.data";
String nowStr = now .format(format); private static String ENV_POSTFIX = "-env.data";
private static String INFO_POSTFIX = "-info.data";
public static String COMBINE_PUNC1 = "@@@";
public static String COMBINE_PUNC2 = "@@@@";
boolean saveFlag = true;
try { /**
File dir = new File(CHAT_CACHE_DIR); * 通过chat_key获得后台保存的历史信息点
if (!dir.exists()) * chatCache:存储了chatKye相对应的对话记录(历史信息点)
dir.mkdir(); *
* @return 历史信息点,对话过程中引擎提取的用户信息
*/
public static synchronized ChatCache getChatCache(String userKey, String randKey, ServletContext context, UserInfo userinfo, Map<String, String[]> receiveParamters, Boolean loadCacheStatus) throws Exception {
Map<String, ChatCache> chatCacheMap = null;
ChatCache chatCache = null;
ObjectFileUtil.writeObjectToFile(chatCache.getGameEnv(), String.format(ENV_PATH, chatKey)); if (context.getAttribute("chatCache") == null) {
chatCacheMap = new HashMap<String, ChatCache>();
context.setAttribute("chatCache", chatCacheMap);
} else {
chatCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache");
}
File file = new File(String.format(INFO_PATH, chatKey));
FileWriter fw = new FileWriter(file);
String jsonString = JSON.toJSONString(chatCache.getInfoPoint()); try {
fw.write(jsonString); chatCache = chatCacheMap.get(userKey);
fw.close();
//如果用户之前没有玩过或者有一段时间没有玩
if(chatCache == null){
chatCache = new ChatCache(userinfo, userKey, randKey);
chatCacheMap.put(userKey, chatCache);
//用户几分钟前还在玩
} else {
if( !chatCache.getRandKey().equals(randKey)) { //同一个用户的不同一次会话, 保存上一次会话
//当用户id和随机对话id不同时,表示用户为登录状态,用户登录且开始游戏,则可以存档
if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isGameStart()) {
ChatCacheController.saveChatCache(chatCache, null);
}
chatCache = new ChatCache(userinfo, userKey, randKey);
chatCacheMap.put(userKey, chatCache);
}
}
//historyInfoPoint = (Map<String, String>) context.getAttribute("chat_key+"+userinfo.userName);
} catch (Exception e) { } catch (Exception e) {
System.out.println("游戏存档时发生异常"); //可整合
e.printStackTrace(); e.printStackTrace();
saveFlag = false; chatCache = new ChatCache(userinfo, userKey, randKey);
chatCacheMap.put(userKey, chatCache);
} }
return saveFlag; return chatCache;
} }
public static synchronized ChatCache3 loadChatCache(String chatKey, ServletContext context, UserInfo userInfo, Boolean loadCacheStatus) throws Exception {
ChatCache3 chatCache = null;
GameEnv gameEnv = null;
Map<String ,String> infoPoint = null;
String fileDir = System.getProperty("user.dir") + "/ChatCache";
String line, pair[]; public static synchronized boolean saveChatCache(ChatCache chatCache, SqlHelper helper) throws IOException {
Map<String, String> infoPoints = new HashMap<String, String>(); LocalDateTime now = LocalDateTime.now();
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
String nowTime = now .format(format);
Boolean opFlag;
System.out.println("游戏存档中");
String userKey = chatCache.getUserKey();
String site = chatCache.getInfoPoint().get("site");
String archiveName = String.format(ARCHIVE_NAME, userKey, site, nowTime);
try { try {
File file = new File(String.format(ENV_PATH, chatKey));
if (file.exists()){ if(helper == null){
gameEnv = (GameEnv) ObjectFileUtil.readObjectFromFile(String.format(ENV_PATH, chatKey)); helper = new SqlHelper();
}else{
throw new IOException("环境存档不存在");
} }
File dir = new File(CHAT_CACHE_DIR);
if (!dir.exists())
dir.mkdir();
file = new File(String.format(INFO_PATH, chatKey));
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String jsonStr = br.readLine();
infoPoint = (Map)JSON.parseObject(jsonStr);
chatCache = new ChatCache3(chatKey, gameEnv, infoPoint);
chatCache.setReloading(true);
br.close();
fr.close();
loadCacheStatus = true; ObjectFileUtil.writeObjectToFile(chatCache.getGameEnv(), String.format(ENV_PATH, userKey, site, nowTime));
File file = new File(String.format(INFO_PATH, userKey, site, nowTime));
FileWriter fw = new FileWriter(file);
} catch (IOException e) { String jsonString = JSON.toJSONString(chatCache.getInfoPoint());
System.out.println(e.toString()); fw.write(jsonString);
chatCache = new ChatCache3(userInfo); fw.close();
loadCacheStatus = false;
opFlag = helper.insertArchiveInfo(archiveName, userKey, site);
} catch (Exception e) {
System.out.println("游戏存档时发生异常");
e.printStackTrace();
opFlag = false;
} }
return chatCache; return opFlag;
} }
public static synchronized ChatCache3 loadChatCache2(String userKey, ServletContext context, UserInfo userInfo, Boolean loadCacheStatus) throws Exception {
ChatCache3 chatCache = null; public static synchronized ChatCache loadChatCache(ArchiveInfo archiveInfo) throws Exception {
ChatCache chatCache = null;
GameEnv gameEnv = null; GameEnv gameEnv = null;
Map<String ,String> infoPoint = null; Map<String ,String> infoPoint = null;
String keys[] = archiveInfo.getArchiveId().split(COMBINE_PUNC1);
keys[1] = keys[1].split("-")[0];
String fileDir = System.getProperty("user.dir") + "/ChatCache"; String fileDir = System.getProperty("user.dir") + "/ChatCache";
String line, pair[]; String line, pair[];
Map<String, String> infoPoints = new HashMap<String, String>(); Map<String, String> infoPoints = new HashMap<String, String>();
try { try {
File file = new File(String.format(ENV_PATH, userKey)); File file = new File(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + ENV_POSTFIX);
if (file.exists()){ if (file.exists()){
gameEnv = (GameEnv) ObjectFileUtil.readObjectFromFile(String.format(ENV_PATH, userKey)); gameEnv = (GameEnv) ObjectFileUtil.readObjectFromFile(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + ENV_POSTFIX);
}else{ }else{
throw new IOException("环境存档不存在"); throw new IOException("环境存档不存在");
} }
file = new File(String.format(INFO_PATH, userKey)); file = new File(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + INFO_POSTFIX);
FileReader fr = new FileReader(file); FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr); BufferedReader br = new BufferedReader(fr);
String jsonStr = br.readLine(); String jsonStr = br.readLine();
infoPoint = (Map)JSON.parseObject(jsonStr); infoPoint = (Map)JSON.parseObject(jsonStr);
chatCache.setReloading(true); chatCache = new ChatCache(keys[0], keys[1], gameEnv, infoPoint);
chatCache.setGameStart(true);
br.close(); br.close();
fr.close(); fr.close();
loadCacheStatus = true;
} catch (IOException e) { } catch (IOException e) {
System.out.println(e.toString()); System.out.println(e.toString());
chatCache = new ChatCache3(userInfo);
loadCacheStatus = false;
} }
return chatCache; return chatCache;
...@@ -143,117 +179,42 @@ public class ChatCacheController { ...@@ -143,117 +179,42 @@ public class ChatCacheController {
/**
* 通过chat_key获得后台保存的历史信息点
* chatCache:存储了chatKye相对应的对话记录(历史信息点)
*
* @return 历史信息点,对话过程中引擎提取的用户信息
*/
public static synchronized ChatCache3 getChatCache(String chatKey, ServletContext context, UserInfo userinfo, Map<String, String[]> receiveParamters, Boolean loadCacheStatus) throws Exception {
Map<String, ChatCache3> chatCacheMap = null;
ChatCache3 chatCache = null;
if (context.getAttribute("chatCache") == null) {
chatCacheMap = new HashMap<String, ChatCache3>();
//chatCacheMap.put(chatKey, new ChatCache(userinfo));
context.setAttribute("chatCache", chatCacheMap);
} else {
chatCacheMap = (Map<String, ChatCache3>) context.getAttribute("chatCache");
}
String chatkey;
try {
chatCache = chatCacheMap.get(chatKey);
HashSet<String> startKeySet = new HashSet<String>(){
{
add("开始");
add("开始剧情");
add("继续");
add("继续剧情");
}
};
HashSet<String> restartKeySet = new HashSet<String>(){
{
add("重新开始");
add("新游戏");
}
};
//如果用户之前没有玩过或者有一段时间没有玩
if(chatCache == null){
//识别到的语义关系包含start_options
if(receiveParamters.containsKey("start_options")){
String startKeyword = receiveParamters.get("start_options")[0].split(":", 2)[1];
//有继续游戏相关的关键词
if(startKeySet.contains(startKeyword)) {
//加载存档
chatCache = loadChatCache(chatKey, context, userinfo, loadCacheStatus);
//没有继续游戏相关的关键词
}else {
chatCache = new ChatCache3(userinfo);
}
}else {
chatCache = new ChatCache3(userinfo);
}
chatCacheMap.put(chatKey, chatCache);
//用户几分钟前还在玩
} else {
//将重新加载的标识重置
chatCache.setReloading(false);
//识别到的语义关系包含start_options
if(receiveParamters.containsKey("start_options")){
String startKeyword = receiveParamters.get("start_options")[0].split(":", 2)[1];
if(startKeySet.contains(startKeyword)) {
chatCache.setReloading(true);
}else if(restartKeySet.contains(startKeyword)){
chatCache = new ChatCache3(userinfo);
}
}
}
//historyInfoPoint = (Map<String, String>) context.getAttribute("chat_key+"+userinfo.userName);
} catch (Exception e) {
//可整合
chatCache = new ChatCache3(userinfo);
}
return chatCache;
}
/** /**
* chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据 * chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据
*/ */
public static synchronized void updateChatCache4Delete(String curChatKey, ServletContext context, UserInfo userInfo) throws IOException { public static synchronized void updateChatCache4Delete(String userKey, ServletContext context, UserInfo userInfo) throws IOException {
String chatKey; String sessionKey;
ChatCache3 chatCache = null; ChatCache chatCache = null;
SqlHelper helper = null;
long lastChatTime, now; long lastChatTime, now;
Map<String, String> history = new HashMap<String, String>(); Map<String, String> history = new HashMap<String, String>();
Map<String, ChatCache3> chatCacheMap = (Map<String, ChatCache3>) context.getAttribute("chatCache"); Map<String, ChatCache> chatCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache");
try {
Iterator<String> it = chatCacheMap.keySet().iterator(); Iterator<String> it = chatCacheMap.keySet().iterator();
while (it.hasNext()) { while (it.hasNext()) {
chatKey = it.next(); sessionKey = it.next();
if(curChatKey.equals(chatKey)) { if (sessionKey.equals(userKey)) {
saveChatCache(chatKey, chatCacheMap.get(chatKey)); saveChatCache(chatCacheMap.get(sessionKey),null);
continue; continue;
} }
history = chatCacheMap.get(chatKey).getInfoPoint(); history = chatCacheMap.get(sessionKey).getInfoPoint();
lastChatTime = Long.valueOf(history.get("lastUpdateTime")); lastChatTime = Long.valueOf(history.get("lastUpdateTime"));
now = System.currentTimeMillis(); now = System.currentTimeMillis();
if (now - lastChatTime > ChatCacheController.TIME_OUT) { if (now - lastChatTime > ChatCacheController.TIME_OUT) {
chatCache = chatCacheMap.get(chatKey); chatCache = chatCacheMap.get(sessionKey);
saveChatCache(chatKey, chatCache);
System.out.println("移除" + chatKey); if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isGameStart()) {
saveChatCache(chatCache, null);
}
System.out.println("移除" + sessionKey);
it.remove(); it.remove();
} }
} }
}catch (Exception e){
e.printStackTrace();
}
context.setAttribute("chatCache", chatCacheMap); context.setAttribute("chatCache", chatCacheMap);
} }
...@@ -262,32 +223,28 @@ public class ChatCacheController { ...@@ -262,32 +223,28 @@ public class ChatCacheController {
*/ */
public static synchronized void updateChatCache4Insert(Map<String, String> curInfoPoint, Map<String, String> historyInfoPoint, GameEnv gameEnv, ServletContext context, UserInfo userInfo) { public static synchronized void updateChatCache4Insert(Map<String, String> curInfoPoint, Map<String, String> historyInfoPoint, GameEnv gameEnv, ServletContext context, UserInfo userInfo) {
historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis()));
Map<String, ChatCache3> keyCacheMap = (Map<String, ChatCache3>) context.getAttribute("chatCache"); Map<String, ChatCache> keyCacheMap = (Map<String, ChatCache>) context.getAttribute("chatCache");
ChatCache3 chatCache = keyCacheMap.get(curInfoPoint.get("chat_key")); ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("userKey"));
chatCache.setInfoPoint(historyInfoPoint); chatCache.setInfoPoint(historyInfoPoint);
chatCache.setGameEnv(gameEnv); chatCache.setGameEnv(gameEnv);
context.setAttribute("chatCache", keyCacheMap); context.setAttribute("chatCache", keyCacheMap);
} }
public static synchronized boolean findChatCache(String chatKey, ServletContext context, String botAccount) throws Exception { public static synchronized boolean findChatCache(String userKey, ServletContext context, String botAccount) throws Exception {
ChatCache3 chatCache = null; ChatCache chatCache = null;
GameEnv gameEnv = null; GameEnv gameEnv = null;
ArchiveInfo archiveInfo = null;
Map<String ,String> infoPoint = null; Map<String ,String> infoPoint = null;
String fileDir = System.getProperty("user.dir") + "/ChatCache"; String fileDir = System.getProperty("user.dir") + "/ChatCache";
String line, pair[]; String line, pair[];
SqlHelper helper;
Map<String, String> infoPoints = new HashMap<String, String>(); Map<String, String> infoPoints = new HashMap<String, String>();
try { try {
if (context.getAttribute("chatCache") != null) {
if (((HashMap<String, ChatCache3>)context.getAttribute("chatCache")).get(chatKey) != null){ helper = new SqlHelper();
return true; archiveInfo = helper.queryUserLastGameArchive(userKey);
}
}
File file = new File(String.format(ENV_PATH, chatKey));
if (file.exists()){
return true;
}
} catch(Exception e){ } catch(Exception e){
...@@ -295,14 +252,14 @@ public class ChatCacheController { ...@@ -295,14 +252,14 @@ public class ChatCacheController {
return false; return false;
} }
return false; return archiveInfo != null;
} }
public static synchronized boolean deleteUnuseChatCache(String chatKey, ServletContext context) throws Exception { public static synchronized boolean deleteUnuseChatCache(String chatKey, ServletContext context) throws Exception {
try { try {
System.out.println("移除----------------------------"); System.out.println("移除----------------------------");
HashMap<String, ChatCache3> chatCacheHashMap = (HashMap<String, ChatCache3>)context.getAttribute("chatCache"); HashMap<String, ChatCache> chatCacheHashMap = (HashMap<String, ChatCache>)context.getAttribute("chatCache");
chatCacheHashMap.remove(chatKey); chatCacheHashMap.remove(chatKey);
} catch(Exception e){ } catch(Exception e){
...@@ -313,30 +270,6 @@ public class ChatCacheController { ...@@ -313,30 +270,6 @@ public class ChatCacheController {
return true; return true;
} }
public static synchronized List<File> queryChatCacheBySite(String key, String site) {
String findPattern = String.format(ENV_PATH, key, site, ".*?");
List<File> fileList = FileFinder.findFiles(CHAT_CACHE_DIR, findPattern);
Comparator<File> FILES_BY_MODEFIED_DATE = new Comparator<File>() {
@Override
public int compare(File object1, File object2) {
long d1 = object1.lastModified();
long d2 = object2.lastModified();
if (d1 == d2) {
return 0;
} else {
return d1 < d2 ? 1 : -1;
}
}
};
fileList.sort(FILES_BY_MODEFIED_DATE);
return fileList;
}
......
...@@ -235,7 +235,7 @@ public class FormsPoster { ...@@ -235,7 +235,7 @@ public class FormsPoster {
} }
} else { } else {
logWriter.record(textscore + "没找到npc名字", 1); logWriter.record(textscore + "没找到npc名字", 1);
historyInfoPoint.put("common_answer", ResponseFilter.appendTalker((String)textscore.get(0), curInfoPoint, historyInfoPoint, gameEnv, worldController)); historyInfoPoint.put("common_answer", ResponseFilter.appendTalker((String)textscore.get(0), historyInfoPoint, gameEnv, worldController));
historyInfoPoint.put("qa_score", String.valueOf(textscore.get(1))); historyInfoPoint.put("qa_score", String.valueOf(textscore.get(1)));
break; break;
} }
......
...@@ -55,7 +55,7 @@ public class QuestionMatcher { ...@@ -55,7 +55,7 @@ public class QuestionMatcher {
/** /**
* 用迭代器迭代当前信息点中的非空关键字,由conditionName索引到状态表中保存包含conditionName这个条件的列表,并查询状态表中的条件是否满足及其优先级,满足条件且优先级更高就设为bestMatch * 用迭代器迭代当前信息点中的非空关键字,由conditionName索引到状态表中保存的包含conditionName这个条件的列表,并查询状态表中的条件是否满足,优先级是否更高,满足条件且优先级更高就设为bestMatch
* *
* @param conditionTable 满足什么条件,就回答什么,下一步跳什么 * @param conditionTable 满足什么条件,就回答什么,下一步跳什么
* @return bestMatch 状态表中满足条件最多的一条 * @return bestMatch 状态表中满足条件最多的一条
......
...@@ -5,9 +5,7 @@ import com.qiwu.chatbotbackend.entity.Condition; ...@@ -5,9 +5,7 @@ import com.qiwu.chatbotbackend.entity.Condition;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import com.qiwu.chatbotbackend.gameDesign.PlotConstructor; import com.qiwu.chatbotbackend.gameDesign.PlotConstructor;
import java.util.ArrayList; import java.util.*;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
...@@ -31,7 +29,7 @@ public class ResponseFilter { ...@@ -31,7 +29,7 @@ public class ResponseFilter {
reply = MyFunc.randStr(reply.split("~")); reply = MyFunc.randStr(reply.split("~"));
if(reply.endsWith("开始游戏或者继续游戏")){ if(reply.endsWith("请说开始剧情或者继续剧情")){
return reply; return reply;
} }
...@@ -44,7 +42,7 @@ public class ResponseFilter { ...@@ -44,7 +42,7 @@ public class ResponseFilter {
}else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1){ }else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1){
return reply; return reply;
}else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0 && !reply.equals("")){ }else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0 && !reply.equals("")){
return appendTalker(reply,curInfoPoint, historyInfoPoint, gameEnv, worldController); return appendTalker(reply, historyInfoPoint, gameEnv, worldController);
}else if (reply.equals("") && ( }else if (reply.equals("") && (
(historyInfoPoint.get("common_answer") != null && !historyInfoPoint.get("common_answer").equals(""))) (historyInfoPoint.get("common_answer") != null && !historyInfoPoint.get("common_answer").equals("")))
|| (historyInfoPoint.get("map_query") != null && !historyInfoPoint.get("map_query").equals("")) || (historyInfoPoint.get("map_query") != null && !historyInfoPoint.get("map_query").equals(""))
...@@ -63,50 +61,51 @@ public class ResponseFilter { ...@@ -63,50 +61,51 @@ public class ResponseFilter {
String lastTalker = ""; String lastTalker = "";
//如果作者当前地点和剧情所在地点相同,那么回答unknown文本的人必须是上个剧情中的人 //如果作者当前地点和剧情所在地点相同,那么回答unknown文本的人必须是上个剧情中的人
if(historyInfoPoint.get("game_step").endsWith(historyInfoPoint.get(String.format(PlotConstructor.TASK_LINE, site)))){ // if(historyInfoPoint.get("game_step").endsWith(historyInfoPoint.get(String.format(PlotConstructor.TASK_LINE, site)))){
Matcher m = findTalker(historyInfoPoint.get(String.format(PlotConstructor.TASK_REPLY, site))); // Matcher m = findTalker(historyInfoPoint.get(String.format(PlotConstructor.TASK_REPLY, site)));
while(m.find()) { // while(m.find()) {
//回答unknown文本的npc必须处于在线模式 // //回答unknown文本的npc必须处于在线模式
npc = m.group(1); // npc = m.group(1);
if(historyInfoPoint.get("onlineModeTalkers").contains("," + npc + ",")) { // if(isOnlineMode(npc, historyInfoPoint)) {
lastTalker = npc; // lastTalker = npc;
}else{ // }else{
System.out.println(npc + "是离线模式"); // System.out.println(npc + "是离线模式");
} // }
} // }
//
for (String ans : userInfo.varInitialMap.get("unknownTextList").split("~")) { // for (String ans : userInfo.varInitialMap.get("unknownTextList").split("~")) {
if (ans.equals("")) // if (ans.equals(""))
continue; // continue;
if (ans.contains(lastTalker) &&sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1) { // if (ans.contains(lastTalker) &&sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1) {
//
unknownList.add(ans); // if(isOnlineText(ans, historyInfoPoint))
//return ans; // unknownList.add(ans);
} else if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0) { // //return ans;
unknownList.add(appendTalker(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController)); // } else if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0) {
} // unknownList.add(appendTalker(ans, historyInfoPoint, gameEnv, worldController));
} // }
if (unknownList.size() > 0) { // }
return MyFunc.randStr(unknownList); // if (unknownList.size() > 0) {
} // return MyFunc.randStr(unknownList);
// }
}else { //
// }else {
for (String ans : userInfo.varInitialMap.get("unknownTextList").split("~")) { for (String ans : userInfo.varInitialMap.get("unknownTextList").split("~")) {
if (ans.equals("")) if (ans.equals(""))
continue; continue;
if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1) { if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1) {
if(isOnlineText(ans, historyInfoPoint))
unknownList.add(ans); unknownList.add(ans);
//return ans; //return ans;
} else if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0) { } else if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0) {
unknownList.add(appendTalker(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController)); unknownList.add(appendTalker(ans, historyInfoPoint, gameEnv, worldController));
} }
} }
if (unknownList.size() > 0) { if (unknownList.size() > 0) {
return MyFunc.randStr(unknownList); return MyFunc.randStr(unknownList);
} }
} // }
} }
if(userInfo.varInitialMap.get("finalUnknownText") != null){ if(userInfo.varInitialMap.get("finalUnknownText") != null){
...@@ -118,10 +117,11 @@ public class ResponseFilter { ...@@ -118,10 +117,11 @@ public class ResponseFilter {
if(ans.equals("")) if(ans.equals(""))
continue; continue;
if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1){ if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1){
if(isOnlineText(ans, historyInfoPoint))
finalUnknownList.add(ans); finalUnknownList.add(ans);
//return ans; //return ans;
}else if(sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0){ }else if(sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0){
finalUnknownList.add(appendTalker(ans,curInfoPoint, historyInfoPoint, gameEnv, worldController)); finalUnknownList.add(appendTalker(ans, historyInfoPoint, gameEnv, worldController));
} }
} }
if(finalUnknownList.size() > 0){ if(finalUnknownList.size() > 0){
...@@ -148,7 +148,7 @@ public class ResponseFilter { ...@@ -148,7 +148,7 @@ public class ResponseFilter {
* 查看回答文本的说话这是否在当前地点 * 查看回答文本的说话这是否在当前地点
* 0:没有说话者 * 0:没有说话者
* 1:说话者在当前地点 * 1:说话者在当前地点
* 2:说话者不在当前地点 * 2:说话者不在当前地点或者不能说话
* @param reply * @param reply
* @param curInfoPoint * @param curInfoPoint
* @param historyInfoPoint * @param historyInfoPoint
...@@ -158,9 +158,6 @@ public class ResponseFilter { ...@@ -158,9 +158,6 @@ public class ResponseFilter {
* @param logWriter * @param logWriter
* @return * @return
*/ */
static Integer sameLocation(String reply, Map<String ,String> curInfoPoint, Map<String ,String> historyInfoPoint, GameEnv gameEnv, WorldController worldController, String site, LogWriter logWriter){ static Integer sameLocation(String reply, Map<String ,String> curInfoPoint, Map<String ,String> historyInfoPoint, GameEnv gameEnv, WorldController worldController, String site, LogWriter logWriter){
String npc, location; String npc, location;
...@@ -190,17 +187,50 @@ public class ResponseFilter { ...@@ -190,17 +187,50 @@ public class ResponseFilter {
} }
static String appendTalker(String reply, Map<String ,String> curInfoPoint, Map<String ,String> historyInfoPoint, GameEnv gameEnv, WorldController worldController){ /**
* 在头部没有【%s@%s】的文本加上【%s@%s】
* @param reply
* @param historyInfoPoint
* @param gameEnv
* @param worldController
* @return
*/
static String appendTalker(String reply, Map<String ,String> historyInfoPoint, GameEnv gameEnv, WorldController worldController){
List<String> npcList = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site")); List<String> npcList = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site"));
String npc = ""; String npc = "";
if(npcList.size() != 0) List<String> filtedNpcList = new ArrayList<String>();
npc = MyFunc.randStr(npcList);
for(String npcName:npcList){
if(isOnlineMode(npcName, historyInfoPoint)) {
filtedNpcList.add(npcName);
}else{
System.out.println(npcName + "是离线模式");
}
}
if(filtedNpcList.size() != 0)
npc = MyFunc.randStr(filtedNpcList);
else else
npc = historyInfoPoint.get(PlotConstructor.ASSISTANT); npc = historyInfoPoint.get(PlotConstructor.ASSISTANT);
return "【" + npc + "@0】" + reply;
return String.format(TALKER_PATTERN, npc, PlotConstructor.ASSISTANT_EMOTION) + reply;
}
static Boolean isOnlineMode(String npc, Map<String, String> historyInfoPoint){
return historyInfoPoint.get("onlineModeTalkers").contains("," + npc + ",");
}
static Boolean isOnlineText(String text, Map<String, String> historyInfoPoint){
Matcher m = findTalker(text);
String npc = "";
if(m.find()) {
npc = m.group(1);
return historyInfoPoint.get("onlineModeTalkers").contains("," + npc + ",");
}else{
System.out.println("竟然没找到npc");
return false;
}
} }
} }
//package com.qiwu.chatbotbackend.processing;
//
//import com.qiwu.chatbotbackend.GameEnvironment.GameEnv;
//import com.qiwu.chatbotbackend.entity.Condition;
//import com.qiwu.chatbotbackend.entity.UserInfo;
//import com.qiwu.chatbotbackend.gameDesign.PlotConstructor;
//
//import java.util.ArrayList;
//import java.util.List;
//import java.util.Map;
//import java.util.regex.Matcher;
//import java.util.regex.Pattern;
//
//import static com.qiwu.chatbotbackend.gameDesign.PlotConstructor.TALKER_PATTERN;
//import static com.qiwu.chatbotbackend.processing.FormsPoster.TALKER;
//
//public class ResponseFilter3 {
//
// static String filt(Map<String ,String> curInfoPoint, Map<String ,String> historyInfoPoint, GameEnv gameEnv, WorldController worldController,
// String reply, UserInfo userInfo, Condition ansCondition, LogWriter logWriter){
// String botType = userInfo.varInitialMap.get("botType"), npc, finalUnknownText;
//
//
// if(botType == null || botType.equals("")){
// return reply;
//
// }else if (botType.equals("game")){
//
// String site = historyInfoPoint.get("site");
//
//
// reply = MyFunc.randStr(reply.split("~"));
//
// if(reply.endsWith("开始游戏或者继续游戏")){
// return reply;
// }
//
//
// //如果剧情跳转中包含了自动跳转的文本,那么不判断是否处于同一地点
//// if(historyInfoPoint.get("plot_jump_text") != null && !historyInfoPoint.get("plot_jump_text").equals("")){
//// return reply;
//// }
//
// if(reply.startsWith(String.format(TALKER_PATTERN, PlotConstructor.ASSISTANT, PlotConstructor.ASSISTANT_EMOTION)) ){
// return reply;
// }else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1){
// return reply;
// }else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0 && !reply.equals("")){
// return appendTalker(reply, historyInfoPoint, gameEnv, worldController);
//
// //如果回答为空但是有qa回答、地图物品npc查询结果则允许返回空文本,否则往下漏,取unknown文本
// }else if (reply.equals("") && (
// (historyInfoPoint.get("common_answer") != null && !historyInfoPoint.get("common_answer").equals("")))
// || (historyInfoPoint.get("map_query") != null && !historyInfoPoint.get("map_query").equals(""))
// || (historyInfoPoint.get("goods_query") != null && !historyInfoPoint.get("goods_query").equals("") )
// || (historyInfoPoint.get("npc_query") != null && !historyInfoPoint.get("npc_query").equals(""))
// ){
// return reply;
// }
//
//
//
// if(userInfo.varInitialMap.get("unknownTextList") != null){
// List<String> unknownList = new ArrayList<String>();
//
// String lastTalker = "";
// Boolean onlyLastTalker = false;
// //如果作者当前地点和剧情所在地点相同,那么回答unknown文本的人必须是上个剧情中的人
// if(historyInfoPoint.get("game_step").endsWith(historyInfoPoint.get(String.format(PlotConstructor.TASK_LINE, site)))){
//// Matcher m = findTalker(historyInfoPoint.get(String.format(PlotConstructor.TASK_REPLY, site)));
//// while(m.find()) {
//// //回答unknown文本的npc必须处于在线模式
//// npc = m.group(1);
//// if(isOnlineMode(npc, historyInfoPoint)) {
//// //找到最后一个说话且处于离线模式的npc
//// lastTalker = npc;
//// }else{
//// System.out.println(npc + "是离线模式");
//// }
//// }
// lastTalker = findPlotLastTalker(historyInfoPoint.get(String.format(PlotConstructor.TASK_REPLY, site)), site, historyInfoPoint, gameEnv, logWriter);
// if(!lastTalker.equals("") && userInfo.varInitialMap.get("unknownTextList").contains(lastTalker))
// onlyLastTalker = true;
//
// for (String ans : userInfo.varInitialMap.get("unknownTextList").split("~")) {
// if (ans.equals(""))
// continue;
// if (ans.contains(lastTalker) && onlyLastTalker) {
//
// unknownList.add(ans);
// //return ans;
// } else if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0) {
// unknownList.add(appendTalker(ans, historyInfoPoint, gameEnv, worldController));
// }
// }
// if (unknownList.size() > 0) {
// return MyFunc.randStr(unknownList);
// }
//
// }else {
//
// for (String ans : userInfo.varInitialMap.get("unknownTextList").split("~")) {
// if (ans.equals(""))
// continue;
// if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1) {
//
// unknownList.add(ans);
// //return ans;
// } else if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0) {
// unknownList.add(appendTalker(ans, historyInfoPoint, gameEnv, worldController));
// }
// }
// if (unknownList.size() > 0) {
// return MyFunc.randStr(unknownList);
// }
// }
// }
//
//
// //最终unknown文本
// if(userInfo.varInitialMap.get("finalUnknownText") != null){
// finalUnknownText = userInfo.varInitialMap.get("finalUnknownText");
// List<String> finalUnknownList = new ArrayList<String>();
//
//
// for(String ans:finalUnknownText.split("~")){
// if(ans.equals(""))
// continue;
// if (sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 1){
// finalUnknownList.add(ans);
// //return ans;
// }else if(sameLocation(ans, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0){
// finalUnknownList.add(appendTalker(ans, historyInfoPoint, gameEnv, worldController));
// }
// }
// if(finalUnknownList.size() > 0){
// return MyFunc.randStr(finalUnknownList);
//
// }
// }
//
// }
//
//
// return "找不到匹配文本";
// }
//
//
//
// static Matcher findTalker(String reply){
// Pattern findTalker = Pattern.compile(TALKER);
// Matcher m = findTalker.matcher(reply);
//
// return m;
// }
// /**
// * 查看回答文本的说话这是否在当前地点
// * 0:没有说话者
// * 1:说话者在当前地点
// * 2:说话者不在当前地点
// * @param reply
// * @param curInfoPoint
// * @param historyInfoPoint
// * @param gameEnv
// * @param worldController
// * @param site
// * @param logWriter
// * @return
// */
// static Integer sameLocation(String reply, Map<String ,String> curInfoPoint, Map<String ,String> historyInfoPoint, GameEnv gameEnv, WorldController worldController, String site, LogWriter logWriter, Boolean needOnline){
// String npc, location;
//
// Matcher m = findTalker(reply);
// int flag = 1;
// if(m.find()) {
// npc = m.group(1);
// flag = npcIsSameLocation(npc, site, reply, historyInfoPoint, gameEnv, logWriter);
// }else{
// logWriter.record("\"" + reply + "\":没有npc名",1 );
// flag = 0;
// }
// return flag;
//
// }
//
// static Integer npcIsSameLocation(String npc, String site, String reply, Map<String ,String> historyInfoPoint, GameEnv gameEnv, LogWriter logWriter){
// Integer flag;
// String location = gameEnv.queryNpcAttrByNpcName(npc, "location");
// //String location = worldController.worldOperation(gameEnv, "npc_query", "queryLocationByNPCName:" + npc, curInfoPoint, historyInfoPoint);
// if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){
// if((gameEnv.queryNpcAttrByNpcName(npc, "能否说话") == null || gameEnv.queryNpcAttrByNpcName(npc, "能否说话").equals("能"))){
// flag = 1;
// logWriter.record("\"" + reply + "\":匹配", 1);
// }else {
// flag = 2;
// logWriter.record(npc + "不能说话或者是离线模式", 1);
// }
//
// }else {
// logWriter.record("\"" + reply + "\":" + npc +"不在" + site + ",跳过",1 );
// flag = 2;
// }
//
// return flag;
// }
//
// /**
// * 在头部没有【%s@%s】的文本加上【%s@%s】
// * @param reply
// * @param historyInfoPoint
// * @param gameEnv
// * @param worldController
// * @return
// */
// static String appendTalker(String reply, Map<String ,String> historyInfoPoint, GameEnv gameEnv, WorldController worldController){
//
// List<String> npcList = gameEnv.queryAroundNpcBySite(historyInfoPoint.get("site"));
// String npc = "";
// List<String> filtedNpcList = new ArrayList<String>();
//
// for(String npcName:npcList){
// if(isOnlineMode(npcName, historyInfoPoint)) {
// filtedNpcList.add(npcName);
// }else{
// System.out.println(npcName + "是离线模式");
// }
// }
// if(filtedNpcList.size() != 0)
// npc = MyFunc.randStr(filtedNpcList);
// else
// npc = historyInfoPoint.get(PlotConstructor.ASSISTANT);
//
//
// return String.format(TALKER_PATTERN, npc, PlotConstructor.ASSISTANT_EMOTION);
//
// }
//
// static Boolean isOnlineMode(String npc, Map<String, String> historyInfoPoint){
// return historyInfoPoint.get("onlineModeTalkers").contains("," + npc + ",");
// }
//
// public static String findPlotLastTalker(String text, String site, Map<String, String> historyInfoPoint, GameEnv gameEnv, LogWriter logWriter){
// Matcher m = findTalker(text);
// String npc, lastTalker = "";
// while(m.find()) {
// //回答unknown文本的npc必须处于在线模式
// npc = m.group(1);
// //处于离线模式 可以说话 相同地点
// if(isOnlineMode(npc, historyInfoPoint) && npcIsSameLocation(npc, site, npc, historyInfoPoint, gameEnv, logWriter) == 1) {
// //找到最后一个说话且处于离线模式的npc
// lastTalker = npc;
// }else{
// System.out.println(npc + "是离线模式");
// }
// }
//
// return lastTalker;
// }
//
//}
package com.qiwu.chatbotbackend.servlet; package com.qiwu.chatbotbackend.servlet;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.processing.ChatCacheController2; import com.qiwu.chatbotbackend.processing.ChatCacheController;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import javax.servlet.ServletException; import javax.servlet.ServletException;
...@@ -24,7 +24,7 @@ public class FindCacheServlet extends HttpServlet { ...@@ -24,7 +24,7 @@ public class FindCacheServlet extends HttpServlet {
Boolean exist = false; Boolean exist = false;
try { try {
exist = ChatCacheController2.findChatCache(userKey, context, botAccount); exist = ChatCacheController.findChatCache(userKey, context, botAccount);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
......
...@@ -133,15 +133,15 @@ public class GameDesignServlet extends HttpServlet { ...@@ -133,15 +133,15 @@ public class GameDesignServlet extends HttpServlet {
switch (moduleName) { switch (moduleName) {
case "map": case "map":
moduleName2 = "地图"; moduleName2 = "地图";
constructor = new MapConstructor2(helper, botId, botAccount, keywordMap, exceptRelation, POS); constructor = new MapConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS);
constructor.construct(gameElements, userinfo); constructor.construct(gameElements, userinfo);
break; break;
case "plots": case "plots":
moduleName2 = "剧情"; moduleName2 = "剧情";
constructor = new PlotConstructor(helper, botId, botAccount, keywordMap, exceptRelation, POS); constructor = new PlotConstructor2(helper, botId, botAccount, keywordMap, exceptRelation, POS);
constructor.construct(gameElements, userinfo); constructor.construct(gameElements, userinfo);
root = ((PlotConstructor) constructor).getId2j().get((String) gameElements.get("start")); root = ((PlotConstructor2) constructor).getId2j().get((String) gameElements.get("start"));
break; break;
case "goods": case "goods":
moduleName2 = "物品"; moduleName2 = "物品";
......
...@@ -91,7 +91,7 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -91,7 +91,7 @@ public class GetAnswerServlet extends HttpServlet {
Boolean loadCacheStatus = Boolean.valueOf(false); Boolean loadCacheStatus = Boolean.valueOf(false);
try { try {
//chatCache = ChatCacheController.getChatCache2(userKey, randKey, context, userinfo, receiveParamters, loadCacheStatus); //chatCache = ChatCacheController.getChatCache2(userKey, randKey, context, userinfo, receiveParamters, loadCacheStatus);
chatCache = ChatCacheController2.getChatCache(userKey, randKey, context, userinfo, receiveParamters, loadCacheStatus); chatCache = ChatCacheController.getChatCache(userKey, randKey, context, userinfo, receiveParamters, loadCacheStatus);
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} catch (Exception e) { } catch (Exception e) {
...@@ -158,12 +158,12 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -158,12 +158,12 @@ public class GetAnswerServlet extends HttpServlet {
matcher.infoTransfer(bestMatch, context, debugFlag); matcher.infoTransfer(bestMatch, context, debugFlag);
ChatCacheController2.updateChatCache4Insert(curInfoPoint, chatCache.getInfoPoint(), chatCache.getGameEnv(), context, userinfo); ChatCacheController.updateChatCache4Insert(curInfoPoint, chatCache.getInfoPoint(), chatCache.getGameEnv(), context, userinfo);
//清理超时的用户数据 //清理超时的用户数据
if (context.getAttribute("cacheUpdateTime") == null) if (context.getAttribute("cacheUpdateTime") == null)
context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); context.setAttribute("cacheUpdateTime", System.currentTimeMillis());
if (System.currentTimeMillis() - (long) context.getAttribute("cacheUpdateTime") > ChatCacheController2.TIME_OUT) { if (System.currentTimeMillis() - (long) context.getAttribute("cacheUpdateTime") > ChatCacheController.TIME_OUT) {
ChatCacheController2.updateChatCache4Delete(chatKey, context, userinfo); ChatCacheController.updateChatCache4Delete(chatKey, context, userinfo);
context.setAttribute("cacheUpdateTime", System.currentTimeMillis()); context.setAttribute("cacheUpdateTime", System.currentTimeMillis());
} }
......
...@@ -2,7 +2,7 @@ package com.qiwu.chatbotbackend.servlet; ...@@ -2,7 +2,7 @@ package com.qiwu.chatbotbackend.servlet;
import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.ChatCache; import com.qiwu.chatbotbackend.entity.ChatCache;
import com.qiwu.chatbotbackend.processing.ChatCacheController2; import com.qiwu.chatbotbackend.processing.ChatCacheController;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextEvent;
...@@ -38,7 +38,10 @@ public class MyListener implements ServletContextListener { ...@@ -38,7 +38,10 @@ public class MyListener implements ServletContextListener {
try { try {
helper = new SqlHelper(); helper = new SqlHelper();
System.out.println(String.format("saving %s", chatKey)); System.out.println(String.format("saving %s", chatKey));
ChatCacheController2.saveChatCache(cache, helper); //当用户id和随机对话id不同时,表示用户为登录状态,用户登录且开始游戏,则可以存档
if(cache != null && !cache.getRandKey().equals(cache.getUserKey()) && cache.isGameStart()) {
ChatCacheController.saveChatCache(cache, helper);
}
}catch (Exception e){ }catch (Exception e){
System.out.println(String.format("保存%s时出现异常", chatKey)); System.out.println(String.format("保存%s时出现异常", chatKey));
} }
......
...@@ -2,7 +2,7 @@ package com.qiwu.chatbotbackend.servlet; ...@@ -2,7 +2,7 @@ package com.qiwu.chatbotbackend.servlet;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.entity.ChatCache; import com.qiwu.chatbotbackend.entity.ChatCache;
import com.qiwu.chatbotbackend.processing.ChatCacheController2; import com.qiwu.chatbotbackend.processing.ChatCacheController;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import javax.servlet.ServletException; import javax.servlet.ServletException;
...@@ -27,8 +27,8 @@ public class SaveChatCacheServlet extends HttpServlet { ...@@ -27,8 +27,8 @@ public class SaveChatCacheServlet extends HttpServlet {
ChatCache chatCache = chatCacheMap.get(chatKey); ChatCache chatCache = chatCacheMap.get(chatKey);
if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isReloading()) { if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isGameStart()) {
flag = ChatCacheController2.saveChatCache(chatCache, null); flag = ChatCacheController.saveChatCache(chatCache, null);
chatCacheMap.remove(chatKey); chatCacheMap.remove(chatKey);
} }
......
...@@ -5,7 +5,6 @@ import com.qiwu.chatbotbackend.db.SqlHelper; ...@@ -5,7 +5,6 @@ import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.*; import com.qiwu.chatbotbackend.entity.*;
import com.qiwu.chatbotbackend.gameDesign.PlotConstructor; import com.qiwu.chatbotbackend.gameDesign.PlotConstructor;
import com.qiwu.chatbotbackend.processing.ChatCacheController; import com.qiwu.chatbotbackend.processing.ChatCacheController;
import com.qiwu.chatbotbackend.processing.ChatCacheController2;
import com.qiwu.chatbotbackend.processing.LogWriter; import com.qiwu.chatbotbackend.processing.LogWriter;
import com.qiwu.chatbotbackend.processing.WorldController; import com.qiwu.chatbotbackend.processing.WorldController;
...@@ -88,6 +87,8 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -88,6 +87,8 @@ public class GameBotUtil extends BasicBotUtil{
} }
} }
//将自动跳转文本、qa文本、查询文本拼接
String queryList[] = { "plot_jump_text" ,"common_answer","map_query", "goods_query", "npc_query"}; String queryList[] = { "plot_jump_text" ,"common_answer","map_query", "goods_query", "npc_query"};
String queryResult; String queryResult;
for(String queryName:queryList){ for(String queryName:queryList){
...@@ -215,13 +216,13 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -215,13 +216,13 @@ public class GameBotUtil extends BasicBotUtil{
if(ansCondition.featureMap.containsKey("newGame")) { if(ansCondition.featureMap.containsKey("newGame")) {
System.out.println("newGame"); System.out.println("newGame");
this.chatCache.setReloading(true); this.chatCache.setGameStart(true);
}else if (ansCondition.featureMap.containsKey("gameBackup")) { }else if (ansCondition.featureMap.containsKey("gameBackup")) {
System.out.println("gameBackup"); System.out.println("gameBackup");
if(! userKey.equals(randKey)) { //两者不同时表示用户已登录,才有权限存档 if(! userKey.equals(randKey)) { //两者不同时表示用户已登录,才有权限存档
chatCache = new ChatCache(userKey, randKey, gameEnv, historyInfoPoint); chatCache = new ChatCache(userKey, randKey, gameEnv, historyInfoPoint);
flag = ChatCacheController2.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
...@@ -235,6 +236,7 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -235,6 +236,7 @@ public class GameBotUtil extends BasicBotUtil{
System.out.println("loadLastArchive"); System.out.println("loadLastArchive");
ArchiveInfo archiveInfo = helper.queryUserLastGameArchive(userKey); ArchiveInfo archiveInfo = helper.queryUserLastGameArchive(userKey);
loading(archiveInfo, solution); loading(archiveInfo, solution);
this.chatCache.setGameStart(true);
} else if (ansCondition.featureMap.containsKey("loadArchiveBySite")) { } else if (ansCondition.featureMap.containsKey("loadArchiveBySite")) {
System.out.println("loadArchiveBySite"); System.out.println("loadArchiveBySite");
...@@ -243,6 +245,7 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -243,6 +245,7 @@ public class GameBotUtil extends BasicBotUtil{
System.out.println("要读取的存档的地点是:" + site); System.out.println("要读取的存档的地点是:" + site);
ArchiveInfo archiveInfo = helper.queryUserLastGameArchiveBySite(userKey, site); ArchiveInfo archiveInfo = helper.queryUserLastGameArchiveBySite(userKey, site);
loading(archiveInfo, solution); loading(archiveInfo, solution);
this.chatCache.setGameStart(true);
}else{ }else{
System.out.println("没有识别到" + LOAD_BY_SITE_CONDITION); System.out.println("没有识别到" + LOAD_BY_SITE_CONDITION);
} }
...@@ -261,9 +264,14 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -261,9 +264,14 @@ public class GameBotUtil extends BasicBotUtil{
String keyword = "", site; String keyword = "", site;
ChatCache loadCache = null; ChatCache loadCache = null;
//如果存在读档,就要将自动跳转和qa的临时数据清空
historyInfoPoint.put("plot_jump_text", "");
historyInfoPoint.put("common_answer", "");
if (archiveInfo != null) { if (archiveInfo != null) {
try { try {
loadCache = ChatCacheController2.loadChatCache(archiveInfo); loadCache = ChatCacheController.loadChatCache(archiveInfo);
} catch (Exception e) { } catch (Exception e) {
System.out.println("从本地加载存档失败"); System.out.println("从本地加载存档失败");
solution.setAnswer("从本地加载存档失败"); solution.setAnswer("从本地加载存档失败");
...@@ -271,8 +279,6 @@ public class GameBotUtil extends BasicBotUtil{ ...@@ -271,8 +279,6 @@ public class GameBotUtil extends BasicBotUtil{
} }
this.chatCache.setInfoPoint(loadCache.getInfoPoint()); this.chatCache.setInfoPoint(loadCache.getInfoPoint());
this.chatCache.setGameEnv(loadCache.getGameEnv()); this.chatCache.setGameEnv(loadCache.getGameEnv());
// this.historyInfoPoint = chatCache.getInfoPoint();
// this.gameEnv = chatCache.getGameEnv();
System.out.println("----------读档中------------"); System.out.println("----------读档中------------");
......
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