Commit 2555aef0 by hxw

删除全局变量分类,程序中断时自动保存对话数据

parent ab892f2f
......@@ -30,9 +30,13 @@ public class ChatCache implements DisposableBean {
this.reloading = reloading;
}
public String getChatKey() { return chatKey; }
public String getChatKey() {
return chatKey;
}
public void setChatKey(String chatKey) { this.chatKey = chatKey; }
public void setChatKey(String chatKey) {
this.chatKey = chatKey;
}
public Map<String, String> getInfoPoint() {
return infoPoint;
......@@ -50,14 +54,13 @@ public class ChatCache implements DisposableBean {
this.gameEnv = gameEnv;
}
public ChatCache(String chatKey, GameEnv gameEnv, Map<String, String> infoPoint){
public ChatCache(String chatKey, GameEnv gameEnv, Map<String, String> infoPoint) {
this.chatKey = chatKey;
this.gameEnv = gameEnv;
this.infoPoint = infoPoint;
}
@Override
public void destroy() throws IOException {
//System.out.println("销毁:" + chatKey);
......@@ -67,7 +70,7 @@ public class ChatCache implements DisposableBean {
public ChatCache(UserInfo userInfo) throws Exception {
try {
gameEnv = new GameEnv(userInfo.botAccount);
}catch (Exception e){
} catch (Exception e) {
System.out.println("游戏平台初始化失败");
e.printStackTrace();
}
......@@ -82,4 +85,11 @@ public class ChatCache implements DisposableBean {
infoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis()));
}
@PreDestroy
public void dostory() {
System.out.println("I'm destory method using @PreDestroy.....");
}
}
......@@ -213,6 +213,18 @@ public class JConfig implements Cloneable{
this.nextStep = nextStep;
}
public JConfig(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge, Map<String, String> autoJumpUpdateKnowledge) {
this.curPremise = curPremise;
this.hisPremise = hisPremise;
this.feature = feature;
this.updateKnowledge = appendKnowledgeStr(autoJumpUpdateKnowledge, updateKnowledge);
//if (!updateKnowledge.equals(""))
// this.updateKnowledge += "updateKnowledge-<-" + updateKnowledge;
this.reply = reply;
this.nextStep = nextStep;
}
public JConfig(List<String> curPremise, List<String> hisPremise, Map<String, String> updateKnowledge, String extraCP, String extraHP, String extraUK, String feature, String reply, String nextStep, String auxiliaryPriority) {
this.curPremise = appendPremiseStr(curPremise, extraCP);
......
......@@ -5,7 +5,6 @@ import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.JConfig;
import com.qiwu.chatbotbackend.entity.UserInfo;
import org.apache.commons.lang.StringUtils;
import java.util.*;
......
......@@ -123,8 +123,48 @@ public class ElementConstructor {
}
}
for(Map premise:JSONArray.parseArray(config.getJSONArray("historyPremiseList").toJSONString(), Map.class)){
conditionName = (String) premise.get("actionName");
if(conditionName.startsWith("npc_") || conditionName.startsWith("goods_"))
continue;
if(!exceptRelation.contains(conditionName)) {
if(!relationKeywords.containsKey(conditionName + "_head")) {
relationKeywords.put(conditionName + "_head", new HashSet<String>());
relationKeywords.put(conditionName + "_tail", new HashSet<String>());
}
premise.put("keywords", ((String)premise.get("keywords")).replace("qiwu", "#visitorname").replace(botName, "#botname"));
for (String keyword : ((String) premise.get("keywords")).split("\\+")) {
if(keyword.equals("")){
continue;
} else if(keyword.contains(":")){
pair = keyword.split(":",2);
if(pair[1].equals(""))
continue;
relationKeywords.get(conditionName + "_head").add(pair[0]);
relationKeywords.get(conditionName + "_tail").add(pair[1]);
} else {
relationKeywords.get(conditionName + "_tail").add(keyword);
}
}
}
}
}
/**
* 根据插入的数据做后处理
* @param idList
......
......@@ -37,7 +37,7 @@ public class GlobalVariableConstructor extends ElementConstructor {
for(String attrName:attribute.keySet()) {
attrValue = attribute.get(attrName);
varInitialMap.put("globalVariable_" + category + "_" + attrName, attrValue);
varInitialMap.put("globalVariable_" + attrName, attrValue);
}
}
......
......@@ -5,7 +5,6 @@ import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.JConfig;
import com.qiwu.chatbotbackend.entity.UserInfo;
import org.apache.commons.lang.StringUtils;
import java.util.*;
......
......@@ -181,8 +181,6 @@ public class MapConstructor extends ElementConstructor {
operationStatus = 0;
e.printStackTrace();
message = "地图处理出现异常:";
e.printStackTrace();
message += e.getMessage();
return;
}
......@@ -396,6 +394,10 @@ public class MapConstructor extends ElementConstructor {
}
/**
* 生成‘周围有什么人’所需要的配置文件
*/
public void generateSurroundingPeople(Map<String, StringBuffer> keywordMap){
String conditionName = "know_exist_what";
String conditionKeywords = keywordMap.get("people_" + conditionName).toString();
......@@ -408,6 +410,10 @@ public class MapConstructor extends ElementConstructor {
}
/**
* 生成‘周围有什么物品’所需要的配置文件
*/
public void generateSurroundingItem(Map<String, StringBuffer> keywordMap){
String conditionName = "know_exist_what";
String conditionKeywords = keywordMap.get("item_" + conditionName).toString();
......@@ -421,6 +427,10 @@ public class MapConstructor extends ElementConstructor {
}
/**
* 生成‘周围有什么(包含人和物品)’所需要的配置文件
*/
public void generateSurroundThings(Map<String, StringBuffer> keywordMap){
String conditionName = "know_exist_what_mohu";
String conditionKeywords = keywordMap.get("things_" + conditionName).toString();
......@@ -433,6 +443,10 @@ public class MapConstructor extends ElementConstructor {
}
/**
* 生成‘周围有什么地点’所需要的配置文件
*/
public void generateSurroundPlace(Map<String, StringBuffer> keywordMap){
String conditionName = "know_exist_what";
String conditionKeywords = keywordMap.get("place_" + conditionName).toString();
......@@ -446,6 +460,11 @@ public class MapConstructor extends ElementConstructor {
}
/**
* 生成‘我们有什么’所需要的配置文件
*/
public void generateWeHave(Map<String, StringBuffer> keywordMap){
String conditionName = "know_exist_what_mohu";
String conditionKeywords = keywordMap.get("we_have_" + conditionName).toString();
......@@ -459,6 +478,11 @@ public class MapConstructor extends ElementConstructor {
}
/**
* 生成‘里面有什么人’所需要的配置文件
*/
public void generateInnerPeople(Map<String, StringBuffer> keywordMap){
......@@ -479,6 +503,11 @@ public class MapConstructor extends ElementConstructor {
}
/**
* 生成‘我们的任务是什么’所需要的配置文件
*/
public void generateTaskDescription(Map<String, StringBuffer> keywordMap){
......
......@@ -5,11 +5,7 @@ import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.JConfig;
import com.qiwu.chatbotbackend.entity.UserInfo;
import com.qiwu.chatbotbackend.processing.FormsPoster;
import org.apache.http.message.BasicNameValuePair;
import com.qiwu.chatbotbackend.processing.MyFunc;
import java.io.UnsupportedEncodingException;
import java.util.*;
import static com.qiwu.chatbotbackend.processing.FormsPoster.QA_URL;
......@@ -17,8 +13,8 @@ import static com.qiwu.chatbotbackend.processing.FormsPoster.QA_URL;
public class PlotConstructor extends ElementConstructor {
public static String ASSISTANT = "globalVariable_默认_智能助手";
public static String TASK_DESCRIPTION = "globalVariable_默认_任务";
public static String ASSISTANT = "globalVariable_智能助手";
public static String TASK_DESCRIPTION = "globalVariable_任务";
public static String TALKER_PATTERN = "【%s】";
String GAME_STEP_FORMAT = "%s_plot_%s";
......@@ -39,7 +35,7 @@ public class PlotConstructor extends ElementConstructor {
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();
this.helper = helper;
this.botId = botId;
......@@ -56,6 +52,7 @@ public class PlotConstructor extends ElementConstructor {
String start = (String) jsonObject.get("start"), startCondition;
JSONObject returnMessage = null;
this.plots = plots;
constructAdjList(plots);
......@@ -73,15 +70,11 @@ public class PlotConstructor extends ElementConstructor {
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;
......@@ -93,7 +86,8 @@ public class PlotConstructor extends ElementConstructor {
} catch(Exception e){
operationStatus = 0;
message = "地图接口处理出现异常";
message = "剧情接口处理出现异常";
e.printStackTrace();
return;
}
}
......@@ -139,23 +133,30 @@ public class PlotConstructor extends ElementConstructor {
* @param userinfo
*/
public void BFSGenerate4(JSONObject root, UserInfo userinfo, JSONObject jsonObject) {
String id, rootId = (String) root.get("id"), adjId, nextId, parentId, taskName = "", value = "", extraHP = "", extraUK = "", nextTaskName, keywordOptions, conditionName = "yaobuyao",
nextUnknownText, curUnknownText, nextCondition, location, nextLocation, jumpLocation, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition, reply;
boolean newBranch, manyParent, autoJump;
String id, rootId = (String) root.get("id"), adjId, nextId, parentId, taskName = "", value = "", nextTaskName, keywordOptions, 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();
StringBuffer skipText = null;
//StringBuffer extraHP = new StringBuffer(), extraUK = new StringBuffer(), extraFT = new StringBuffer();
String extraHP = "", extraUK = "", extraFT = "";
JSONArray branch = null;
List<String> adjNodeList = null;
int priority, taskStep, nextPriority, nextTaskStep, 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];
......@@ -167,80 +168,62 @@ public class PlotConstructor extends ElementConstructor {
//用于开始游戏的配置
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);
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");
parentId = (String) node.get("parentId");
location = ((String) node.get("place")).split("\\+")[0];
jumpLocation = location;
conditionName = (String) node.get("conditionName");
curUnknownText = (String) node.get("nextUnknownText");
taskLineName = "任务线_" + location + "进度";
conditionDescription.put(id, "剧情" + id + "状态");
varInitialMap.put(id ,"");
nextUnknownText = "";
skipText = new StringBuffer();
//本任务线的最后一个condition和本任务线的最后一个回答
if (!varInitialMap.containsKey(taskLineName)) {
conditionDescription.put(taskLineName, taskLineName);
varInitialMap.put(taskLineName, "");
}
//初始化
newBranch = false;
manyParent = false;
adjNodeList = adjList.get(id);
visited.put(id, true);
branch = node.getJSONArray("branch");
branchSize = branch.size();
//当两次出现unknown时给用户一下候选项
keywordOptions = "";
String jumpNextNextId, jumpNextNextLocation;
for (int i = 0; i < branchSize; i++) {
branchNode = branch.getJSONObject(i);
Map<String, String> updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class);
nextUnknownText = updateKnowledge.get("unknownText");
nextId = (String)branchNode.get("nextPlotId");
if(nextId == null || nextId.equals("")){
nextId = id + "_end";
branchNode.put("nextPlotId", nextId);
createEndNode(node, id, nextId, curUnknownText);
}
//保留下一步剧情的地点
beforeJumpLocatin = ((String)id2j.get(nextId).get("place")).split("\\+")[0];
autoJumpUpdateKnowledge.clear();
//自动跳转到下一个剧情,因为有可能存在多步自动跳转,所以要用一个while来处理
/**
* 自动跳转到下一个剧情,因为有可能存在多步自动跳转,所以要用一个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);
......@@ -248,7 +231,9 @@ public class PlotConstructor extends ElementConstructor {
skipText.append((String)jumpBranchNode.get("reply"));
Map newUpdateKnowledge = jumpBranchNode.getJSONObject("updateKnowledge");
updateKnowledge.putAll(newUpdateKnowledge);
autoJumpUpdateKnowledge.putAll(newUpdateKnowledge);
nextUnknownText = (String)newUpdateKnowledge.get("unknownText");
//updateKnowledge.putAll(newUpdateKnowledge);
jumpNextNextId = (String)jumpBranchNode.get("nextPlotId");
......@@ -256,47 +241,42 @@ public class PlotConstructor extends ElementConstructor {
if(jumpNextNextId != null && !jumpNextNextId.equals("")){
jumpNextNextLocation = (String)id2j.get(jumpNextNextId).get("place");
jumpLocation = jumpNextNextLocation;
updateKnowledge.put("site", jumpNextNextLocation);
updateKnowledge.put("npc_update", "updateFollowerLocation:" + jumpNextNextLocation);
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("autoJump", jumpBranchNode.get("autoJump"));
branchNode.put("nextPlotId", jumpNextNextId);
}
nextId = (String) branchNode.get("nextPlotId");
reply = (String)branchNode.get("reply");
if(reply.equals(""))
reply = curUnknownText;
if(updateKnowledge.containsKey("unknownText"))
nextUnknownText = updateKnowledge.get("unknownText");
else
nextUnknownText = "unknown";
//如果存在下一剧情,就将下一步剧情的condition设为下一个激活的conditin,把地点更新为下一步剧情的地点,并更新任务线进度
if (id2j.get(nextId) != null) {
nextCondition = (String) id2j.get(nextId).get("conditionName");
if(nextCondition.equals(""))
nextCondition = "yaobuyao";
nextLocation = ((String) id2j.get(nextId).get("place")).split("\\+")[0];
nTaskLineName = "任务线_" + nextLocation + "进度";
} else {
//如果不存在下一剧情,就将condition设为空,任务线进度不变
nextId = id;
nTaskLineName = taskLineName;
nextLocation = location;
nextCondition = (String) id2j.get(nextId).get("conditionName");
if(nextCondition.equals(""))
nextCondition = "yaobuyao";
branchNode.put("reply", curUnknownText);
reply = curUnknownText;
branchNode.put("moveWithPlot", false);
}
lastTaskCondition = "任务线" + nextLocation + "最后一个condition";
lastTaskReply = "任务线" + nextLocation + "最后的回答";
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);
/**
......@@ -306,13 +286,17 @@ public class PlotConstructor extends ElementConstructor {
* 2. 设一个专门的剧情表示剧情的结尾
*/
extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1;
if(!id.equals(nextId)){
extraHP += "," + nextId + "::match-Include=null";
}
extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1 + "," + nextId + "::match-Include=null";
extraUK = nTaskLineName + ":" + nextId + "-<-" + lastTaskCondition + ":" + nextCondition + "-<-" + lastTaskReply + ":" + (String)branchNode.get("reply") +
"-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1" ;
"-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1" + "-<-plot_jump_text:" + skipText;
if(!beforeJumpLocatin.equals(nextLocation)) {
//extraBeforeJumpUK =
}
if(nextId.endsWith("_end"))
nextGameStep = id;
else
nextGameStep = nextId;
/**
......@@ -340,34 +324,43 @@ public class PlotConstructor extends ElementConstructor {
*/
//如果主角的位置随着剧情移动
if(!branchNode.containsKey("moveWithPlot") || (Boolean)branchNode.get("moveWithPlot")) {
extraUK += "-<-site:" + nextLocation + "-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextId);
if((!branchNode.containsKey("moveWithPlot") || (Boolean)branchNode.get("moveWithPlot")) || location.equals(beforeJumpLocatin)) {
extraUK += "-<-site:" + nextLocation + "-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextGameStep);
updateKnowledge.putAll(autoJumpUpdateKnowledge);
}else {
//任务线最后一个condition
String beforeJumpTaskCondition = String.format(TASK_CONDITION, beforeJumpLocatin);
String beforeJumpTaskReply = String.format(TASK_REPLY, beforeJumpLocatin);
String beforeJumpUK = "-<-" + lastTaskCondition + ":yaobuyao" + "-<-" + lastTaskReply + ":" + skipText + "-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1" ;
/**
* 注意,比较的是当前地点和跳转前的地点
* 地点更新为跳转后的地点
*/
//如果在剧情中存在自动跳转的情况,那么应该比较自动跳转完成后的地点喝下一步剧情的地点是否相同
if(!jumpLocation.equals(nextLocation)){
if(!location.equals(beforeJumpLocatin)){
if(curUnknownText.equals(""))
reply = "请到" + nextLocation;
reply = "请到" + beforeJumpLocatin;
//如果当前地点和下一步剧情地点不同,要提示
else
reply = curUnknownText;
//如果下一步剧情和当前剧情的地点是不一样的,那么在玩家没有到达下一个地点是剧情还是停留在当前剧情,只有到达目的地后,下一步剧情才会发生变化
jConfig = new JConfig(
"yaobuyao::match-Keyword=+" + nextLocation,
"game_step::match-Include=" + String.format(GAME_STEP_FORMAT, botAccount, id) + "," + id + "::number-BiggerOrEqual=" + 1
+ "," + nextId + "::number-BiggerOrEqual=" + 1,
"match", (String)branchNode.get("reply") + skipText , (String) nextCondition,
"-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextId)
+ "-<-unknownText:" + nextUnknownText + "-<-site:" + nextLocation + "-<-npc_update:updateFollowerLocation:"+ nextLocation
"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_" + nextLocation + "_" + id,false);
jConfig.setConfigName("plot_" + beforeJumpLocatin + "_" + id,false);
jConfig.setjStatus(1);
jConfigList.add(jConfig);
......@@ -376,6 +369,11 @@ public class PlotConstructor extends ElementConstructor {
//如果当前剧情所在地喝下一步剧情所在地不一样,那么unknown文本
//只有到达下一步剧情所在地时才会更新
updateKnowledge.remove("unknownText");
updateKnowledge.remove("site");
extraUK = beforeJumpUK;
//如果下一步剧情不在同一地点,那么即使有跳转剧情,也是在下一个地点才说
skipText.setLength(0);
//必须在上一个jConfig添加完之后
//extraUK = extraUK.replace("-<-" + nextId + ":" + "+1", "");
......@@ -384,52 +382,58 @@ public class PlotConstructor extends ElementConstructor {
}
List<String> curPremiseList = JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class);
curPremiseList = JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class);
historyPremiseList = JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class);
//是否将当前识别到的数据加入到已知数据列表
if((Boolean)branchNode.get("includeCurInfo")){
extraFT = ",includeCurInfo";
}else{
extraFT = "";
}
jConfig = new JConfig(
curPremiseList,
JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class),
historyPremiseList,
updateKnowledge,
"", extraHP, extraUK,
"match", reply + skipText, (String) nextCondition, "1"
"match"+extraFT, reply, (String) nextCondition, "1"
);
//没有当前条件的限制,
if (curPremiseList.size() == 0){
jConfig.setFeature(jConfig.getFeature() + ",activate,post::gameQA(" + QA_URL + ")");
jConfig.setNextStep("queryskip*,map*,item*,npc*");
jConfig.setUpdateKnowledge(jConfig.getUpdateKnowledge() + "-<-临时变量condition:"+ nextCondition +"-<-临时变量reply:var={reply-3}");
jConfig.setNextStepStatus("active");
//当剧情没有条件限制时的操作
if (curPremiseList.size() == 0 && historyPremiseList.size() == 0){
unconditionalPlotProcess(jConfig, nextCondition);
}
jConfigList.add(jConfig);
//将子结点加入队列
adjId = (String) branchNode.get("nextPlotId");
if (visited.get(adjId) == null && id2j.get(adjId) != null) {
adjNode = id2j.get(adjId);
jConfigList.add(jConfig);
adjNode.put("parentId", id);
adjNode.put("nextUnknownText", nextUnknownText);
queue.add(adjNode);
} else {
conditionDescription.put(adjId, "剧情" + adjId + "进度");
varInitialMap.put(adjId, "");
}
if (branchNode.get("nextPlotId") != null) {
adjId = (String) branchNode.get("nextPlotId");
if (visited.get(adjId) == null) {
if (id2j.get(adjId) != null) {
adjNode = id2j.get(adjId);
adjNode.put("parentId", id);
adjNode.put("nextUnknownText", nextUnknownText);
queue.add(adjNode);
} else {
conditionDescription.put(adjId, "剧情" + adjId + "进度");
varInitialMap.put(adjId, "");
}
}
}
}
}
/**
* ----------------------------------------------------------------------------------------------------
* 不设剧情不设条件时的处理
......@@ -542,6 +546,35 @@ public class PlotConstructor extends ElementConstructor {
}
/**
* 游戏开始的配置
*/
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){
if (idList.size() != 0) {
......@@ -553,6 +586,69 @@ public class PlotConstructor extends ElementConstructor {
}
}
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);
}
//如果是无条件剧情,那么需要跟这一个激活操作
public void unconditionalPlotProcess(JConfig jConfig, String nextCondition){
jConfig.setFeature(jConfig.getFeature() + ",activate,post::gameQA(" + QA_URL + ")");
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.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 com.qiwu.chatbotbackend.processing.FormsPoster;
import org.apache.http.message.BasicNameValuePair;
import com.qiwu.chatbotbackend.processing.MyFunc;
import java.io.UnsupportedEncodingException;
import java.util.*;
import static com.qiwu.chatbotbackend.processing.FormsPoster.QA_URL;
public class PlotConstructor3 extends ElementConstructor {
public static String ASSISTANT = "globalVariable_默认_智能助手";
public static String TASK_DESCRIPTION = "globalVariable_默认_任务";
public static String TALKER_PATTERN = "【%s】";
String GAME_STEP_FORMAT = "%s_plot_%s";
JSONArray plots = null;
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 PlotConstructor3(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 {
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<>());
}
adjList.get(id).add(nextPlotId);
revAdjList.get(nextPlotId).add(id);
}
id2j.put(id, plot);
}
}
/**
* 将所有剧情根据地点分为多条剧情线,每一条剧情线都有一个计数器,记录当前地点的剧情到了第几步。
* 加上剧情计数器, 每一步分为三个状态
* @param root
* @param userinfo
*/
public void BFSGenerate4(JSONObject root, UserInfo userinfo, JSONObject jsonObject) {
String id, rootId = (String) root.get("id"), adjId, nextId, parentId, taskName = "", value = "", extraHP = "", extraUK = "", extraFT, nextTaskName, keywordOptions, conditionName = "yaobuyao",
nextUnknownText, curUnknownText, nextCondition, location, nextLocation, jumpLocation, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition, reply;
Boolean newBranch, manyParent, autoJump, includeCurInfo;
JSONObject node = null, branchNode = null, adjNode = null;
StringBuffer skipText = new StringBuffer();
JSONArray branch = null;
List<String> adjNodeList = null;
int priority, taskStep, nextPriority, nextTaskStep, 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");
String startPlace = ((String)root.get("place")).split("\\+")[0];
varInitialMap.put("site", startPlace);
varInitialMap.put("任务线" + startPlace + "最后一个condition", "");
varInitialMap.put("任务线" + startPlace + "最后的回答", "");
conditionDescription.put("任务线" + startPlace + "最后一个condition","任务线" + startPlace + "最后一个condition");
conditionDescription.put("任务线" + startPlace + "最后的回答", "任务线" + startPlace + "最后的回答");
//用于开始游戏的配置
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);
Queue<JSONObject> queue = new LinkedList<JSONObject>();
queue.add(root);
while (!queue.isEmpty()) {
node = queue.remove();
id = (String) node.get("id");
parentId = (String) node.get("parentId");
location = ((String) node.get("place")).split("\\+")[0];
jumpLocation = location;
conditionName = (String) node.get("conditionName");
curUnknownText = (String) node.get("nextUnknownText");
taskLineName = "任务线_" + location + "进度";
conditionDescription.put(id, "剧情" + id + "状态");
varInitialMap.put(id ,"");
nextUnknownText = "";
skipText = new StringBuffer();
//本任务线的最后一个condition和本任务线的最后一个回答
if (!varInitialMap.containsKey(taskLineName)) {
conditionDescription.put(taskLineName, taskLineName);
varInitialMap.put(taskLineName, "");
}
//初始化
newBranch = false;
manyParent = false;
adjNodeList = adjList.get(id);
visited.put(id, true);
branch = node.getJSONArray("branch");
branchSize = branch.size();
//当两次出现unknown时给用户一下候选项
keywordOptions = "";
String beforeJumpLocatin, jumpNextNextId, jumpNextNextLocation;
for (int i = 0; i < branchSize; i++) {
branchNode = branch.getJSONObject(i);
Map<String, String> updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class);
beforeJumpLocatin = (String)branchNode.get("place");
/**
* 自动跳转到下一个剧情,因为有可能存在多步自动跳转,所以要用一个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)jumpBranchNode.get("reply"));
Map newUpdateKnowledge = jumpBranchNode.getJSONObject("updateKnowledge");
updateKnowledge.putAll(newUpdateKnowledge);
jumpNextNextId = (String)jumpBranchNode.get("nextPlotId");
if(jumpNextNextId != null && !jumpNextNextId.equals("")){
jumpNextNextLocation = (String)id2j.get(jumpNextNextId).get("place");
jumpLocation = jumpNextNextLocation;
updateKnowledge.put("site", jumpNextNextLocation);
updateKnowledge.put("npc_update", "updateFollowerLocation:" + jumpNextNextLocation);
}
branchNode.put("autoJump", jumpBranchNode.get("autoJump"));
branchNode.put("nextPlotId", jumpNextNextId);
}
nextId = (String) branchNode.get("nextPlotId");
reply = (String)branchNode.get("reply");
if(updateKnowledge.containsKey("unknownText"))
nextUnknownText = updateKnowledge.get("unknownText");
else
nextUnknownText = "unknown";
//如果存在下一剧情,就将下一步剧情的condition设为下一个激活的conditin,把地点更新为下一步剧情的地点,并更新任务线进度
if (id2j.get(nextId) != null) {
nextCondition = (String) id2j.get(nextId).get("conditionName");
if(nextCondition.equals(""))
nextCondition = "yaobuyao";
nextLocation = ((String) id2j.get(nextId).get("place")).split("\\+")[0];
nTaskLineName = "任务线_" + nextLocation + "进度";
} else {
//如果不存在下一剧情,就将condition设为空,任务线进度不变
nextId = id;
nTaskLineName = taskLineName;
nextLocation = location;
nextCondition = "yaobuyao";
branchNode.put("reply", curUnknownText);
reply = curUnknownText;
branchNode.put("moveWithPlot", false);
}
lastTaskCondition = "任务线" + nextLocation + "最后一个condition";
lastTaskReply = "任务线" + nextLocation + "最后的回答";
/**
* 额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情
* 如果某个地点的剧情已经到结尾啦,那么有两种解决方法:
* 1: 将剧情停留在最后一步剧情
* 2. 设一个专门的剧情表示剧情的结尾
*/
extraHP = taskLineName + "::match-Include=" + id + ",site::match-Include=" + location + "," + id + "::number-BiggerOrEqual=" + 1;
if(!id.equals(nextId)){
extraHP += "," + nextId + "::match-Include=null";
}
extraUK = nTaskLineName + ":" + nextId + "-<-" + lastTaskCondition + ":" + nextCondition + "-<-" + lastTaskReply + ":" + (String)branchNode.get("reply") +
"-<-" + id + ":" + "+1-<-" + nextId + ":" + "+1" ;
/**
* 1. 主角是否随剧情移动
* 如果随剧情移动,则更新地点和game_step
* 如果不随剧情移动,则不更新地点和game_step,添加中间配置"去XX",设高优先级,并更新状态
*
* 2. 当前条件是否为空
* 如果当前条件为空,则提交qa激活并进入下一步剧情
* 如果当前条件不为空,则需要满足条件才能进入下一步剧情
*
* 3. 下一部剧情是否为空
* 如果下一部剧情为空,剧情编号、任务线、地点、不变,condition改为yaobuyao,reply改为当前unknown文本,主角不随剧情移动
*
* 4. 有没有说去XX
*
* 主角不随剧情移动+当前条件为空+去沙滩
* 1、沙滩无剧情
* 2、沙滩有剧情
*
* 5. 地点变化
* 1. 当前所处地点
* 2. 下一步剧情所处地点(包含自动跳转的情况)
* 3. 自动跳转完成后的地点
*/
//如果主角的位置随着剧情移动
if(!branchNode.containsKey("moveWithPlot") || (Boolean)branchNode.get("moveWithPlot")) {
extraUK += "-<-site:" + nextLocation + "-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextId);
}else {
//如果在剧情中存在自动跳转的情况,那么应该比较自动跳转完成后的地点喝下一步剧情的地点是否相同
if(!jumpLocation.equals(nextLocation)){
if(curUnknownText.equals(""))
reply = "请到" + nextLocation;
//如果当前地点和下一步剧情地点不同,要提示
else
reply = curUnknownText;
//如果下一步剧情和当前剧情的地点是不一样的,那么在玩家没有到达下一个地点是剧情还是停留在当前剧情,只有到达目的地后,下一步剧情才会发生变化
jConfig = new JConfig(
"yaobuyao::match-Keyword=+" + nextLocation,
"game_step::match-Include=" + String.format(GAME_STEP_FORMAT, botAccount, id) + "," + id + "::number-BiggerOrEqual=" + 1
+ "," + nextId + "::number-BiggerOrEqual=" + 1,
"match", (String)branchNode.get("reply") + skipText , (String) nextCondition,
"-<-game_step:" + String.format(GAME_STEP_FORMAT, botAccount, nextId)
+ "-<-unknownText:" + nextUnknownText + "-<-site:" + nextLocation + "-<-npc_update:updateFollowerLocation:"+ nextLocation
);
jConfig.setStatus("sleeping");
jConfig.setConfigName("plot_" + nextLocation + "_" + id,false);
jConfig.setjStatus(1);
jConfigList.add(jConfig);
//如果当前剧情所在地喝下一步剧情所在地不一样,那么unknown文本
//只有到达下一步剧情所在地时才会更新
updateKnowledge.remove("unknownText");
//必须在上一个jConfig添加完之后
//extraUK = extraUK.replace("-<-" + nextId + ":" + "+1", "");
}
}
curPremiseList = JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class);
historyPremiseList = JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class);
includeCurInfo = (Boolean)branchNode.get("includeCurInfo");
if((Boolean)branchNode.get("includeCurInfo")){
extraFT = ",includeCurInfo";
}else{
extraFT = "";
}
jConfig = new JConfig(
curPremiseList,
historyPremiseList,
updateKnowledge,
"", extraHP, extraUK,
"match"+extraFT, reply + skipText, (String) nextCondition, "1"
);
//没有当前条件的限制,
if (curPremiseList.size() == 0 && historyPremiseList.size() == 0){
jConfig.setFeature(jConfig.getFeature() + ",activate,post::gameQA(" + QA_URL + ")");
jConfig.setNextStep("queryskip*,map*,item*,npc*");
jConfig.setUpdateKnowledge(jConfig.getUpdateKnowledge() + "-<-临时变量condition:"+ nextCondition +"-<-临时变量reply:var={reply-3}");
jConfig.setNextStepStatus("active");
}
jConfigList.add(jConfig);
if (branchNode.get("nextPlotId") != null) {
adjId = (String) branchNode.get("nextPlotId");
if (visited.get(adjId) == null) {
if (id2j.get(adjId) != null) {
adjNode = id2j.get(adjId);
adjNode.put("parentId", id);
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问答
*/
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);
//---------------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------------
/**
* ----------------------------------------------------------------------------------------------------
* 用于处理开始游戏或者继续游戏
*
*
*/
}
@Override
public void postProcessing(List<Integer> idList, int categoryId){
if (idList.size() != 0) {
jConfig = new JConfig(" ", " ", "activate,post::gameQA(" + QA_URL+ ")", "", "unknown4,unknown3,unknown2,unknown1,common_answer", "");
jConfig.setNextStepStatus("active");
JSONObject json = jConfig.toJson(this.getConditionDescription());
helper.insertConfigByBotId(botId, json, idList, categoryId);
jConfigList.add(jConfig);
}
}
}
......@@ -152,6 +152,7 @@ public class ChatCacheController {
chatCache.setReloading(true);
br.close();
fr.close();
loadCacheStatus = true;
......@@ -262,6 +263,7 @@ public class ChatCacheController {
if (now - lastChatTime > ChatCacheController.TIME_OUT) {
chatCache = chatCacheMap.get(chatKey);
saveChatCache(chatKey, chatCache);
System.out.println("移除" + chatKey);
it.remove();
}
}
......
......@@ -6,6 +6,7 @@ import com.qiwu.chatbotbackend.entity.Solution;
import com.qiwu.chatbotbackend.entity.Condition;
import com.qiwu.chatbotbackend.entity.UserInfo;
import com.qiwu.chatbotbackend.gameDesign.GameUtil;
import com.qiwu.chatbotbackend.task.utils.BasicBotUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
......@@ -43,8 +44,9 @@ public class QuestionMatcher {
public Map<String ,String> curInfoPoint = null;
public Map<String ,String> historyInfoPoint = null;
public WorldController worldController = null;
BasicBotUtil botUtil = null;
public QuestionMatcher(Map<String ,String> curInfoPoint, Map<String ,String> historyInfoPoint, LogWriter logWriter, UserInfo userinfo, ServletContext context, GameEnv gameEnv) {
public QuestionMatcher(Map<String ,String> curInfoPoint, Map<String ,String> historyInfoPoint, LogWriter logWriter, UserInfo userinfo, ServletContext context, GameEnv gameEnv, BasicBotUtil botUtil) {
this.curInfoPoint = curInfoPoint;
this.historyInfoPoint = historyInfoPoint;
this.logWriter = logWriter;
......@@ -52,6 +54,7 @@ public class QuestionMatcher {
this.context = context;
this.gameEnv = gameEnv;
this.worldController = new WorldController(logWriter, userinfo);
this.botUtil = botUtil;
}
......@@ -185,7 +188,7 @@ public class QuestionMatcher {
comparePair = premiseStr.split("::");
actionName = comparePair[0];
cmpType = comparePair[1];
keyword = getKeyword(curInfoPoint, historyInfoPoint, false, actionName);
keyword = botUtil.getKeyword(curInfoPoint, historyInfoPoint, false, actionName);
if (keyword == null) {
flag = false;
......@@ -211,7 +214,7 @@ public class QuestionMatcher {
cmpType = comparePair[1];
actionName = comparePair[0];
//如果featureMap中包含includeCurInfo,则已知信息中包含啦当前对话中识别的所有信息
keyword = getKeyword(historyInfoPoint, curInfoPoint, condition.featureMap.containsKey("includeCurInfo"), actionName);
keyword = botUtil.getKeyword(historyInfoPoint, curInfoPoint, condition.featureMap.containsKey("includeCurInfo"), actionName);
if (keyword == null) {
flag = false;
......@@ -238,46 +241,8 @@ public class QuestionMatcher {
}
public String getKeyword(Map<String, String> infoPoint, Map<String, String> infoPoint2, Boolean chooseLater, String actionName){
String keyword = "";
String nameSeries[] = actionName.split("_");
if(actionName.startsWith("npc_")){
if(nameSeries.length == 4){
keyword = gameEnv.queryNpcAttrByNpcName(nameSeries[3], nameSeries[4]);
}
}else if (actionName.startsWith("goods_")) {
if (nameSeries.length == 4) {
keyword = gameEnv.queryGoodsAttrByGoodsName(nameSeries[2], nameSeries[3]);
System.out.println("return" + keyword);
}
}else if(actionName.startsWith("isNeighbour")){
String opPair[] = actionName.split(":");
if(!curInfoPoint.containsKey(opPair[1]) || curInfoPoint.get(opPair[1]).equals("unknown") || curInfoPoint.get(opPair[1]).equals("")){
keyword = "not_exist";
}else {
logWriter.record("isNeighbour(" + historyInfoPoint.get("site") + "," + curInfoPoint.get(opPair[1]).split(":")[1] + ")", 1);
keyword = String.valueOf(gameEnv.isNeighbour(historyInfoPoint.get("site"), curInfoPoint.get(opPair[1]).split(":")[1]));
logWriter.record("返回:" + keyword, 1);
}
}else {
/**
* 如果chooseLater为真,则先提取infoPint2中的关键字,如果infoPoint2中不存在,再提取infoPoint中的关键字
*/
if(chooseLater){
keyword = infoPoint2.get(actionName);
if(keyword != null && !keyword.equals(""))
return keyword;
}
keyword = infoPoint.get(actionName);
}
return keyword;
};
/**
* 单个条件的匹配,判断是否满足条件
......@@ -384,7 +349,6 @@ public class QuestionMatcher {
else if (operator.equals("Later"))
flag = candidateA > candidateB;
} else if(cmpType.equals("curVarCmp") || cmpType.equals("hisVarCmp")) {
String conditionName2 = "", conditionValue2 = "";
for (String k : keywordSet) {
......@@ -395,9 +359,9 @@ public class QuestionMatcher {
}
if(cmpType.equals("curVarCmp") && curInfoPoint.get(conditionName2) != null && !curInfoPoint.get(conditionName2).equals("")) {
conditionValue2 = getKeyword(curInfoPoint, historyInfoPoint, false, conditionName2);
conditionValue2 = botUtil.getKeyword(curInfoPoint, historyInfoPoint, false, conditionName2);
}else if (cmpType.equals("hisVarCmp") && historyInfoPoint.get(conditionName2) != null && !historyInfoPoint.get(conditionName2).equals("")){
conditionValue2 = getKeyword(historyInfoPoint, curInfoPoint, false, conditionName2);
conditionValue2 = botUtil.getKeyword(historyInfoPoint, curInfoPoint, false, conditionName2);
}else {
flag = false;
}
......@@ -506,8 +470,6 @@ public class QuestionMatcher {
// 操作符为等于时可以比较两个字符串是否相同
}
}
}
......@@ -642,7 +604,7 @@ public class QuestionMatcher {
//updateKnowledge关键字
if (ansCondition.featureMap.containsKey("updateKnowledge")) {
logWriter.record("---------------------进入更新答案【略】",1);
updateKnowledge(ansCondition);
updateKnowledge2(ansCondition);
logWriter.record("---------------------更新答案结束",1);
}
......@@ -939,17 +901,17 @@ public class QuestionMatcher {
String keyword, variableName, updateValue, returnStr = "1";
Iterator<String> iit = condition.updateKnowledge.keySet().iterator();
while (iit.hasNext()) {
variableName = iit.next();
updateValue = condition.updateKnowledge.get(variableName);
keyword = historyInfoPoint.get(variableName);
//如果变量名开头为NPC或者item,就专门交给world处理
if((userinfo.varInitialMap.get("botType") != null && userinfo.varInitialMap.get("botType").equals("game")) &&
(variableName.startsWith("npc_") || variableName.startsWith("goods_") || variableName.startsWith("map_"))){
(variableName.startsWith("npc_") || variableName.startsWith("goods_") || variableName.startsWith("map_") || variableName.startsWith("place_"))){
try {
returnStr = worldController.worldOperation(gameEnv, variableName, updateValue, curInfoPoint, historyInfoPoint);
updateValue = returnStr;
......@@ -1079,6 +1041,142 @@ public class QuestionMatcher {
}
public void updateKnowledge2(Condition condition) throws ParseException {
String keyword, variableName, updateValue, returnStr = "1";
Iterator<String> iit = condition.updateKnowledge.keySet().iterator();
while (iit.hasNext()) {
variableName = iit.next();
keyword = botUtil.getKeyword(historyInfoPoint, curInfoPoint, false, variableName);
updateValue = botUtil.knowledgeProcess(variableName, condition.updateKnowledge.get(variableName));
try {
//做数字加法
if (updateValue.startsWith("+")) {
if (keyword == null || keyword.equals(""))
keyword = "0";
if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) {
long time = MyFunc.transferToMillisecond(keyword);
int offset = Integer.parseInt(updateValue.substring(1));
updateValue = MyFunc.transferToStandardTime(time + (1000 * offset));
} else if (StringUtils.isNumeric(keyword)) {
int number = Integer.parseInt(keyword);
int offset = Integer.parseInt(updateValue.substring(1));
updateValue = String.valueOf(number + offset);
}
//做数字减法
} else if (updateValue.startsWith("-")) {
if (keyword == null || keyword.equals(""))
keyword = "0";
if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) {
long time = MyFunc.transferToMillisecond(keyword);
int offset = Integer.parseInt(updateValue.substring(1));
updateValue = MyFunc.transferToStandardTime(time - (1000 * offset));
} else if (StringUtils.isNumeric(keyword)) {
int number = Integer.parseInt(keyword);
int offset = Integer.parseInt(updateValue.substring(1));
updateValue = String.valueOf(number - offset);
}
//做字符串累加
} else if (updateValue.startsWith("str+")) {
if (keyword == null || keyword.equals(""))
keyword = "";
updateValue = keyword + updateValue.substring(4);
//做字符串删除
} else if (updateValue.startsWith("str-")) {
if (keyword == null || keyword.equals(""))
keyword = "";
updateValue = keyword.replace(updateValue.substring(4), "");
} else if (updateValue.startsWith("int+=")) {
if (keyword == null || keyword.equals(""))
keyword = "0";
if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) {
long time = MyFunc.transferToMillisecond(keyword);
int offset = Integer.parseInt(updateValue.substring(1));
updateValue = MyFunc.transferToStandardTime(time + (1000 * offset));
} else if (StringUtils.isNumeric(keyword)) {
int number = Integer.parseInt(keyword);
int offset = Integer.parseInt(updateValue.substring(5));
updateValue = String.valueOf(number + offset);
}
//做数字减法
} else if (updateValue.startsWith("int-=")) {
if (keyword == null || keyword.equals(""))
keyword = "0";
if (keyword.matches("\\d{4}年\\d{1,2}月\\d{1,2}日.*")) {
long time = MyFunc.transferToMillisecond(keyword);
int offset = Integer.parseInt(updateValue.substring(5));
updateValue = MyFunc.transferToStandardTime(time - (1000 * offset));
} else if (StringUtils.isNumeric(keyword)) {
int number = Integer.parseInt(keyword);
int offset = Integer.parseInt(updateValue.substring(1));
updateValue = String.valueOf(number - offset);
}
//做字符串累加
} else if (updateValue.startsWith("str+=")) {
if (keyword == null || keyword.equals(""))
keyword = "";
updateValue = keyword + updateValue.substring(5);
//做字符串删除
} else if (updateValue.startsWith("str-=")) {
if (keyword == null || keyword.equals(""))
keyword = "";
updateValue = keyword.replace(updateValue.substring(5), "");
} else if (updateValue.startsWith("var=")) {
String conditionName = updateValue.substring(5, updateValue.length() - 3);
if (updateValue.endsWith("-1}")) {
if (curInfoPoint.get(conditionName) != null) {
updateValue = curInfoPoint.get(conditionName);
} else {
updateValue = "";
}
} else if (updateValue.endsWith("-2}")) {
if (historyInfoPoint.get(conditionName) != null) {
updateValue = historyInfoPoint.get(conditionName);
} else {
updateValue = "";
}
} else if (updateValue.endsWith("nextStep-3}")) {
updateValue = condition.nextStep;
} else if (updateValue.endsWith("reply-3}")) {
updateValue = MyFunc.randStr(condition.answer);
}
if (variableName.startsWith("process-nextStep")) {
condition.nextStep = updateValue;
updateValue = "";
}
}
} catch (Exception e) {
e.printStackTrace();
continue;
}
if(updateValue.equals("")) {
curInfoPoint.put(variableName + "_backup", curInfoPoint.get(variableName)); //更新答案将某变量设为空时,要将当前信息点也清空,不然后边信息点转移时这个变量的已知信息依然不是空的。
// 为了避免将当前信息点清空后debug信息显示不完整,现创造一个备份,在appendDebugInfo后会将这个备份清空。
curInfoPoint.put(variableName, "");
}
botUtil.putKeyword(variableName, updateValue);
}
}
public void activateCondition(Queue<Condition> activatedQueue, String botAccount, int basePriority, int baseAuxiliaryPriority,String activateList, ServletContext context) throws IOException {
UserInfo userinfo = (UserInfo) context.getAttribute(botAccount);
......
......@@ -2,7 +2,6 @@ package com.qiwu.chatbotbackend.processing;
import com.qiwu.chatbotbackend.GameEnvironment.GameEnv;
import com.qiwu.chatbotbackend.entity.Condition;
import com.qiwu.chatbotbackend.entity.Solution;
import com.qiwu.chatbotbackend.entity.UserInfo;
import com.qiwu.chatbotbackend.gameDesign.PlotConstructor;
......@@ -35,12 +34,18 @@ public class ResponseFilter {
return reply;
}
if(historyInfoPoint.get("plot_jump_text") != null && !historyInfoPoint.get("plot_jump_text").equals("")){
return reply;
}
if(reply.startsWith("【" + historyInfoPoint.get(PlotConstructor.ASSISTANT)+ "】") ){
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){
}else if (sameLocation(reply, curInfoPoint, historyInfoPoint, gameEnv, worldController, site, logWriter) == 0 && !reply.equals("")){
return appendTalker(reply,curInfoPoint, historyInfoPoint, gameEnv, worldController);
}else if (reply.equals("") && !historyInfoPoint.get("common_answer").equals("")){
return reply;
}
if(userInfo.varInitialMap.get("unknownTextList") != null){
......@@ -57,8 +62,6 @@ public class ResponseFilter {
}
if(unknownList.size() > 0){
return MyFunc.randStr(unknownList);
}
}
......
......@@ -92,6 +92,9 @@ public class UserInfoController {
try {
text = line.split("---");
if (line.startsWith("yaobuyao::match-Keyword=+海边|game_step::match-Include=9826795627_plot_1-2,1-2::number-BiggerOrEqual=1|match,updateKnowledge-<-unknownText:-<-site:武器库-<--<-game_step:9826795627_plot_1-5-<-unknownText:还没到下一个地点-<-site:武器库-<-npc_update:updateFollowerLocation:武"))
System.out.println("xxx");
line = text[0];
if(text.length > 1 && text[1].startsWith("<-"))
line += "---" + text[1];
......
......@@ -25,8 +25,8 @@ public class GetAnswerServlet extends HttpServlet {
*/
String NAME_MISSING_ERROR = "没找到bot名?";
String LOG_PATH = "/var/www/html/logs/";
//String LOG_PATH = "/var/www/html/logs/";
String LOG_PATH = "/home/hxw/source/logs/";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
......@@ -108,7 +108,7 @@ public class GetAnswerServlet extends HttpServlet {
//信息点预处理
QuestionMatcher matcher = new QuestionMatcher(curInfoPoint, historyInfoPoint, logWriter, userinfo, context, chatCache.getGameEnv());
QuestionMatcher matcher = new QuestionMatcher(curInfoPoint, historyInfoPoint, logWriter, userinfo, context, chatCache.getGameEnv(), botUtil);
/*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/
......
package com.qiwu.chatbotbackend.servlet;
import com.qiwu.chatbotbackend.entity.ChatCache;
import com.qiwu.chatbotbackend.processing.ChatCacheController;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.Iterator;
import java.util.Map;
@WebListener
public class MyListener implements ServletContextListener {
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("destory context....");
/**
* 在程序中断时先把所有存在servletContext中的对话缓存数据保存下来
*/
String chatKey;
ServletContext servletContext = sce.getServletContext();
Object obj = servletContext.getAttribute("chatCache");
ChatCache cache = null;
if(obj != null){
Map<String, ChatCache> chatCacheMap = (Map<String, ChatCache>)obj;
Iterator<String> cacheIter = chatCacheMap.keySet().iterator();
while(cacheIter.hasNext()){
chatKey = cacheIter.next();
cache = chatCacheMap.get(chatKey);
try {
System.out.println(String.format("saving %s", chatKey));
ChatCacheController.saveChatCache(chatKey, cache);
}catch (Exception e){
System.out.println(String.format("保存%s时出现异常", chatKey));
}
cacheIter.remove();
}
}
}
}
package com.qiwu.chatbotbackend.task.utils;
import com.qiwu.chatbotbackend.GameEnvironment.GameEnv;
import com.qiwu.chatbotbackend.entity.Solution;
import com.qiwu.chatbotbackend.entity.UserInfo;
import com.qiwu.chatbotbackend.gameDesign.GameUtil;
......@@ -123,4 +124,32 @@ public class BasicBotUtil {
public boolean postprocessing(String chatKey, ServletContext context, Solution bestMatch){
return true;
}
public String getKeyword(Map<String, String> infoPoint, Map<String, String> infoPoint2, Boolean chooseLater, String actionName){
String keyword = "";
String nameSeries[] = actionName.split("_");
/**
* 如果chooseLater为真,则先提取infoPint2中的关键字,如果infoPoint2中不存在,再提取infoPoint中的关键字
*/
if(chooseLater){
keyword = infoPoint2.get(actionName);
if(keyword != null && !keyword.equals(""))
return keyword;
}
keyword = infoPoint.get(actionName);
return keyword;
};
public void putKeyword(String variableName, String updateValue){
historyInfoPoint.put(variableName, updateValue);
}
public String knowledgeProcess(String variableName, String updateValue){
return updateValue;
}
}
......@@ -67,12 +67,93 @@ public class GameBotUtil extends BasicBotUtil{
e.printStackTrace();
}
}
String plot_jump_text = historyInfoPoint.get("plot_jump_text");
if(plot_jump_text != null && !plot_jump_text.equals("")) {
bestMatch.setAnswer(bestMatch.getAnswer() + plot_jump_text + " " );
historyInfoPoint.put("plot_jump_text", "");
}
String common_answer = historyInfoPoint.get("common_answer");
if(common_answer != null && !common_answer.equals("") && !common_answer.equals("no answer")){
bestMatch.setAnswer(common_answer + ", " + bestMatch.getAnswer());
bestMatch.setAnswer(common_answer + " " + bestMatch.getAnswer());
historyInfoPoint.put("common_answer", "");
}
return true;
}
public String getKeyword(Map<String, String> infoPoint, Map<String, String> infoPoint2, Boolean chooseLater, String actionName){
String keyword = "";
String nameSeries[] = actionName.split("_");
//变量名以npc_开头,就从游戏环境中查询相应的值
if(actionName.startsWith("npc_")){
if(nameSeries.length == 4){
keyword = gameEnv.queryNpcAttrByNpcName(nameSeries[2], nameSeries[3]);
}
}else if (actionName.startsWith("goods_")) {
if (nameSeries.length == 4) {
keyword = gameEnv.queryGoodsAttrByGoodsName(nameSeries[2], nameSeries[3]);
System.out.println("return" + keyword);
}
}else if(actionName.startsWith("isNeighbour")){
String opPair[] = actionName.split(":");
if(!curInfoPoint.containsKey(opPair[1]) || curInfoPoint.get(opPair[1]).equals("unknown") || curInfoPoint.get(opPair[1]).equals("")){
keyword = "not_exist";
}else {
logWriter.record("isNeighbour(" + historyInfoPoint.get("site") + "," + curInfoPoint.get(opPair[1]).split(":")[1] + ")", 1);
keyword = String.valueOf(gameEnv.isNeighbour(historyInfoPoint.get("site"), curInfoPoint.get(opPair[1]).split(":")[1]));
logWriter.record("返回:" + keyword, 1);
}
}else {
/**
* 如果chooseLater为真,则先提取infoPint2中的关键字,如果infoPoint2中不存在,再提取infoPoint中的关键字
*/
if(chooseLater){
keyword = infoPoint2.get(actionName);
if(keyword != null && !keyword.equals(""))
return keyword;
}
keyword = infoPoint.get(actionName);
}
return keyword;
};
@Override
public void putKeyword(String variableName, String updateValue){
//如果变量名开头为NPC或者item,就专门交给world处理
if((variableName.startsWith("npc_") || variableName.startsWith("goods_") || variableName.startsWith("map_") || variableName.startsWith("place_"))){
try {
if(!updateValue.startsWith("query") && !updateValue.startsWith("update")){
updateValue = "update:" + updateValue;
}
String returnStr = worldController.worldOperation(gameEnv, variableName, updateValue, curInfoPoint, historyInfoPoint);
updateValue = returnStr;
}catch (Exception e){
e.printStackTrace();
updateValue = "游戏模块处理出错";
}
}
historyInfoPoint.put(variableName, updateValue);
}
public String knowledgeProcess(String variableName, String updateValue){
String values[] = updateValue.split(":",2), returnValue;
if(values.length > 1 && values[0].equals("update"))
returnValue = values[1];
else
returnValue = updateValue;
return returnValue;
}
}
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