Commit 6faa3ec8 by 赵国君

some minor changes

parent 180a08d8
/target/
.classpath
.project
.settings/
ChatCache/
vincent_player*
package com.qiwu.chatbotbackend.actiongenerate.utils; package com.qiwu.chatbotbackend.actiongenerate.utils;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import com.qiwu.chatbotbackend.actiongenerate.DB.EngineUtils; import com.qiwu.chatbotbackend.actiongenerate.DB.EngineUtils;
import com.qiwu.chatbotbackend.actiongenerate.DB.PlatformUtils; import com.qiwu.chatbotbackend.actiongenerate.DB.PlatformUtils;
import com.qiwu.chatbotbackend.actiongenerate.entity.*; import com.qiwu.chatbotbackend.actiongenerate.entity.*;
import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.processing.SimpleUtil; import com.qiwu.chatbotbackend.processing.SimpleUtil;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.*; import java.util.*;
import static com.qiwu.chatbotbackend.Config.Config.*; import static com.qiwu.chatbotbackend.Config.Config.*;
public class ActionUtils { public class ActionUtils {
EngineUtils engine = null; EngineUtils engine = null;
SqlHelper helper = null; SqlHelper helper = null;
String activeCondition = ""; String activeCondition = "";
ActionPostElem ape = null; ActionPostElem ape = null;
public IntervalStatus intervalStatus = new IntervalStatus(1, ""); public IntervalStatus intervalStatus = new IntervalStatus(1, "");
public ActionUtils(EngineUtils engine, SqlHelper helper){ public ActionUtils(EngineUtils engine, SqlHelper helper){
this.engine = engine; this.engine = engine;
this.helper = helper; this.helper = helper;
} }
public void insertCondition(JSONObject parameters){ public void insertCondition(JSONObject parameters){
String conditionName = "", text = "", categoryStr, conditionJsonStr = "", isActive = ""; String conditionName = "", text = "", categoryStr, conditionJsonStr = "", isActive = "";
Integer count = 0; Integer count = 0;
JSONObject conditionJson = null; JSONObject conditionJson = null;
Condition condition = null; Condition condition = null;
List<Condition> conditionList = new ArrayList<Condition>(); List<Condition> conditionList = new ArrayList<Condition>();
Boolean insertFlag = false; Boolean insertFlag = false;
JSONArray conditions = parameters.getJSONArray("conditionData"); JSONArray conditions = parameters.getJSONArray("conditionData");
Integer botId = parameters.getInteger("botId"); Integer botId = parameters.getInteger("botId");
List<String> actionTextList = helper.queryActionTextList(botId); List<String> actionTextList = helper.queryActionTextList(botId);
Set<String> conditionNameSet = new HashSet<String>(); Set<String> conditionNameSet = new HashSet<String>();
for(String actionText:actionTextList){ for(String actionText:actionTextList){
//从action文本取出condition的名字 //从action文本取出condition的名字
//System.out.println("--" + actionText.trim().substring(100).split("\r\n")[0] + "---"); //System.out.println("--" + actionText.trim().substring(100).split("\r\n")[0] + "---");
conditionName = actionText.trim().split("\r\n")[0].split("=")[1].split(":")[0]; conditionName = actionText.trim().split("\r\n")[0].split("=")[1].split(":")[0];
conditionNameSet.add(conditionName); conditionNameSet.add(conditionName);
} }
count = conditions.size(); count = conditions.size();
if(count > 0){ if(count > 0){
for(int i =0; i < count;i++){ for(int i =0; i < count;i++){
conditionJson = conditions.getJSONObject(i); conditionJson = conditions.getJSONObject(i);
conditionName = conditionJson.getString("conditionName"); conditionName = conditionJson.getString("conditionName");
//condition名字已存在 //condition名字已存在
if(conditionNameSet.contains(conditionName)){ if(conditionNameSet.contains(conditionName)){
for(int j =2;j < 100 && conditionNameSet.contains(conditionName);j++){ for(int j =2;j < 100 && conditionNameSet.contains(conditionName);j++){
conditionName = conditionJson.getString("conditionName") + j; conditionName = conditionJson.getString("conditionName") + j;
} }
conditionJson.put("conditionName", conditionName); conditionJson.put("conditionName", conditionName);
} }
text = generateSingleActionText(conditionName, conditionJson); text = generateSingleActionText(conditionName, conditionJson);
actionTextList.add(text); actionTextList.add(text);
if(conditionJson.getBoolean("active")) if(conditionJson.getBoolean("active"))
isActive = "1"; isActive = "1";
else else
isActive = "0"; isActive = "0";
categoryStr = conditionJson.getString("conditionCategory"); categoryStr = conditionJson.getString("conditionCategory");
conditionJson.put("displayOrder", 999); //展示顺序为condition的展示顺序,越小排在越前面 conditionJson.put("displayOrder", 999); //展示顺序为condition的展示顺序,越小排在越前面
conditionJsonStr = JSONObject.toJSONString(condition); conditionJsonStr = JSONObject.toJSONString(condition);
condition = new Condition(botId, conditionJson.toJSONString(), text, categoryStr, isActive); condition = new Condition(botId, conditionJson.toJSONString(), text, categoryStr, isActive);
conditionList.add(condition); conditionList.add(condition);
insertIdElemIfNotExist(conditionJson.getInteger("originConditionId"), conditionJson.getString("relationName").replace("0", "a0").replace("-", "b0")); insertIdElemIfNotExist(conditionJson.getInteger("originConditionId"), conditionJson.getString("relationName").replace("0", "a0").replace("-", "b0"));
} }
insertFlag = helper.batchInsertCondition(conditionList); insertFlag = helper.batchInsertCondition(conditionList);
} }
if(insertFlag) if(insertFlag)
intervalStatus = new IntervalStatus(1, ""); intervalStatus = new IntervalStatus(1, "");
else else
intervalStatus = new IntervalStatus(0, "插入失败"); intervalStatus = new IntervalStatus(0, "插入失败");
} }
public void insertIdElemIfNotExist(Integer originConditionId, String relationName){ public void insertIdElemIfNotExist(Integer originConditionId, String relationName){
int len = 0; int len = 0;
Boolean exist = false; Boolean exist = false;
if(ape.getConditionIdPair() != null){ if(ape.getConditionIdPair() != null){
len = ape.getConditionIdPair().size(); len = ape.getConditionIdPair().size();
} }
for(int i = 0;i < len;i++){ for(int i = 0;i < len;i++){
if(ape.getConditionIdPair().getJSONArray(i).getInteger(0) == originConditionId){ if(ape.getConditionIdPair().getJSONArray(i).getInteger(0) == originConditionId){
exist = true; exist = true;
break; break;
} }
} }
if(!exist){ if(!exist){
ape.getConditionIdPair().add(new JSONArray(){{add(originConditionId);add(relationName);}}); ape.getConditionIdPair().add(new JSONArray(){{add(originConditionId);add(relationName);}});
} }
} }
public void deleteIdElemIfExist(Integer originConditionId){ public void deleteIdElemIfExist(Integer originConditionId){
int len = 0; int len = 0;
Boolean exist = false; Boolean exist = false;
if(ape.getConditionIdPair() != null){ if(ape.getConditionIdPair() != null){
len = ape.getConditionIdPair().size(); len = ape.getConditionIdPair().size();
} }
for(int i = 0;i < len;i++){ for(int i = 0;i < len;i++){
if(ape.getConditionIdPair().getJSONArray(i).getInteger(0) == originConditionId){ if(ape.getConditionIdPair().getJSONArray(i).getInteger(0) == originConditionId){
ape.getConditionIdPair().remove(i); ape.getConditionIdPair().remove(i);
} }
} }
} }
public String generateSingleActionText(String conditionName, JSONObject condition){ public String generateSingleActionText(String conditionName, JSONObject condition){
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
String listeningText = ""; String listeningText = "";
StringBuffer actionText = new StringBuffer(); StringBuffer actionText = new StringBuffer();
appendActionHead(conditionName, actionText, "waiting"); appendActionHead(conditionName, actionText, "waiting");
appendCondition(conditionName, actionText, condition); appendCondition(conditionName, actionText, condition);
appendProcess(conditionName, actionText, condition); appendProcess(conditionName, actionText, condition);
listeningText = actionText.toString().replace("name=" + conditionName, "name=" +conditionName + "_listening"); listeningText = actionText.toString().replace("name=" + conditionName, "name=" +conditionName + "_listening");
listeningText = listeningText.replace("status=waiting", "states=listening"); listeningText = listeningText.replace("status=waiting", "status=listening");
actionText.append(listeningText); actionText.append(listeningText);
return actionText.toString(); return actionText.toString();
} }
public String generateCompleteActionText(JSONObject parameters, List<String> actionTextList){ public String generateCompleteActionText(JSONObject parameters, List<String> actionTextList){
Integer botId = parameters.getInteger("botId"); Integer botId = parameters.getInteger("botId");
BotInfo botInfo = helper.queryBotInfo(botId); BotInfo botInfo = helper.queryBotInfo(botId);
Boolean bothValue = true; Boolean bothValue = true;
String styleText = "", serviceURL = "", elements[], conditionName, finalText; String styleText = "", serviceURL = "", elements[], conditionName, finalText;
Set<String> conditionNameSet = new HashSet<String>(); Set<String> conditionNameSet = new HashSet<String>();
Map<String, String> macroMap = null; Map<String, String> macroMap = null;
StringBuffer postActionText = null, processText = new StringBuffer(), fullActionText = new StringBuffer(); StringBuffer postActionText = null, processText = new StringBuffer(), fullActionText = new StringBuffer();
if(botInfo == null){ if(botInfo == null){
styleText = POST_STYLE1; styleText = POST_STYLE1;
serviceURL = SERVICE_URL; serviceURL = SERVICE_URL;
}else{ }else{
if(botInfo.getBothValue().equals("1")){ if(botInfo.getBothValue().equals("1")){
styleText = POST_STYLE1; styleText = POST_STYLE1;
}else{ }else{
styleText = POST_STYLE2; styleText = POST_STYLE2;
} }
if(!botInfo.getPostURL().equals("")){ if(!botInfo.getPostURL().equals("")){
serviceURL = botInfo.getPostURL(); serviceURL = botInfo.getPostURL();
}else{ }else{
serviceURL = SERVICE_URL; serviceURL = SERVICE_URL;
} }
} }
postActionText = new StringBuffer(String.format(POST_ACTION_HEAD, styleText, serviceURL)); postActionText = new StringBuffer(String.format(POST_ACTION_HEAD, styleText, serviceURL));
for(String text:actionTextList){ for(String text:actionTextList){
for(String line:text.split("\r\n")){ for(String line:text.split("\r\n")){
if(line.startsWith("condition")){ if(line.startsWith("condition")){
//System.out.println("line====" + line); //System.out.println("line====" + line);
line = line.replace("condition", "reference"); line = line.replace("condition", "reference");
postActionText.append(line); postActionText.append(line);
postActionText.append("\r\n"); postActionText.append("\r\n");
elements = line.trim().split("\\|"); elements = line.trim().split("\\|");
conditionName = elements[0].split("=")[1].split(":")[0]; conditionName = elements[0].split("=")[1].split(":")[0];
conditionNameSet.add(conditionName); conditionNameSet.add(conditionName);
break; break;
} }
} }
} }
for(String name:conditionNameSet){ for(String name:conditionNameSet){
postActionText.append("process=nextStep="); postActionText.append("process=nextStep=");
postActionText.append(name); postActionText.append(name);
postActionText.append("|"); postActionText.append("|");
postActionText.append(name); postActionText.append(name);
postActionText.append("=clear_active|\r\n"); postActionText.append("=clear_active|\r\n");
} }
for(String actionText:actionTextList){ for(String actionText:actionTextList){
postActionText.append(actionText); postActionText.append(actionText);
} }
postActionText.append("\r\n\r\n"); postActionText.append("\r\n\r\n");
macroMap = getKeywordMacroMap(botId); macroMap = getKeywordMacroMap(botId);
finalText = postActionText.toString(); finalText = postActionText.toString();
//System.out.println(finalText); //System.out.println(finalText);
for(String macro:macroMap.keySet()){ for(String macro:macroMap.keySet()){
//专门替换三元组前面 //专门替换三元组前面
//System.out.println(macro + ":替换"); //System.out.println(macro + ":替换");
finalText = finalText.replace(macro + ",", macroMap.get(macro) + ","); finalText = finalText.replace(macro + ",", macroMap.get(macro) + ",");
} }
return finalText; return finalText;
} }
public void appendProcess(String conditionName, StringBuffer actionText, JSONObject condition){ public void appendProcess(String conditionName, StringBuffer actionText, JSONObject condition){
} }
/** /**
* *
* 构建action的头部信息,包括name、status、style、fellow等信息 * 构建action的头部信息,包括name、status、style、fellow等信息
* 其中addition_element,就是前段传的一些参数 * 其中addition_element,就是前段传的一些参数
* *
* @param actionText * @param actionText
* @param actionStatus * @param actionStatus
*/ */
public void appendActionHead(String conditionName, StringBuffer actionText, String actionStatus){ public void appendActionHead(String conditionName, StringBuffer actionText, String actionStatus){
actionText.append("\r\n\r\n"); actionText.append("\r\n\r\n");
actionText.append("name=").append(conditionName).append("\r\n"); actionText.append("name=").append(conditionName).append("\r\n");
actionText.append("status=").append(actionStatus).append("\r\n"); actionText.append("status=").append(actionStatus).append("\r\n");
actionText.append("action=select\r\n"); actionText.append("action=select\r\n");
if(AUTOMATCH_THRESHOLD != null && !AUTOMATCH_THRESHOLD.equals("")) if(AUTOMATCH_THRESHOLD != null && !AUTOMATCH_THRESHOLD.equals(""))
actionText.append("automatchthreshold=").append(AUTOMATCH_THRESHOLD).append("\r\n"); actionText.append("automatchthreshold=").append(AUTOMATCH_THRESHOLD).append("\r\n");
actionText.append(DEFAULT_STYLE).append("\r\n"); actionText.append(DEFAULT_STYLE).append("\r\n");
actionText.append("fellow=pivot_httppost\r\n"); actionText.append("fellow=pivot_httppost\r\n");
} }
public void queryCondition(JSONObject parameters){ public void queryCondition(JSONObject parameters){
int botId = parameters.getInteger("botId"); int botId = parameters.getInteger("botId");
String category = parameters.getString("category"); String category = parameters.getString("category");
String queryType = parameters.getString("queryType"); String queryType = parameters.getString("queryType");
List<Condition> conditionList = null; List<Condition> conditionList = null;
JSONObject data = new JSONObject(){ JSONObject data = new JSONObject(){
{ {
put("conditionList", new JSONArray()); put("conditionList", new JSONArray());
} }
}; };
JSONObject conditionJson = null; JSONObject conditionJson = null;
if(queryType != null && queryType.equals("category")){ if(queryType != null && queryType.equals("category")){
conditionList = helper.queryConditionByCategory(botId, category); conditionList = helper.queryConditionByCategory(botId, category);
}else{ }else{
conditionList = helper.queryConditionAll(botId); conditionList = helper.queryConditionAll(botId);
} }
for(Condition condition:conditionList){ for(Condition condition:conditionList){
conditionJson = JSON.parseObject(condition.getConditionJsonText()); conditionJson = JSON.parseObject(condition.getConditionJsonText());
conditionJson.put("conditionId", condition.getConditionId()); conditionJson.put("conditionId", condition.getConditionId());
data.getJSONArray("conditionList").add(conditionJson); data.getJSONArray("conditionList").add(conditionJson);
} }
intervalStatus = new IntervalStatus(1, "", data); intervalStatus = new IntervalStatus(1, "", data);
} }
/** /**
* 从关键词单元获取宏定义 * 从关键词单元获取宏定义
* @return * @return
*/ */
public Map<String, String>getKeywordMacroMap(Integer botId){ public Map<String, String>getKeywordMacroMap(Integer botId){
String keywordtText = engine.queryKeywordUnitText(botId); String keywordtText = engine.queryKeywordUnitText(botId);
Map<String ,String> macroMap = new HashMap<String, String>(); Map<String ,String> macroMap = new HashMap<String, String>();
String pair[] = null; String pair[] = null;
for(String line:keywordtText.split("\r\n")){ for(String line:keywordtText.split("\r\n")){
if(line.startsWith("++")){ if(line.startsWith("++")){
pair = line.split("\\|"); pair = line.split("\\|");
if(pair.length < 2) { if(pair.length < 2) {
System.out.println("宏定义非法: " + line); System.out.println("宏定义非法: " + line);
} }
else { else {
macroMap.put(pair[0], pair[1]); macroMap.put(pair[0], pair[1]);
} }
} }
} }
return macroMap; return macroMap;
} }
public void queryCategory(JSONObject parameters){ public void queryCategory(JSONObject parameters){
int botId = parameters.getInteger("botId"); int botId = parameters.getInteger("botId");
String[] categoryChain; String[] categoryChain;
List<String> conditionCategories = helper.queryConditionCategoriesById(botId); List<String> conditionCategories = helper.queryConditionCategoriesById(botId);
JSONObject categoryTree = new JSONObject(), categoryTreeJson = new JSONObject(), finalCategory = new JSONObject(); JSONObject categoryTree = new JSONObject(), categoryTreeJson = new JSONObject(), finalCategory = new JSONObject();
if(conditionCategories.size() != 0 ){ if(conditionCategories.size() != 0 ){
for(String category:conditionCategories){ for(String category:conditionCategories){
categoryChain = category.split("-"); categoryChain = category.split("-");
for(String node: categoryChain){ for(String node: categoryChain){
categoryTree.putIfAbsent(node, new JSONObject()); //设置默认子节点 categoryTree.putIfAbsent(node, new JSONObject()); //设置默认子节点
categoryTree = categoryTree.getJSONObject(node); //进入子节点 categoryTree = categoryTree.getJSONObject(node); //进入子节点
} }
} }
categoryTreeJson.putIfAbsent("-1", new JSONObject(){ categoryTreeJson.putIfAbsent("-1", new JSONObject(){
{ {
put("children", new JSONArray()); put("children", new JSONArray());
} }
}); });
constructCategoryTreeJson(categoryTree, categoryTreeJson, "-1"); constructCategoryTreeJson(categoryTree, categoryTreeJson, "-1");
finalCategory.put("category", categoryTreeJson.getJSONObject("-1").getJSONArray("children")); finalCategory.put("category", categoryTreeJson.getJSONObject("-1").getJSONArray("children"));
}else{ }else{
finalCategory.put("category", new JSONArray()); finalCategory.put("category", new JSONArray());
} }
intervalStatus = new IntervalStatus(1, "", finalCategory); intervalStatus = new IntervalStatus(1, "", finalCategory);
} }
public void query4post(JSONObject parameters){ public void query4post(JSONObject parameters){
Integer activedConditionId = -1; Integer activedConditionId = -1;
JSONArray conditionIdElem = null; JSONArray conditionIdElem = null;
String finalText = ""; String finalText = "";
JSONObject conditionJson = null; JSONObject conditionJson = null;
int botId = parameters.getInteger("botId"); int botId = parameters.getInteger("botId");
List<Condition> conditionList = helper.queryConditionAll(botId); List<Condition> conditionList = helper.queryConditionAll(botId);
List<String> conditionTextList = new ArrayList<String>(); List<String> conditionTextList = new ArrayList<String>();
ape.setConditionIdPair(new JSONArray()); ape.setConditionIdPair(new JSONArray());
for(Condition condition:conditionList){ for(Condition condition:conditionList){
if(condition.getActive().equals("1")) if(condition.getActive().equals("1"))
activedConditionId = condition.getConditionId(); activedConditionId = condition.getConditionId();
conditionTextList.add(condition.getActionText()); conditionTextList.add(condition.getActionText());
//添加condition模板id和语义关系名,用于生成关键词单元 //添加condition模板id和语义关系名,用于生成关键词单元
conditionJson = JSONObject.parseObject(condition.getConditionJsonText()); conditionJson = JSONObject.parseObject(condition.getConditionJsonText());
conditionIdElem = new JSONArray(); conditionIdElem = new JSONArray();
conditionIdElem.add(conditionJson.get("originConditionId")); conditionIdElem.add(conditionJson.get("originConditionId"));
conditionIdElem.add(conditionJson.getString("relationName").replace("-","b0").replace("0", "a0")); conditionIdElem.add(conditionJson.getString("relationName").replace("-","b0").replace("0", "a0"));
ape.getConditionIdPair().add(conditionIdElem); ape.getConditionIdPair().add(conditionIdElem);
} }
if(activedConditionId == -1 && conditionList.size() >= 1){ if(activedConditionId == -1 && conditionList.size() >= 1){
conditionTextList.set(0, conditionTextList.get(0).replace("status=waiting","status=active")); conditionTextList.set(0, conditionTextList.get(0).replace("status=waiting","status=active"));
} }
finalText = generateCompleteActionText(parameters, conditionTextList); finalText = generateCompleteActionText(parameters, conditionTextList);
ape.setActionText(finalText); ape.setActionText(finalText);
postAction(ape, null); postAction(ape, null);
} }
public void constructCategoryTreeJson(JSONObject categoryTree, JSONObject categoryTreeJson, String root){ public void constructCategoryTreeJson(JSONObject categoryTree, JSONObject categoryTreeJson, String root){
String namePair[]; String namePair[];
JSONObject node = categoryTreeJson.getJSONObject(root); JSONObject node = categoryTreeJson.getJSONObject(root);
JSONObject childNode = null; JSONObject childNode = null;
for(String key:categoryTree.keySet()){ for(String key:categoryTree.keySet()){
namePair = key.split(":"); //id:名字 namePair = key.split(":"); //id:名字
childNode = new JSONObject(); childNode = new JSONObject();
childNode.put("value", namePair[0]); childNode.put("value", namePair[0]);
childNode.put("label", namePair[1]); childNode.put("label", namePair[1]);
categoryTreeJson.put(namePair[0], node); categoryTreeJson.put(namePair[0], node);
if(!node.containsKey("children")) if(!node.containsKey("children"))
node.put("children", new JSONArray()); node.put("children", new JSONArray());
node.getJSONArray("children").add(childNode); node.getJSONArray("children").add(childNode);
constructCategoryTreeJson(categoryTree.getJSONObject(key), categoryTreeJson, namePair[0]); constructCategoryTreeJson(categoryTree.getJSONObject(key), categoryTreeJson, namePair[0]);
} }
} }
/** /**
* 将某个condition设为初始问题 * 将某个condition设为初始问题
* 将某个condition改成active, 将之前active的condition改成waiting * 将某个condition改成active, 将之前active的condition改成waiting
*/ */
public void changeActive(JSONObject parameters){ public void changeActive(JSONObject parameters){
Boolean flag = true; Boolean flag = true;
int botId = parameters.getInteger("botId"); int botId = parameters.getInteger("botId");
int activeConditionId = parameters.getInteger("activeConditionId"); int activeConditionId = parameters.getInteger("activeConditionId");
List<Condition> conditionList = new ArrayList<Condition>(); List<Condition> conditionList = new ArrayList<Condition>();
Condition oldActiveCondition = helper.queryActiveCondition(botId); Condition oldActiveCondition = helper.queryActiveCondition(botId);
if(oldActiveCondition != null){ if(oldActiveCondition != null){
oldActiveCondition.setActionText(oldActiveCondition.getActionText().replace("status=active", "status=waiting")); oldActiveCondition.setActionText(oldActiveCondition.getActionText().replace("status=active", "status=waiting"));
oldActiveCondition.setConditionJsonText(oldActiveCondition.getConditionJsonText().replace("\"active\": true", "\"active\": false")); oldActiveCondition.setConditionJsonText(oldActiveCondition.getConditionJsonText().replace("\"active\": true", "\"active\": false"));
oldActiveCondition.setActive("0"); oldActiveCondition.setActive("0");
conditionList.add(oldActiveCondition); conditionList.add(oldActiveCondition);
} }
Condition newActiveCondition = helper.queryConditionByConditionId(botId, activeConditionId); Condition newActiveCondition = helper.queryConditionByConditionId(botId, activeConditionId);
newActiveCondition.setActive("1"); newActiveCondition.setActive("1");
newActiveCondition.setActionText(newActiveCondition.getActionText().replace("status=waiting","status=active")); newActiveCondition.setActionText(newActiveCondition.getActionText().replace("status=waiting","status=active"));
newActiveCondition.setConditionJsonText(newActiveCondition.getConditionJsonText().replace( "\"active\": false", "\"active\": true")); newActiveCondition.setConditionJsonText(newActiveCondition.getConditionJsonText().replace( "\"active\": false", "\"active\": true"));
conditionList.add(newActiveCondition); conditionList.add(newActiveCondition);
flag = helper.batchUpdateCondition(botId, conditionList); flag = helper.batchUpdateCondition(botId, conditionList);
} }
public void appendCondition(String conditionName, StringBuffer actionText, JSONObject condition){ public void appendCondition(String conditionName, StringBuffer actionText, JSONObject condition){
int count = 0; int count = 0;
String relationHead = "", relationName = "", relationTail; String relationHead = "", relationName = "", relationTail;
String iteration = "1", finalText; String iteration = "1", finalText;
JSONObject questionElem = null, repeatElem = null; JSONObject questionElem = null, repeatElem = null;
StringBuffer questionText = new StringBuffer(), repeatText = new StringBuffer(), processText = new StringBuffer(); StringBuffer questionText = new StringBuffer(), repeatText = new StringBuffer(), processText = new StringBuffer();
String conditionPattern = "condition=%s:%s:%s|%s,%s,%s|%s|%s\r\n"; String conditionPattern = "condition=%s:%s:%s|%s,%s,%s|%s|%s\r\n";
relationHead = condition.getString("relationHead"); relationHead = condition.getString("relationHead");
if(relationHead.equals("")) if(relationHead.equals(""))
relationHead = "#visitorname"; relationHead = "#visitorname";
//不是问号,没有加号,且不是星号,则添加问号 //不是问号,没有加号,且不是星号,则添加问号
else if(!relationHead.equals("?") && !relationHead.startsWith("+") && !relationHead.equals("*")) else if(!relationHead.equals("?") && !relationHead.startsWith("+") && !relationHead.equals("*"))
relationHead = "+" + relationHead; relationHead = "+" + relationHead;
relationTail = condition.getString("relationTail"); relationTail = condition.getString("relationTail");
if(relationTail.equals("")) if(relationTail.equals(""))
relationTail = "#visitorname"; relationTail = "#visitorname";
else if(!relationTail.equals("?") && !relationTail.startsWith("+") && !relationHead.equals("*")) else if(!relationTail.equals("?") && !relationTail.startsWith("+") && !relationHead.equals("*"))
relationTail = "+" + relationTail; relationTail = "+" + relationTail;
relationName = condition.getString("relationName"); relationName = condition.getString("relationName");
//condition的属性 number、string、location //condition的属性 number、string、location
String dataType = condition.getString("dataType"); String dataType = condition.getString("dataType");
if(dataType != null && ! dataType.equals("")) if(dataType != null && ! dataType.equals(""))
dataType = dataType; dataType = dataType;
else else
dataType = ""; dataType = "";
//解析问题的开始轮次等 //解析问题的开始轮次等
JSONArray questionList = condition.getJSONArray("questionList"); JSONArray questionList = condition.getJSONArray("questionList");
count = questionList.size(); count = questionList.size();
for(int i = 0;i < count;i++){ for(int i = 0;i < count;i++){
if(i != 0) if(i != 0)
questionText.append("~"); questionText.append("~");
questionElem = questionList.getJSONObject(i); questionElem = questionList.getJSONObject(i);
questionText.append(questionElem.getString("que_start_time")).append(":").append(questionElem.getString("que_stop_time")); questionText.append(questionElem.getString("que_start_time")).append(":").append(questionElem.getString("que_stop_time"));
questionText.append(":").append(questionElem.getString("que_sen")); questionText.append(":").append(questionElem.getString("que_sen"));
//添加base问题 //添加base问题
if(questionElem.getInteger("base") == 1){ if(questionElem.getInteger("base") == 1){
questionText.append(":base"); questionText.append(":base");
} }
} }
//添加复述列表 //添加复述列表
JSONArray repeatList = condition.getJSONArray("repeatList"); JSONArray repeatList = condition.getJSONArray("repeatList");
count = repeatList.size(); count = repeatList.size();
for(int i = 0;i < count;i++) { for(int i = 0;i < count;i++) {
if(i != 0) if(i != 0)
repeatText.append("~"); repeatText.append("~");
repeatElem = repeatList.getJSONObject(i); repeatElem = repeatList.getJSONObject(i);
if(!repeatElem.getString("repeatKeywords").startsWith("+") && !repeatElem.getString("repeatKeywords").equals("")) if(!repeatElem.getString("repeatKeywords").startsWith("+") && !repeatElem.getString("repeatKeywords").equals(""))
repeatElem.put("repeatKeywords", "+" + repeatElem.getString("repeatKeywords")); repeatElem.put("repeatKeywords", "+" + repeatElem.getString("repeatKeywords"));
repeatText.append(repeatElem.getString("repeatString")).append("=").append(repeatElem.getString("repeatKeywords")); repeatText.append(repeatElem.getString("repeatString")).append("=").append(repeatElem.getString("repeatKeywords"));
processText.append("process=").append(conditionName).append("=").append(repeatElem.getString("repeatKeywords").split("-")[0]).append("|pivot_httppost=active|\r\n"); processText.append("process=").append(conditionName).append("=").append(repeatElem.getString("repeatKeywords").split("-")[0]).append("|pivot_httppost=active|\r\n");
} }
processText.append("process=").append(conditionName).append("=unknown|pivot_httppost=active|\r\n"); processText.append("process=").append(conditionName).append("=unknown|pivot_httppost=active|\r\n");
processText.append("process=completed=true|pivot_httppost=active|\r\n"); processText.append("process=completed=true|pivot_httppost=active|\r\n");
finalText = String.format(conditionPattern, conditionName, dataType, iteration, finalText = String.format(conditionPattern, conditionName, dataType, iteration,
relationHead, relationName, relationTail, questionText.toString(), repeatText.toString()); relationHead, relationName, relationTail, questionText.toString(), repeatText.toString());
actionText.append(finalText); actionText.append(finalText);
actionText.append(processText.toString()); actionText.append(processText.toString());
} }
/** /**
* 更新rule并且监测condition模板中的base问题和style是否发生变化 * 更新rule并且监测condition模板中的base问题和style是否发生变化
* @param parameters * @param parameters
*/ */
public void updateRelation(JSONObject parameters){ public void updateRelation(JSONObject parameters){
int botId = parameters.getInteger("botId"), len, baseIdx1 = 0, baseIdx2 = 0, originConditionId; int botId = parameters.getInteger("botId"), len, baseIdx1 = 0, baseIdx2 = 0, originConditionId;
Boolean updateFlag = false; Boolean updateFlag = false;
JSONObject conditionJson = new JSONObject(), patternConditionJson, questionDict; JSONObject conditionJson = new JSONObject(), patternConditionJson, questionDict;
String relation = ""; String relation = "";
List<Condition> conditionList = helper.queryConditionAll(botId); List<Condition> conditionList = helper.queryConditionAll(botId);
List<String> conditionRelationList = new ArrayList<String>(); List<String> conditionRelationList = new ArrayList<String>();
List<JSONObject> conditionJsonList = new ArrayList<JSONObject>(); List<JSONObject> conditionJsonList = new ArrayList<JSONObject>();
intervalStatus = updateKnowledgeUnit(botId, new HashMap<String, String>(){{put("options", OPTIONS);put("idlelimit",IDLE_LIMIT);}}, null, null); intervalStatus = updateKnowledgeUnit(botId, new HashMap<String, String>(){{put("options", OPTIONS);put("idlelimit",IDLE_LIMIT);}}, null, null);
if(intervalStatus.getStatus() == 1) { if(intervalStatus.getStatus() == 1) {
for (Condition condition : conditionList) { for (Condition condition : conditionList) {
conditionJson = JSONObject.parseObject(condition.getConditionJsonText()); conditionJson = JSONObject.parseObject(condition.getConditionJsonText());
conditionJson.put("conditionId", condition.getConditionId()); conditionJson.put("conditionId", condition.getConditionId());
relation = conditionJson.getString("relationName").replace("0", "a0").replace("-", "b0"); relation = conditionJson.getString("relationName").replace("0", "a0").replace("-", "b0");
conditionRelationList.add(relation); conditionRelationList.add(relation);
conditionJsonList.add(conditionJson); conditionJsonList.add(conditionJson);
} }
Map<Integer, String> patternTextMap = engine.queryConditionPatternText(botId, conditionRelationList); Map<Integer, String> patternTextMap = engine.queryConditionPatternText(botId, conditionRelationList);
for (JSONObject condtiionJson : conditionJsonList) { for (JSONObject condtiionJson : conditionJsonList) {
originConditionId = conditionJson.getInteger("originConditionId"); originConditionId = conditionJson.getInteger("originConditionId");
updateFlag = false; updateFlag = false;
if (patternTextMap.get(originConditionId) != null && intervalStatus.getStatus() == 1) { if (patternTextMap.get(originConditionId) != null && intervalStatus.getStatus() == 1) {
patternConditionJson = ActionParser.parse(patternTextMap.get(originConditionId)); patternConditionJson = ActionParser.parse(patternTextMap.get(originConditionId));
//分别找到condition的base问题 //分别找到condition的base问题
len = conditionJson.getJSONArray("questionList").size(); len = conditionJson.getJSONArray("questionList").size();
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++) {
questionDict = conditionJson.getJSONArray("questionList").getJSONObject(i); questionDict = conditionJson.getJSONArray("questionList").getJSONObject(i);
if (questionDict.getInteger("base") == 1) { if (questionDict.getInteger("base") == 1) {
baseIdx1 = i; baseIdx1 = i;
break; break;
} }
} }
len = patternConditionJson.getJSONArray("questionList").size(); len = patternConditionJson.getJSONArray("questionList").size();
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++) {
questionDict = patternConditionJson.getJSONArray("questionList").getJSONObject(i); questionDict = patternConditionJson.getJSONArray("questionList").getJSONObject(i);
if (questionDict.getInteger("base") == 1) { if (questionDict.getInteger("base") == 1) {
baseIdx2 = i; baseIdx2 = i;
break; break;
} }
} }
//如果关于base问题的两个json数据不一样,就更新数据 //如果关于base问题的两个json数据不一样,就更新数据
if (!conditionJson.getJSONArray("questionList").getJSONObject(baseIdx1).equals(patternConditionJson.getJSONArray("questionList").getJSONObject(baseIdx2))) { if (!conditionJson.getJSONArray("questionList").getJSONObject(baseIdx1).equals(patternConditionJson.getJSONArray("questionList").getJSONObject(baseIdx2))) {
conditionJson.getJSONArray("questionList").set(baseIdx1, patternConditionJson.getJSONArray("questionList").getJSONObject(baseIdx2)); conditionJson.getJSONArray("questionList").set(baseIdx1, patternConditionJson.getJSONArray("questionList").getJSONObject(baseIdx2));
updateFlag = true; updateFlag = true;
} }
//如果关于style的json数据不一致,就更新styleList //如果关于style的json数据不一致,就更新styleList
if (!conditionJson.getJSONArray("styleList").equals(patternConditionJson.getJSONArray("styleList"))) { if (!conditionJson.getJSONArray("styleList").equals(patternConditionJson.getJSONArray("styleList"))) {
conditionJson.put("styleList", patternConditionJson.getJSONArray("styleList")); conditionJson.put("styleList", patternConditionJson.getJSONArray("styleList"));
updateFlag = true; updateFlag = true;
} }
if (updateFlag) { if (updateFlag) {
parameters.put("conditionData", conditionJson); parameters.put("conditionData", conditionJson);
intervalStatus = updateCondition(parameters); intervalStatus = updateCondition(parameters);
} }
} }
} }
} }
} }
/** /**
* 更新关键词单元, * 更新关键词单元,
* @param botId * @param botId
* @param extraKeyword 额外需要更新的关键词 * @param extraKeyword 额外需要更新的关键词
* @param appendMacro 在宏定义中添加关键词 * @param appendMacro 在宏定义中添加关键词
* @param POS * @param POS
*/ */
public IntervalStatus updateKnowledgeUnit(int botId, Map<String, String> extraKeyword, Map<String, StringBuffer> appendMacro, String POS){ public IntervalStatus updateKnowledgeUnit(int botId, Map<String, String> extraKeyword, Map<String, StringBuffer> appendMacro, String POS){
StringBuffer newKeywords = new StringBuffer(); StringBuffer newKeywords = new StringBuffer();
IntervalStatus intervalStatus = null; IntervalStatus intervalStatus = null;
Boolean flag; Boolean flag;
String keywordUnitText = engine.queryKeywordUnitText(botId), keywordPair[]; String keywordUnitText = engine.queryKeywordUnitText(botId), keywordPair[];
for(String line:keywordUnitText.split("\r\n")){ for(String line:keywordUnitText.split("\r\n")){
if (line.startsWith("options|") || line.trim().equals("") || line.startsWith("idlelimit")) if (line.startsWith("options|") || line.trim().equals("") || line.startsWith("idlelimit"))
continue; continue;
//修改关键词单元时应该修改version //修改关键词单元时应该修改version
if(line.startsWith("$version")) { if(line.startsWith("$version")) {
newKeywords.append("$version|").append(System.currentTimeMillis()).append("\r\n"); newKeywords.append("$version|").append(System.currentTimeMillis()).append("\r\n");
continue; continue;
} }
newKeywords.append(line); newKeywords.append(line);
if(line.startsWith("++")){ if(line.startsWith("++")){
keywordPair = line.split("\\|"); keywordPair = line.split("\\|");
if(appendMacro != null && appendMacro.containsKey(keywordPair[0])){ if(appendMacro != null && appendMacro.containsKey(keywordPair[0])){
newKeywords.append("+").append(appendMacro.get(keywordPair[0]).toString()); newKeywords.append("+").append(appendMacro.get(keywordPair[0]).toString());
} }
} }
newKeywords.append("\r\n"); newKeywords.append("\r\n");
} }
if(extraKeyword != null) { if(extraKeyword != null) {
for (String key : extraKeyword.keySet()) { for (String key : extraKeyword.keySet()) {
newKeywords.append(key).append("|").append(extraKeyword.get(key)); newKeywords.append(key).append("|").append(extraKeyword.get(key));
if (key.equals("options")) { if (key.equals("options")) {
BotInfo botInfo = helper.queryBotInfo(botId); BotInfo botInfo = helper.queryBotInfo(botId);
//是否将用户回答传给后台 //是否将用户回答传给后台
if (botInfo.getQueryTextTransfer().equals("1")) if (botInfo.getQueryTextTransfer().equals("1"))
newKeywords.append(",query_text_transfer"); newKeywords.append(",query_text_transfer");
} }
newKeywords.append("\r\n"); newKeywords.append("\r\n");
} }
} }
if(POS != null){ if(POS != null){
newKeywords.append(POS); newKeywords.append(POS);
} }
flag = engine.updateKeywordUnitText(botId, newKeywords.toString()); flag = engine.updateKeywordUnitText(botId, newKeywords.toString());
if(flag || keywordUnitText.equals(newKeywords.toString())) if(flag || keywordUnitText.equals(newKeywords.toString()))
intervalStatus = new IntervalStatus(1, ""); intervalStatus = new IntervalStatus(1, "");
else else
intervalStatus = new IntervalStatus(0, UPDATE_KEYWORD_ERROR); intervalStatus = new IntervalStatus(0, UPDATE_KEYWORD_ERROR);
return intervalStatus; return intervalStatus;
} }
public void createBot(JSONObject data, String authorization){ public void createBot(JSONObject data, String authorization){
//新建bot //新建bot
ActionPostElem ape = new ActionPostElem("", -1, data.getString("botName_yhm"), data.getString("catName"), authorization, data.getString("botType")); ActionPostElem ape = new ActionPostElem("", -1, data.getString("botName_yhm"), data.getString("catName"), authorization, data.getString("botType"));
postAction(ape, null); postAction(ape, null);
if(intervalStatus.getStatus() == 1){ if(intervalStatus.getStatus() == 1){
((JSONObject)intervalStatus.getExtraData()).put("botId", ape.getBotId()); ((JSONObject)intervalStatus.getExtraData()).put("botId", ape.getBotId());
((JSONObject)intervalStatus.getExtraData()).put("botAccount", engine.queryBotAccountByBotId(ape.getBotId())); ((JSONObject)intervalStatus.getExtraData()).put("botAccount", engine.queryBotAccountByBotId(ape.getBotId()));
BotInfo botInfo = new BotInfo(ape.getBotId(), "", "", "", "", "1", "1"); BotInfo botInfo = new BotInfo(ape.getBotId(), "", "", "", "", "1", "1");
helper.insertBotInfo(botInfo); helper.insertBotInfo(botInfo);
} }
} }
public void queryBotInfo(JSONObject parameters){ public void queryBotInfo(JSONObject parameters){
int botId = parameters.getInteger("botId"); int botId = parameters.getInteger("botId");
BotInfo botInfo = helper.queryBotInfo(botId); BotInfo botInfo = helper.queryBotInfo(botId);
JSONArray returnList = new JSONArray(); JSONArray returnList = new JSONArray();
if(botInfo != null) { if(botInfo != null) {
//List<String[]> returnList = new ArrayList<String[]>(); //List<String[]> returnList = new ArrayList<String[]>();
returnList.add(new JSONArray(){{ returnList.add(new JSONArray(){{
add("bothValue"); add("bothValue");
add("将三元组两边的值都传给后台"); add("将三元组两边的值都传给后台");
add(botInfo.getBothValue()); add(botInfo.getBothValue());
}}); }});
returnList.add(new JSONArray(){{ returnList.add(new JSONArray(){{
add("queryTextTransfer"); add("queryTextTransfer");
add("将问句传给后台"); add("将问句传给后台");
add(botInfo.getQueryTextTransfer()); add(botInfo.getQueryTextTransfer());
}}); }});
intervalStatus = new IntervalStatus(1, "", returnList); intervalStatus = new IntervalStatus(1, "", returnList);
}else{ }else{
intervalStatus = new IntervalStatus(0, "查询失败"); intervalStatus = new IntervalStatus(0, "查询失败");
} }
} }
public IntervalStatus deleteCondition(JSONObject data, String authorization){ public IntervalStatus deleteCondition(JSONObject data, String authorization){
int conditionId = data.getInteger("conditionId"); int conditionId = data.getInteger("conditionId");
int botId = data.getInteger("botId"); int botId = data.getInteger("botId");
IntervalStatus intervalStatus = null; IntervalStatus intervalStatus = null;
Condition condition = helper.queryConditionByConditionId(botId, conditionId); Condition condition = helper.queryConditionByConditionId(botId, conditionId);
JSONObject conditionJson = JSONObject.parseObject(condition.getConditionJsonText()); JSONObject conditionJson = JSONObject.parseObject(condition.getConditionJsonText());
Boolean flag = helper.deleteConditionBy2Id(botId, conditionId); Boolean flag = helper.deleteConditionBy2Id(botId, conditionId);
if(flag){ if(flag){
deleteIdElemIfExist(conditionJson.getInteger("originConditionId")); deleteIdElemIfExist(conditionJson.getInteger("originConditionId"));
intervalStatus = new IntervalStatus(1, ""); intervalStatus = new IntervalStatus(1, "");
}else{ }else{
intervalStatus = new IntervalStatus(0, "删除失败"); intervalStatus = new IntervalStatus(0, "删除失败");
} }
return intervalStatus; return intervalStatus;
} }
public IntervalStatus updateCondition(JSONObject parameters){ public IntervalStatus updateCondition(JSONObject parameters){
IntervalStatus intervalStatus = null; IntervalStatus intervalStatus = null;
Integer botId = parameters.getInteger("botId"), conditionId, displayOrder; Integer botId = parameters.getInteger("botId"), conditionId, displayOrder;
String categoryStr, actionText, conditionName, conditionJsonText, active; String categoryStr, actionText, conditionName, conditionJsonText, active;
Boolean flag; Boolean flag;
JSONObject conditionData = parameters.getJSONObject("conditionData"); JSONObject conditionData = parameters.getJSONObject("conditionData");
conditionId = conditionData.getInteger("conditionId"); conditionId = conditionData.getInteger("conditionId");
conditionName = conditionData.getString("conditionName"); conditionName = conditionData.getString("conditionName");
categoryStr = conditionData.getString("conditionCategory"); categoryStr = conditionData.getString("conditionCategory");
displayOrder = conditionData.getInteger("displayOrder"); displayOrder = conditionData.getInteger("displayOrder");
active = conditionData.getBoolean("active") ? "1":"0"; active = conditionData.getBoolean("active") ? "1":"0";
conditionJsonText = conditionData.toJSONString(); conditionJsonText = conditionData.toJSONString();
actionText = generateSingleActionText(conditionName, conditionData); actionText = generateSingleActionText(conditionName, conditionData);
Condition condition = new Condition(botId, conditionId, conditionJsonText, actionText, categoryStr, active, displayOrder); Condition condition = new Condition(botId, conditionId, conditionJsonText, actionText, categoryStr, active, displayOrder);
flag = helper.updateConditionById(condition); flag = helper.updateConditionById(condition);
if(!flag){ if(!flag){
condition = helper.queryConditionByConditionId(botId, conditionId); condition = helper.queryConditionByConditionId(botId, conditionId);
if(condition != null && condition.getConditionJsonText().equals(conditionJsonText)){ if(condition != null && condition.getConditionJsonText().equals(conditionJsonText)){
flag = true; flag = true;
} }
} }
if(flag){ if(flag){
intervalStatus = new IntervalStatus(1, "success"); intervalStatus = new IntervalStatus(1, "success");
}else{ }else{
intervalStatus = new IntervalStatus(0, "修改失败"); intervalStatus = new IntervalStatus(0, "修改失败");
} }
return intervalStatus; return intervalStatus;
} }
/** /**
* 将生成的action文本提交到周志宇处 * 将生成的action文本提交到周志宇处
* @param ape * @param ape
* @return * @return
*/ */
public void postAction(ActionPostElem ape, String gameEditorSessionId){ public void postAction(ActionPostElem ape, String gameEditorSessionId){
String url = CONDITION_BACKEND_URL + "/post/actions"; String url = CONDITION_BACKEND_URL + "/post/actions";
JSONObject retData = null; JSONObject retData = null;
Integer statusCode = 0; Integer statusCode = 0;
JSONObject postData = new JSONObject(); JSONObject postData = new JSONObject();
postData.put("botname", ape.getBotName()); postData.put("botname", ape.getBotName());
postData.put("actions", ape.getActionText()); postData.put("actions", ape.getActionText());
postData.put("catName", ape.getCategoryName()); postData.put("catName", ape.getCategoryName());
postData.put("cdt_name_ls", ape.getConditionIdPair()); postData.put("cdt_name_ls", ape.getConditionIdPair());
postData.put("id", ape.getBotId()); postData.put("id", ape.getBotId());
//新建bot时不传botId //新建bot时不传botId
if(ape.getBotId() == -1){ if(ape.getBotId() == -1){
postData.remove("id"); postData.remove("id");
} }
if(!ape.getBotType().equals("")) if(!ape.getBotType().equals(""))
postData.put("project", ape.getBotType()); postData.put("project", ape.getBotType());
if(gameEditorSessionId != null){ if(gameEditorSessionId != null){
postData.put("gameEditorSessionId", gameEditorSessionId); postData.put("gameEditorSessionId", gameEditorSessionId);
} }
try { try {
retData = SimpleUtil.postJSON(url, postData, ape.getAuthorization()); retData = SimpleUtil.postJSON(url, postData, ape.getAuthorization());
}catch (UnsupportedEncodingException e){ }catch (UnsupportedEncodingException e){
retData = new JSONObject(){ retData = new JSONObject(){
{ {
put("status_code", -1); put("status_code", -1);
} }
}; };
} }
//System.out.println(retData.toJSONString()); //System.out.println(retData.toJSONString());
switch(retData.getInteger("status_code")){ switch(retData.getInteger("status_code")){
case 200: case 200:
switch(retData.getString("status")){ switch(retData.getString("status")){
case "Success": case "Success":
ape.setBotId(retData.getInteger("id")); ape.setBotId(retData.getInteger("id"));
intervalStatus = new IntervalStatus(1, "", new JSONObject()); intervalStatus = new IntervalStatus(1, "", new JSONObject());
break; break;
case "Fail": case "Fail":
intervalStatus = new IntervalStatus(0, retData.getString("reason")); intervalStatus = new IntervalStatus(0, retData.getString("reason"));
break; break;
} }
break; break;
case 401: case 401:
intervalStatus = new IntervalStatus(0, TOKEN_TIME_OUT); intervalStatus = new IntervalStatus(0, TOKEN_TIME_OUT);
break; break;
case 500: case 500:
intervalStatus = new IntervalStatus(0, CONDITION_BACKEND_ERROR); intervalStatus = new IntervalStatus(0, CONDITION_BACKEND_ERROR);
default: default:
intervalStatus = new IntervalStatus(0, CONDITION_BACKEND_ERROR); intervalStatus = new IntervalStatus(0, CONDITION_BACKEND_ERROR);
} }
} }
public void gamePlotInit(String botName, int botId, String auth, JSONObject parameters, String startCondition, Map<String, HashSet<String>> conditionExtraKeywords){ public void gamePlotInit(String botName, int botId, String auth, JSONObject parameters, String startCondition, Map<String, HashSet<String>> conditionExtraKeywords){
Boolean flag = true; Boolean flag = true;
String elem[], postfix, conditionName, keywordPosition, actionText, relationName, finalText, activeFlag; String elem[], postfix, conditionName, keywordPosition, actionText, relationName, finalText, activeFlag;
PlatformUtils platformUtils = null; PlatformUtils platformUtils = null;
JSONObject patternConditionJson = null, conditionJson = null; JSONObject patternConditionJson = null, conditionJson = null;
List<Integer> idList = new ArrayList<Integer>(); List<Integer> idList = new ArrayList<Integer>();
List<String> actionTextList = new ArrayList<String>(); List<String> actionTextList = new ArrayList<String>();
List<Condition> conditionList = new ArrayList<Condition>(); List<Condition> conditionList = new ArrayList<Condition>();
JSONArray conditionData = new JSONArray(), conditionPostPair = new JSONArray(); JSONArray conditionData = new JSONArray(), conditionPostPair = new JSONArray();
Map<Integer, EngineUnit> id2unit = null; Map<Integer, EngineUnit> id2unit = null;
Map<String, StringBuffer> macroMap = null, macroAppendMap = new HashMap<String, StringBuffer>(); Map<String, StringBuffer> macroMap = null, macroAppendMap = new HashMap<String, StringBuffer>();
try{ try{
platformUtils = new PlatformUtils(); platformUtils = new PlatformUtils();
//helper.deleteUserData(botId); //helper.deleteUserData(botId);
idList = platformUtils.queryConditionIdByTypetreeId(parameters.getJSONArray("conditionCategories")); idList = platformUtils.queryConditionIdByTypetreeId(parameters.getJSONArray("conditionCategories"));
id2unit = engine.queryUnitsByIdList(idList); id2unit = engine.queryUnitsByIdList(idList);
for(Integer id:id2unit.keySet()){ for(Integer id:id2unit.keySet()){
patternConditionJson = ActionParser.parse(id2unit.get(id).getActions()); patternConditionJson = ActionParser.parse(id2unit.get(id).getActions());
patternConditionJson.put("originConditionId", id); patternConditionJson.put("originConditionId", id);
patternConditionJson.put("active", false); patternConditionJson.put("active", false);
patternConditionJson.put("conditionCategory", "0:默认"); patternConditionJson.put("conditionCategory", "0:默认");
relationName = patternConditionJson.getString("relationName").replace("0", "a0").replace("-", "b0"); relationName = patternConditionJson.getString("relationName").replace("0", "a0").replace("-", "b0");
conditionExtraKeywords.putIfAbsent(DEFAULT_CONDITION + "_head", new HashSet<String>()); conditionExtraKeywords.putIfAbsent(DEFAULT_CONDITION + "_head", new HashSet<String>());
conditionExtraKeywords.putIfAbsent(DEFAULT_CONDITION + "_tail", new HashSet<String>()); conditionExtraKeywords.putIfAbsent(DEFAULT_CONDITION + "_tail", new HashSet<String>());
for(int i = 1;i < 10;i++){ for(int i = 1;i < 10;i++){
//给condition的名字添加后缀,因为游戏中可能用到condition的复制,但值域和名字不一样 //给condition的名字添加后缀,因为游戏中可能用到condition的复制,但值域和名字不一样
if(i == 1) if(i == 1)
postfix = ""; postfix = "";
else else
postfix = String.valueOf(i); postfix = String.valueOf(i);
activeFlag = "0"; activeFlag = "0";
conditionJson = (JSONObject) patternConditionJson.clone(); conditionJson = (JSONObject) patternConditionJson.clone();
conditionName = conditionJson.getString("conditionName") + postfix; conditionName = conditionJson.getString("conditionName") + postfix;
if(!conditionExtraKeywords.containsKey(conditionName + "_tail")){ //如果没有用到这个condition,就跳过 if(!conditionExtraKeywords.containsKey(conditionName + "_tail")){ //如果没有用到这个condition,就跳过
break; break;
} }
conditionJson.put("conditionName", conditionName); conditionJson.put("conditionName", conditionName);
if(conditionJson.getString("relationHead").equals("?")) if(conditionJson.getString("relationHead").equals("?"))
keywordPosition = "left"; keywordPosition = "left";
else else
keywordPosition = "right"; keywordPosition = "right";
flag = conditionAppendKeyword(conditionName, conditionJson, conditionExtraKeywords, macroAppendMap); flag = conditionAppendKeyword(conditionName, conditionJson, conditionExtraKeywords, macroAppendMap);
if(conditionJson.getBoolean("active") && !conditionName.equals(startCondition)) if(conditionJson.getBoolean("active") && !conditionName.equals(startCondition))
conditionJson.put("active", false); conditionJson.put("active", false);
actionText = generateSingleActionText(conditionName, conditionJson); actionText = generateSingleActionText(conditionName, conditionJson);
if(startCondition.equals(conditionName)) { if(startCondition.equals(conditionName)) {
conditionJson.put("active", true); conditionJson.put("active", true);
actionText = actionText.replace("status=waiting", "status=active"); actionText = actionText.replace("status=waiting", "status=active");
activeFlag = "1"; activeFlag = "1";
} }
conditionList.add(new Condition(botId, conditionJson.toJSONString(), actionText, conditionJson.getString("conditionCategory"), activeFlag)); conditionList.add(new Condition(botId, conditionJson.toJSONString(), actionText, conditionJson.getString("conditionCategory"), activeFlag));
actionTextList.add(actionText); actionTextList.add(actionText);
conditionData.add(conditionJson); conditionData.add(conditionJson);
String finalRelationName = relationName; String finalRelationName = relationName;
conditionPostPair.add(new JSONArray(){ conditionPostPair.add(new JSONArray(){
{ {
add(id); add(id);
add(finalRelationName); add(finalRelationName);
} }
}); });
} }
} }
parameters.put("conditionData", conditionData); parameters.put("conditionData", conditionData);
//第一次提交,获取关键词单元的数据 //第一次提交,获取关键词单元的数据
ape = new ActionPostElem(botId, botName, "", auth, "", conditionPostPair); ape = new ActionPostElem(botId, botName, "", auth, "", conditionPostPair);
postAction(ape, parameters.getString("gameEditorSessionId")); postAction(ape, parameters.getString("gameEditorSessionId"));
if(intervalStatus.getStatus() == 1) { if(intervalStatus.getStatus() == 1) {
helper.batchInsertCondition(conditionList); helper.batchInsertCondition(conditionList);
//insertCondition(parameters); //insertCondition(parameters);
if (intervalStatus.getStatus() == 1) { if (intervalStatus.getStatus() == 1) {
engine.updateWelcomeText(botId, parameters.getString("welcome")); engine.updateWelcomeText(botId, parameters.getString("welcome"));
updateKnowledgeUnit(botId, new HashMap<String, String>() {{ updateKnowledgeUnit(botId, new HashMap<String, String>() {{
put("options", OPTIONS); put("options", OPTIONS);
put("idlelimit", IDLE_LIMIT); put("idlelimit", IDLE_LIMIT);
}}, macroAppendMap, parameters.getString("POS")); }}, macroAppendMap, parameters.getString("POS"));
} }
} }
if(intervalStatus.getStatus() == 1) { if(intervalStatus.getStatus() == 1) {
finalText = generateCompleteActionText(parameters, actionTextList); finalText = generateCompleteActionText(parameters, actionTextList);
//替换宏定义后生成完整的action文本再提交一次 //替换宏定义后生成完整的action文本再提交一次
ape = new ActionPostElem(botId, botName, finalText, auth, "", conditionPostPair); ape = new ActionPostElem(botId, botName, finalText, auth, "", conditionPostPair);
postAction(ape, parameters.getString("gameEditorSessionId")); postAction(ape, parameters.getString("gameEditorSessionId"));
if (intervalStatus.getStatus() == 1) { if (intervalStatus.getStatus() == 1) {
engine.updateWelcomeText(botId, parameters.getString("welcome")); engine.updateWelcomeText(botId, parameters.getString("welcome"));
updateKnowledgeUnit(botId, new HashMap<String, String>() {{ updateKnowledgeUnit(botId, new HashMap<String, String>() {{
put("options", OPTIONS); put("options", OPTIONS);
put("idlelimit", IDLE_LIMIT); put("idlelimit", IDLE_LIMIT);
}}, macroAppendMap, parameters.getString("POS")); }}, macroAppendMap, parameters.getString("POS"));
} }
} }
}catch (SQLException e){ }catch (SQLException e){
intervalStatus = new IntervalStatus(0, ACTION_TEXT_GENERATE_ERROR); intervalStatus = new IntervalStatus(0, ACTION_TEXT_GENERATE_ERROR);
System.out.println(e.getMessage()); System.out.println(e.getMessage());
e.printStackTrace(); e.printStackTrace();
}finally { }finally {
platformUtils.destroy(); platformUtils.destroy();
} }
} }
public void getBotConditionInfo(int botId, String botName, String auth){ public void getBotConditionInfo(int botId, String botName, String auth){
String url = CONDITION_BACKEND_URL + "/get/actions/" + String.valueOf(botId); String url = CONDITION_BACKEND_URL + "/get/actions/" + String.valueOf(botId);
Integer statusCode; Integer statusCode;
JSONObject receiveData = SimpleUtil.getMethod(url, auth); JSONObject receiveData = SimpleUtil.getMethod(url, auth);
IntervalStatus intervalStatus = null; IntervalStatus intervalStatus = null;
ape = new ActionPostElem(botId, botName, auth); ape = new ActionPostElem(botId, botName, auth);
statusCode = receiveData.getInteger("status_code"); statusCode = receiveData.getInteger("status_code");
//System.out.println(receiveData.toJSONString()); //System.out.println(receiveData.toJSONString());
switch(statusCode){ switch(statusCode){
case 200: case 200:
ape.setCategoryName(receiveData.getString("catName")); ape.setCategoryName(receiveData.getString("catName"));
ape.setConditionIdPair(receiveData.getJSONArray("cdt_name_ls")); ape.setConditionIdPair(receiveData.getJSONArray("cdt_name_ls"));
intervalStatus = new IntervalStatus(1, ""); intervalStatus = new IntervalStatus(1, "");
break; break;
case 401: case 401:
intervalStatus = new IntervalStatus(0,"token过期了"); intervalStatus = new IntervalStatus(0,"token过期了");
break; break;
default: default:
intervalStatus = new IntervalStatus(0, "condition后台报错"); intervalStatus = new IntervalStatus(0, "condition后台报错");
break; break;
} }
} }
public Boolean conditionAppendKeyword(String conditionName, JSONObject conditionJson, Map<String, HashSet<String>> conditionExtraKeywords, Map<String, StringBuffer> macroAppendMap ){ public Boolean conditionAppendKeyword(String conditionName, JSONObject conditionJson, Map<String, HashSet<String>> conditionExtraKeywords, Map<String, StringBuffer> macroAppendMap ){
String relationHead = conditionJson.getString("relationHead"); String relationHead = conditionJson.getString("relationHead");
String repeatKeywords = conditionJson.getJSONArray("repeatList").getJSONObject(0).getString("repeatKeywords").split("-")[0]; String repeatKeywords = conditionJson.getJSONArray("repeatList").getJSONObject(0).getString("repeatKeywords").split("-")[0];
String extraKeywords = Joiner.on("+").join(conditionExtraKeywords.get(conditionName + "_head")); String extraKeywords = Joiner.on("+").join(conditionExtraKeywords.get(conditionName + "_head"));
//condition原来的值域是一个宏定义 //condition原来的值域是一个宏定义
if(relationHead.startsWith("++")){ if(relationHead.startsWith("++")){
//要添加的关键词不为空 //要添加的关键词不为空
if(!extraKeywords.equals("")) { if(!extraKeywords.equals("")) {
if (macroAppendMap.containsKey(relationHead)) { if (macroAppendMap.containsKey(relationHead)) {
macroAppendMap.get(relationHead).append(extraKeywords); macroAppendMap.get(relationHead).append(extraKeywords);
} else { } else {
macroAppendMap.put(relationHead, new StringBuffer(extraKeywords)); macroAppendMap.put(relationHead, new StringBuffer(extraKeywords));
} }
} }
}else{ }else{
conditionJson.put("relationHead", extraKeywords); conditionJson.put("relationHead", extraKeywords);
} }
//将三元组头部的限定词替换为游戏中使用的关键词,如果为*,则不替换 //将三元组头部的限定词替换为游戏中使用的关键词,如果为*,则不替换
//if(!conditionJson.getString("relationHead").equals("*")) //if(!conditionJson.getString("relationHead").equals("*"))
extraKeywords = Joiner.on("+").join(conditionExtraKeywords.get(conditionName + "_tail")); extraKeywords = Joiner.on("+").join(conditionExtraKeywords.get(conditionName + "_tail"));
if(repeatKeywords.startsWith("++")){ if(repeatKeywords.startsWith("++")){
//要添加的关键词不为空 //要添加的关键词不为空
if(!repeatKeywords.equals("")) { if(!repeatKeywords.equals("")) {
if (macroAppendMap.containsKey(repeatKeywords)) { if (macroAppendMap.containsKey(repeatKeywords)) {
macroAppendMap.get(repeatKeywords).append(extraKeywords); macroAppendMap.get(repeatKeywords).append(extraKeywords);
} else { } else {
macroAppendMap.put(repeatKeywords, new StringBuffer(extraKeywords)); macroAppendMap.put(repeatKeywords, new StringBuffer(extraKeywords));
} }
} }
}else { }else {
conditionJson.getJSONArray("repeatList").getJSONObject(0).put("repeatKeywords", extraKeywords); conditionJson.getJSONArray("repeatList").getJSONObject(0).put("repeatKeywords", extraKeywords);
} }
return true; return true;
} }
public Set<String> getConditionNameSet(List<Condition> conditionList){ public Set<String> getConditionNameSet(List<Condition> conditionList){
String elements[]; String elements[];
String conditionName; String conditionName;
Set<String> conditionNameSet = new HashSet<String>(); Set<String> conditionNameSet = new HashSet<String>();
for(Condition condition:conditionList){ for(Condition condition:conditionList){
for(String line:condition.getActionText().split("\r\n")){ for(String line:condition.getActionText().split("\r\n")){
if(line.startsWith("condition")){ if(line.startsWith("condition")){
elements = line.trim().split("\\|"); elements = line.trim().split("\\|");
conditionName = elements[0].split("=")[1].split(":")[0]; conditionName = elements[0].split("=")[1].split(":")[0];
conditionNameSet.add(conditionName); conditionNameSet.add(conditionName);
break; break;
} }
} }
} }
return conditionNameSet; return conditionNameSet;
} }
public String getConditionName(Condition condition){ public String getConditionName(Condition condition){
String elements[]; String elements[];
String conditionName = ""; String conditionName = "";
for(String line:condition.getActionText().split("\r\n")){ for(String line:condition.getActionText().split("\r\n")){
if(line.startsWith("condition")){ if(line.startsWith("condition")){
elements = line.trim().split("\\|"); elements = line.trim().split("\\|");
conditionName = elements[0].split("=")[1].split(":")[0]; conditionName = elements[0].split("=")[1].split(":")[0];
break; break;
} }
} }
return conditionName; return conditionName;
} }
/** /**
* 更新condition的名字 * 更新condition的名字
* @param parameters * @param parameters
* @return * @return
*/ */
public String updateConditionName(JSONObject parameters){ public String updateConditionName(JSONObject parameters){
int botId = parameters.getInteger("botId"); int botId = parameters.getInteger("botId");
int conditioId = parameters.getInteger("conditionId"); int conditioId = parameters.getInteger("conditionId");
Boolean flag = true; Boolean flag = true;
String conditionName = parameters.getString("conditionName"), actionText = ""; String conditionName = parameters.getString("conditionName"), actionText = "";
Condition condition = helper.queryConditionByConditionId(botId, conditioId); Condition condition = helper.queryConditionByConditionId(botId, conditioId);
JSONObject conditionJson = JSONObject.parseObject(condition.getConditionJsonText()); JSONObject conditionJson = JSONObject.parseObject(condition.getConditionJsonText());
List<Condition> conditionList = helper.queryConditionAll(botId); List<Condition> conditionList = helper.queryConditionAll(botId);
Set<String> conditionNameSet = getConditionNameSet(conditionList); Set<String> conditionNameSet = getConditionNameSet(conditionList);
if(conditionNameSet.contains(conditionName)){ if(conditionNameSet.contains(conditionName)){
intervalStatus = new IntervalStatus(0, CONDITION_NAME_DUMPLICATE); intervalStatus = new IntervalStatus(0, CONDITION_NAME_DUMPLICATE);
}else{ }else{
conditionJson.put("conditionName", conditionName); conditionJson.put("conditionName", conditionName);
actionText = generateSingleActionText(conditionName, conditionJson); actionText = generateSingleActionText(conditionName, conditionJson);
condition.setActionText(actionText); condition.setActionText(actionText);
condition.setConditionJsonText(conditionJson.toJSONString()); condition.setConditionJsonText(conditionJson.toJSONString());
flag = helper.updateConditionById(condition); flag = helper.updateConditionById(condition);
if(!flag){ if(!flag){
intervalStatus = new IntervalStatus(0, CONDITION_NAME_UPDATE_ERROR); intervalStatus = new IntervalStatus(0, CONDITION_NAME_UPDATE_ERROR);
}else{ }else{
intervalStatus = new IntervalStatus(1, ""); intervalStatus = new IntervalStatus(1, "");
} }
} }
return ""; return "";
} }
public void updateGoodbye(JSONObject parameters){ public void updateGoodbye(JSONObject parameters){
int botId = parameters.getInteger("botId"); int botId = parameters.getInteger("botId");
String goodbyeText = parameters.getString("sayGoodBye"); String goodbyeText = parameters.getString("sayGoodBye");
intervalStatus = updateKnowledgeUnit(botId, new HashMap<String, String>(){{put("options", OPTIONS);put("idlelimit",IDLE_LIMIT);put("sayGoodbye", goodbyeText);}}, null, null); intervalStatus = updateKnowledgeUnit(botId, new HashMap<String, String>(){{put("options", OPTIONS);put("idlelimit",IDLE_LIMIT);put("sayGoodbye", goodbyeText);}}, null, null);
} }
/** /**
* 修改conditiond的显示顺序 * 修改conditiond的显示顺序
* @param parameters * @param parameters
*/ */
public void updateConditionDisplayOrder(JSONObject parameters){ public void updateConditionDisplayOrder(JSONObject parameters){
int botId = parameters.getInteger("botId"); int botId = parameters.getInteger("botId");
int conditioId = parameters.getInteger("conditionId"); int conditioId = parameters.getInteger("conditionId");
int order = parameters.getInteger("order"); int order = parameters.getInteger("order");
Boolean flag = true; Boolean flag = true;
Condition condition = helper.queryConditionByConditionId(botId, conditioId); Condition condition = helper.queryConditionByConditionId(botId, conditioId);
condition.setDisplayOrder(order); condition.setDisplayOrder(order);
if(helper.updateConditionById(condition)){ if(helper.updateConditionById(condition)){
intervalStatus = new IntervalStatus(1, ""); intervalStatus = new IntervalStatus(1, "");
}else{ }else{
intervalStatus = new IntervalStatus(0, CONDITION_UPDATE_ERROR); intervalStatus = new IntervalStatus(0, CONDITION_UPDATE_ERROR);
} }
} }
public void updateBotInfo(JSONObject parameters){ public void updateBotInfo(JSONObject parameters){
int botId = parameters.getInteger("botId"); int botId = parameters.getInteger("botId");
Boolean updateFlag = true; Boolean updateFlag = true;
String option = parameters.getString("option"); String option = parameters.getString("option");
String value = parameters.getString("value"); String value = parameters.getString("value");
BotInfo botInfo = helper.queryBotInfo(botId); BotInfo botInfo = helper.queryBotInfo(botId);
if(botInfo != null) { if(botInfo != null) {
switch (option) { switch (option) {
case "welcomeText": case "welcomeText":
botInfo.setWelcomeText(value); botInfo.setWelcomeText(value);
break; break;
case "postURL": case "postURL":
botInfo.setPostURL(value); botInfo.setPostURL(value);
break; break;
case "bothValue": case "bothValue":
botInfo.setBothValue(value); botInfo.setBothValue(value);
break; break;
case "queryTextTransfer": case "queryTextTransfer":
botInfo.setQueryTextTransfer(value); botInfo.setQueryTextTransfer(value);
break; break;
} }
updateFlag = helper.updateBotInfo(botInfo); updateFlag = helper.updateBotInfo(botInfo);
if(updateFlag){ if(updateFlag){
intervalStatus = updateKnowledgeUnit(botId, new HashMap<String, String>(){{put("options", OPTIONS);put("idlelimit",IDLE_LIMIT);}}, null, null); intervalStatus = updateKnowledgeUnit(botId, new HashMap<String, String>(){{put("options", OPTIONS);put("idlelimit",IDLE_LIMIT);}}, null, null);
intervalStatus = new IntervalStatus(1, ""); intervalStatus = new IntervalStatus(1, "");
}else{ }else{
intervalStatus = new IntervalStatus(0, UPDATE_ERROR); intervalStatus = new IntervalStatus(0, UPDATE_ERROR);
} }
}else{ }else{
intervalStatus = new IntervalStatus(0, BOT_INFO_NOT_EXIST); intervalStatus = new IntervalStatus(0, BOT_INFO_NOT_EXIST);
} }
} }
} }
package com.qiwu.chatbotbackend.entity; package com.qiwu.chatbotbackend.entity;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
public class ConfigTermText implements Cloneable{ public class ConfigTermText implements Cloneable{
public static ThreadLocal<Integer> iterNum=new ThreadLocal<Integer>() { public static ThreadLocal<Integer> iterNum=new ThreadLocal<Integer>() {
protected Integer initialValue() { protected Integer initialValue() {
return 0; return 0;
} }
}; };
private int id = 0; private int id = 0;
private String curPremise = ""; private String curPremise = "";
private String hisPremise = ""; private String hisPremise = "";
private String feature = ""; private String feature = "";
private String reply = ""; private String reply = "";
private String nextStep = ""; private String nextStep = "";
private String updateKnowledge = ""; private String updateKnowledge = "";
private String nextStepStatus = "return"; private String nextStepStatus = "return";
private String configName = ""; private String configName = "";
private String auxiliaryPriority = "1"; private String auxiliaryPriority = "1";
private String status = "waiting"; private String status = "waiting";
static HashMap<String, Integer> StatusMap = new HashMap<String, Integer>(){ static HashMap<String, Integer> StatusMap = new HashMap<String, Integer>(){
{ {
put("waiting", 0); put("waiting", 0);
put("sleeping", 1); put("sleeping", 1);
} }
}; };
public String getFeature() { public String getFeature() {
return feature; return feature;
} }
public void setFeature(String feature) { public void setFeature(String feature) {
this.feature = feature; this.feature = feature;
} }
public String getCurPremise() { public String getCurPremise() {
return curPremise; return curPremise;
} }
public String getNextStep() { public String getNextStep() {
return nextStep; return nextStep;
} }
public void setNextStep(String nextStep) { public void setNextStep(String nextStep) {
this.nextStep = nextStep; this.nextStep = nextStep;
} }
public String getConfigName() { public String getConfigName() {
return configName; return configName;
} }
public void setConfigName(String configName, Boolean append) { public void setConfigName(String configName, Boolean append) {
if(append) { if(append) {
iterNum.set(iterNum.get() + 1); iterNum.set(iterNum.get() + 1);
this.configName = configName + "_" + iterNum.get(); this.configName = configName + "_" + iterNum.get();
}else{ }else{
this.configName = configName; this.configName = configName;
} }
} }
public int getId() { public int getId() {
return id; return id;
} }
public void setId(int id) { public void setId(int id) {
this.id = id; this.id = id;
} }
public void setCurPremise(String curPremise) { public void setCurPremise(String curPremise) {
this.curPremise = curPremise; this.curPremise = curPremise;
} }
public String getHisPremise() { public String getHisPremise() {
return hisPremise; return hisPremise;
} }
public void setHisPremise(String hisPremise) { public void setHisPremise(String hisPremise) {
this.hisPremise = hisPremise; this.hisPremise = hisPremise;
} }
public String getReply() { public String getReply() {
return reply; return reply;
} }
public void setReply(String reply) { public void setReply(String reply) {
this.reply = reply; this.reply = reply;
} }
public String getAuxiliaryPriority() { public String getAuxiliaryPriority() {
return auxiliaryPriority; return auxiliaryPriority;
} }
public String getStatus() { public String getStatus() {
return status; return status;
} }
public String getNextStepStatus() { public String getNextStepStatus() {
return nextStepStatus; return nextStepStatus;
} }
public String getUpdateKnowledge() { public String getUpdateKnowledge() {
return updateKnowledge; return updateKnowledge;
} }
public void setUpdateKnowledge(String updateKnowledge) { public void setUpdateKnowledge(String updateKnowledge) {
this.updateKnowledge = updateKnowledge; this.updateKnowledge = updateKnowledge;
} }
static Map<String, String> statusMap = new HashMap<String, String>() { static Map<String, String> statusMap = new HashMap<String, String>() {
{ {
put("return", "return"); put("return", "return");
put("return-1", "back"); put("return-1", "back");
put("return-0", "stay"); put("return-0", "stay");
put("activate", "activate"); put("activate", "activate");
put("activate:after", "activate:after"); put("activate:after", "activate:after");
} }
}; };
public void setStatus(String status) { public void setStatus(String status) {
this.status = status; this.status = status;
} }
public void setAuxiliaryPriority(String auxiliaryPriority) { public void setAuxiliaryPriority(String auxiliaryPriority) {
this.auxiliaryPriority = auxiliaryPriority; this.auxiliaryPriority = auxiliaryPriority;
} }
public void setNextStepStatus(String nextStepStatus) { public void setNextStepStatus(String nextStepStatus) {
this.nextStepStatus = nextStepStatus; this.nextStepStatus = nextStepStatus;
} }
public ConfigTermText(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge) { public ConfigTermText(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge) {
this.curPremise = curPremise; this.curPremise = curPremise;
this.hisPremise = hisPremise; this.hisPremise = hisPremise;
this.feature = feature; this.feature = feature;
if (!updateKnowledge.equals("")) if (!updateKnowledge.equals(""))
this.updateKnowledge += "updateKnowledge-<-" + updateKnowledge; this.updateKnowledge += "updateKnowledge-<-" + updateKnowledge;
this.reply = reply; this.reply = reply;
this.nextStep = nextStep; this.nextStep = nextStep;
} }
public ConfigTermText(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge, Map<String, String> autoJumpUpdateKnowledge) { public ConfigTermText(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge, Map<String, String> autoJumpUpdateKnowledge) {
this.curPremise = curPremise; this.curPremise = curPremise;
this.hisPremise = hisPremise; this.hisPremise = hisPremise;
this.feature = feature; this.feature = feature;
this.updateKnowledge = appendKnowledgeStr(autoJumpUpdateKnowledge, updateKnowledge); this.updateKnowledge = appendKnowledgeStr(autoJumpUpdateKnowledge, updateKnowledge);
//if (!updateKnowledge.equals("")) //if (!updateKnowledge.equals(""))
// this.updateKnowledge += "updateKnowledge-<-" + updateKnowledge; // this.updateKnowledge += "updateKnowledge-<-" + updateKnowledge;
this.reply = reply; this.reply = reply;
this.nextStep = nextStep; this.nextStep = nextStep;
} }
public ConfigTermText(List<Premise> curPremise, List<Premise> hisPremise, Map<String, String> updateKnowledge, String extraCP, String extraHP, String extraUK, String feature, String reply, String nextStep, String auxiliaryPriority) { public ConfigTermText(List<Premise> curPremise, List<Premise> hisPremise, Map<String, String> updateKnowledge, String extraCP, String extraHP, String extraUK, String feature, String reply, String nextStep, String auxiliaryPriority) {
this.curPremise = appendPremiseStr(curPremise, extraCP); this.curPremise = appendPremiseStr(curPremise, extraCP);
this.hisPremise = appendPremiseStr(hisPremise, extraHP); this.hisPremise = appendPremiseStr(hisPremise, extraHP);
this.updateKnowledge = appendKnowledgeStr(updateKnowledge, extraUK); this.updateKnowledge = appendKnowledgeStr(updateKnowledge, extraUK);
this.feature = feature; this.feature = feature;
this.reply = reply; this.reply = reply;
this.nextStep = nextStep; this.nextStep = nextStep;
this.auxiliaryPriority = auxiliaryPriority; this.auxiliaryPriority = auxiliaryPriority;
} }
public String appendPremiseStr(List<Premise> premises, String extraPremise) { public String appendPremiseStr(List<Premise> premises, String extraPremise) {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
String premiseStr = "", conditionName; String premiseStr = "", conditionName;
Map<String ,Integer> nameCount = new HashMap<String , Integer>(); Map<String ,Integer> nameCount = new HashMap<String , Integer>();
for (Premise premise : premises){ for (Premise premise : premises){
conditionName = premise.getConditionName(); conditionName = premise.getConditionName();
if(conditionName.startsWith("npc_") || if(conditionName.startsWith("npc_") ||
conditionName.startsWith("goods_") || conditionName.startsWith("goods_") ||
conditionName.startsWith("globalVariable_") || conditionName.startsWith("globalVariable_") ||
conditionName.startsWith("map_")) conditionName.startsWith("map_"))
{} {}
else { else {
nameCount.putIfAbsent(conditionName, 0); nameCount.putIfAbsent(conditionName, 0);
//nameCount加一 //nameCount加一
nameCount.put(conditionName, nameCount.get(conditionName) + 1); nameCount.put(conditionName, nameCount.get(conditionName) + 1);
//在conditionName后添加count //在conditionName后添加count
if(nameCount.get(conditionName) > 1) { if(nameCount.get(conditionName) > 1) {
premise.setConditionName(conditionName + nameCount.get(conditionName)); premise.setConditionName(conditionName + nameCount.get(conditionName));
} }
} }
sb.append(","); sb.append(",");
sb.append(premise.getConditionName()); sb.append(premise.getConditionName());
sb.append("::"); sb.append("::");
sb.append(premise.getCmpType()); sb.append(premise.getCmpType());
sb.append("-"); sb.append("-");
sb.append(premise.getOperator()); sb.append(premise.getOperator());
sb.append("="); sb.append("=");
sb.append(premise.getKeyword()); sb.append(premise.getKeyword());
} }
if (sb.length() > 0) if (sb.length() > 0)
sb.deleteCharAt(0); //删除第一个逗号 sb.deleteCharAt(0); //删除第一个逗号
if (!extraPremise.equals("")) { if (!extraPremise.equals("")) {
if (sb.length() == 0) if (sb.length() == 0)
sb.append(extraPremise); sb.append(extraPremise);
else else
sb.append("," + extraPremise); sb.append("," + extraPremise);
} else if (sb.length() == 0) { } else if (sb.length() == 0) {
sb.append(" "); sb.append(" ");
} }
premiseStr = sb.toString(); premiseStr = sb.toString();
return premiseStr; return premiseStr;
} }
public String appendKnowledgeStr(Map<String, String> knowledge, String extraKL) { public String appendKnowledgeStr(Map<String, String> knowledge, String extraKL) {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
String varName = "", varValue = "", knowledgeStr; String varName = "", varValue = "", knowledgeStr;
Iterator<String> iit = knowledge.keySet().iterator(); Iterator<String> iit = knowledge.keySet().iterator();
Boolean delayUpdateFollowerLocation = false; //updateFollowerLocation:更新跟随玩家的NPC的位置,delayUpdateFollowerLocation将更新跟随玩家的角色放在更新答案的最后 Boolean delayUpdateFollowerLocation = false; //updateFollowerLocation:更新跟随玩家的NPC的位置,delayUpdateFollowerLocation将更新跟随玩家的角色放在更新答案的最后
String delayUpdateFollowerLocationValue = "", delayUpdateFollowerLocationKey = ""; String delayUpdateFollowerLocationValue = "", delayUpdateFollowerLocationKey = "";
while (iit.hasNext()) { while (iit.hasNext()) {
varName = iit.next(); varName = iit.next();
varValue = knowledge.get(varName); varValue = knowledge.get(varName);
if(varValue.startsWith("updateFollowerLocation")){ if(varValue.startsWith("updateFollowerLocation")){
delayUpdateFollowerLocation = true; delayUpdateFollowerLocation = true;
delayUpdateFollowerLocationKey = varName; delayUpdateFollowerLocationKey = varName;
delayUpdateFollowerLocationValue = varValue; delayUpdateFollowerLocationValue = varValue;
continue; continue;
} }
sb.append("-<-").append(varName).append(":").append(varValue); sb.append("-<-").append(varName).append(":").append(varValue);
} }
if (!extraKL.equals("")) { if (!extraKL.equals("")) {
sb.append("-<-" + extraKL); sb.append("-<-" + extraKL);
} }
if(delayUpdateFollowerLocation){ if(delayUpdateFollowerLocation){
sb.append("-<-").append(delayUpdateFollowerLocationKey).append(":").append(delayUpdateFollowerLocationValue); sb.append("-<-").append(delayUpdateFollowerLocationKey).append(":").append(delayUpdateFollowerLocationValue);
} }
if (sb.length() > 0) if (sb.length() > 0)
knowledgeStr = "updateKnowledge" + sb.toString(); knowledgeStr = "updateKnowledge" + sb.toString();
else else
knowledgeStr = ""; knowledgeStr = "";
return knowledgeStr; return knowledgeStr;
} }
public void appendJPremise(JSONArray premiseList, String premise, Map<String, String> conditionDescription) { public void appendJPremise(JSONArray premiseList, String premise, Map<String, String> conditionDescription) {
//System.out.println(premise); //System.out.println(premise);
String pair1[] = premise.split("=", 2); String pair1[] = premise.split("=", 2);
String key = pair1[0]; String key = pair1[0];
String keywords = pair1[1]; String keywords = pair1[1];
String pair2[] = key.split("::"); String pair2[] = key.split("::");
String conditionName = pair2[0]; String conditionName = pair2[0];
String pair3[] = pair2[1].split("-"); String pair3[] = pair2[1].split("-");
String cmpType = pair3[0]; String cmpType = pair3[0];
String operator = ""; String operator = "";
if (pair3.length > 1) if (pair3.length > 1)
operator = pair3[1]; operator = pair3[1];
String question = ""; String question = "";
if (conditionDescription.get(conditionName) != null) if (conditionDescription.get(conditionName) != null)
question = conditionDescription.get(conditionName); question = conditionDescription.get(conditionName);
JSONObject premiseJ = new JSONObject(); JSONObject premiseJ = new JSONObject();
premiseJ.put("keywords", keywords); premiseJ.put("keywords", keywords);
premiseJ.put("actionName", conditionName); premiseJ.put("actionName", conditionName);
premiseJ.put("cmpType", cmpType); premiseJ.put("cmpType", cmpType);
premiseJ.put("question", question); premiseJ.put("question", question);
premiseJ.put("operator", operator); premiseJ.put("operator", operator);
premiseList.add(premiseJ); premiseList.add(premiseJ);
} }
public void appendJKnowledge(JSONArray knowledgeList, String knowledge, Map<String, String> conditionDescription) { public void appendJKnowledge(JSONArray knowledgeList, String knowledge, Map<String, String> conditionDescription) {
String pair[] = knowledge.split(":", 2); String pair[] = knowledge.split(":", 2);
if (knowledge.equals("") || pair.length < 2) if (knowledge.equals("") || pair.length < 2)
return; return;
String question = ""; String question = "";
if (conditionDescription.get(pair[0]) != null) if (conditionDescription.get(pair[0]) != null)
question = conditionDescription.get(pair[0]); question = conditionDescription.get(pair[0]);
JSONObject knowledgeJ = new JSONObject(); JSONObject knowledgeJ = new JSONObject();
knowledgeJ.put("variableName", pair[0]); knowledgeJ.put("variableName", pair[0]);
knowledgeJ.put("keyword", pair[1]); knowledgeJ.put("keyword", pair[1]);
knowledgeList.add(knowledgeJ); knowledgeList.add(knowledgeJ);
} }
public void appendJNextStep(JSONArray nextStepList, String next, Map<String, String> conditionDescription) { public void appendJNextStep(JSONArray nextStepList, String next, Map<String, String> conditionDescription) {
String pair[] = next.split("-"); String pair[] = next.split("-");
JSONObject nextStepJ = new JSONObject(); JSONObject nextStepJ = new JSONObject();
JSONArray exceptJ = new JSONArray(); JSONArray exceptJ = new JSONArray();
for (int i = 1; i < pair.length; i++) for (int i = 1; i < pair.length; i++)
exceptJ.add(pair[i]); exceptJ.add(pair[i]);
String question = ""; String question = "";
if (conditionDescription.get(pair[0]) != null) if (conditionDescription.get(pair[0]) != null)
question = conditionDescription.get(pair[0]); question = conditionDescription.get(pair[0]);
nextStepJ.put("nextStep", pair[0]); nextStepJ.put("nextStep", pair[0]);
nextStepJ.put("except", exceptJ); nextStepJ.put("except", exceptJ);
nextStepJ.put("nextStepText", question); nextStepJ.put("nextStepText", question);
nextStepList.add(nextStepJ); nextStepList.add(nextStepJ);
} }
public JSONObject toJson(Map<String, String> conditionDescription) { public JSONObject toJson(Map<String, String> conditionDescription) {
JSONObject data = new JSONObject(); JSONObject data = new JSONObject();
JSONArray curPremiseList = new JSONArray(); JSONArray curPremiseList = new JSONArray();
JSONArray hisPremiseList = new JSONArray(); JSONArray hisPremiseList = new JSONArray();
//添加当前对话内容 //添加当前对话内容
for (String premise : curPremise.split(",")) { for (String premise : curPremise.split(",")) {
if (!premise.equals("") && !premise.equals(" ")) if (!premise.equals("") && !premise.equals(" "))
appendJPremise(curPremiseList, premise, conditionDescription); appendJPremise(curPremiseList, premise, conditionDescription);
} }
data.put("currentPremiseList", curPremiseList); data.put("currentPremiseList", curPremiseList);
//添加已知信息的内容 //添加已知信息的内容
for (String premise : hisPremise.split(",")) { for (String premise : hisPremise.split(",")) {
if (!premise.equals("") && !premise.equals(" ")) if (!premise.equals("") && !premise.equals(" "))
appendJPremise(hisPremiseList, premise, conditionDescription); appendJPremise(hisPremiseList, premise, conditionDescription);
} }
data.put("historyPremiseList", hisPremiseList); data.put("historyPremiseList", hisPremiseList);
//添加下一步状态 //添加下一步状态
//添加configName //添加configName
data.put("configName", configName); data.put("configName", configName);
//添加config状态 //添加config状态
data.put("configStatus", statusMap.get(status)); data.put("configStatus", statusMap.get(status));
boolean doPost = false; boolean doPost = false;
String postURL = "", postType = "all", pair[]; String postURL = "", postType = "all", pair[];
for (String feat : feature.split(",")) { for (String feat : feature.split(",")) {
if (feat.startsWith("post")) { if (feat.startsWith("post")) {
doPost = true; doPost = true;
pair = feat.substring(0, feat.length() - 1).split("\\(", 2); pair = feat.substring(0, feat.length() - 1).split("\\(", 2);
postURL = pair[1]; postURL = pair[1];
postType = pair[0].split("::")[1]; postType = pair[0].split("::")[1];
}else if(feat.equals("return-0")){ }else if(feat.equals("return-0")){
nextStepStatus = "return-0"; nextStepStatus = "return-0";
}else if(feat.equals("activate")){ }else if(feat.equals("activate")){
nextStepStatus = "activate"; nextStepStatus = "activate";
}else if(feat.equals("activate:after")){ }else if(feat.equals("activate:after")){
nextStepStatus = "activate:after"; nextStepStatus = "activate:after";
} }
} }
data.put("nextStepStatus", statusMap.get(nextStepStatus)); data.put("nextStepStatus", statusMap.get(nextStepStatus));
//添加post参数 //添加post参数
data.put("doPost", doPost); data.put("doPost", doPost);
data.put("postURL", postURL); data.put("postURL", postURL);
data.put("postType", postType); data.put("postType", postType);
//添加回答 //添加回答
data.put("reply", reply); data.put("reply", reply);
//添加config类别id //添加config类别id
data.put("categoryId", 0); data.put("categoryId", 0);
//添加辅助优先级 //添加辅助优先级
data.put("auxiliaryPriority", auxiliaryPriority); data.put("auxiliaryPriority", auxiliaryPriority);
//添加更新答案处的信息 //添加更新答案处的信息
JSONArray knowledgeList = new JSONArray(); JSONArray knowledgeList = new JSONArray();
if (!updateKnowledge.equals("")) { if (!updateKnowledge.equals("")) {
for (String knowledge : updateKnowledge.split("-<-")) { for (String knowledge : updateKnowledge.split("-<-")) {
appendJKnowledge(knowledgeList, knowledge, conditionDescription); appendJKnowledge(knowledgeList, knowledge, conditionDescription);
} }
} }
data.put("updateKnowledge", knowledgeList); data.put("updateKnowledge", knowledgeList);
//添加下一步 //添加下一步
JSONArray nextStepList = new JSONArray(); JSONArray nextStepList = new JSONArray();
for (String next : nextStep.split(",")) { for (String next : nextStep.split(",")) {
appendJNextStep(nextStepList, next, conditionDescription); appendJNextStep(nextStepList, next, conditionDescription);
} }
data.put("nextStepList", nextStepList); data.put("nextStepList", nextStepList);
return data; return data;
} }
public String toString() { public String toString() {
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
sb.append(curPremise).append("|"); sb.append(curPremise).append("|");
sb.append(hisPremise); sb.append(hisPremise);
sb.append("|").append(feature).append(","); sb.append("|").append(feature).append(",");
sb.append(updateKnowledge).append(","); sb.append(updateKnowledge).append(",");
sb.append(nextStepStatus).append( "|"); //sb.append(nextStepStatus).append( "|");
sb.append("auxiliaryPriority="); sb.append( "|");
sb.append(auxiliaryPriority).append("|").append("configName="); sb.append("auxiliaryPriority=");
sb.append(configName); sb.append(auxiliaryPriority).append("|").append("configName=");
sb.append("|=>|").append(reply); sb.append(configName);
sb.append("|").append("nextStep="); sb.append("|=>|").append(reply);
sb.append(nextStep).append("|"); sb.append("|").append("nextStep=");
sb.append("status=").append(status); sb.append(nextStep).append("|");
sb.append("|").append("configId="); sb.append("status=").append(status);
sb.append("|").append("configId=");
return sb.toString();
} return sb.toString();
}
public Object clone() {
Object o=null; public Object clone() {
try{ Object o=null;
o= super.clone(); try{
}catch(CloneNotSupportedException e){ o= super.clone();
System.out.println(e.toString()); }catch(CloneNotSupportedException e){
} System.out.println(e.toString());
return o; }
} return o;
}
public static void activateCopy(ConfigTermText configTermText, List<ConfigTermText> configTermTextList, String name){
public static void activateCopy(ConfigTermText configTermText, List<ConfigTermText> configTermTextList, String name){
configTermText.setReply(configTermText.getReply() + "{临时变量reply-2}");
configTermText.setReply(configTermText.getReply() + "{临时变量reply-2}");
ConfigTermText configTermText2 = (ConfigTermText) configTermText.clone();
ConfigTermText configTermText2 = (ConfigTermText) configTermText.clone();
if(configTermText2.getUpdateKnowledge().equals(""))
configTermText2.setUpdateKnowledge("process-nextStep:var={临时变量condition-2}"); if(configTermText2.getUpdateKnowledge().equals(""))
else configTermText2.setUpdateKnowledge("process-nextStep:var={临时变量condition-2}");
configTermText2.setUpdateKnowledge(configTermText2.getUpdateKnowledge() + "-<-process-nextStep:var={临时变量condition-2}"); else
configTermText2.setConfigName(name, true); configTermText2.setUpdateKnowledge(configTermText2.getUpdateKnowledge() + "-<-process-nextStep:var={临时变量condition-2}");
configTermText2.setConfigName(name, true);
configTermTextList.add(configTermText2);
configTermTextList.add(configTermText2);
}
}
public ConfigTermText simpleCopy(ConfigTermText configTermText){
public ConfigTermText simpleCopy(ConfigTermText configTermText){
ConfigTermText configTermText2 = (ConfigTermText) configTermText.clone();
ConfigTermText configTermText2 = (ConfigTermText) configTermText.clone();
return configTermText2;
} return configTermText2;
} }
}
package com.qiwu.chatbotbackend.gameDesign; package com.qiwu.chatbotbackend.gameDesign;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.ConfigTermText; import com.qiwu.chatbotbackend.entity.ConfigTermText;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import java.util.*; import java.util.*;
public class ElementConstructor { public class ElementConstructor {
int botId = 0; int botId = 0;
int operationStatus = 1; int operationStatus = 1;
Map<String, StringBuffer> keywordMap = null; Map<String, StringBuffer> keywordMap = null;
SqlHelper helper = null; SqlHelper helper = null;
HashSet<String> exceptRelation = null; HashSet<String> exceptRelation = null;
ConfigTermText configTermText = null; ConfigTermText configTermText = null;
String botAccount; String botAccount;
String message = ""; String message = "";
List<JSONObject> configDataList = new ArrayList<JSONObject>(); List<JSONObject> configDataList = new ArrayList<JSONObject>();
List<ConfigTermText> configTermTextList = new ArrayList<ConfigTermText>(); List<ConfigTermText> configTermTextList = new ArrayList<ConfigTermText>();
StringBuffer configText = new StringBuffer(); StringBuffer configText = new StringBuffer();
Map<String, String> varInitialMap = new HashMap<String, String>(); Map<String, String> varInitialMap = new HashMap<String, String>();
Map<String, String> conditionDescription = new HashMap<String, String>(); Map<String, String> conditionDescription = new HashMap<String, String>();
StringBuffer POS = new StringBuffer(); StringBuffer POS = new StringBuffer();
public String getMessage() { return message; } public String getMessage() { return message; }
public int getOperationStatus() { return operationStatus; } public int getOperationStatus() { return operationStatus; }
public Map<String, String> getVarInitialMap() { public Map<String, String> getVarInitialMap() {
return varInitialMap; return varInitialMap;
} }
public void construct(JSONObject gameElements, UserInfo userinfo) { } public void construct(JSONObject gameElements, UserInfo userinfo) { }
public List<ConfigTermText> getConfigTermTextList() { public List<ConfigTermText> getConfigTermTextList() {
return configTermTextList; return configTermTextList;
} }
public Map<String, String> getConditionDescription() { public Map<String, String> getConditionDescription() {
return conditionDescription; return conditionDescription;
} }
public List<JSONObject> getConfigDataList() { public List<JSONObject> getConfigDataList() {
return configDataList; return configDataList;
} }
public void ElementConstructor(String userName) { public void ElementConstructor(String userName) {
this.botAccount = botAccount; this.botAccount = botAccount;
} }
public String getConfigText() { public String getConfigText() {
return configText.toString(); return configText.toString();
} }
//生成完整的后台配置文件 //生成完整的后台配置文件
public void generateConfigText(List<Integer> idList) { public void generateConfigText(List<Integer> idList) {
int id, length = idList.size(); int id, length = idList.size();
String varValue; String varValue;
ConfigTermText configTermText = null; ConfigTermText configTermText = null;
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
configTermText = configTermTextList.get(i); configTermText = configTermTextList.get(i);
id = idList.get(i); id = idList.get(i);
configText.append(configTermText.toString() + id + "\n"); configText.append(configTermText.toString() + id + "\n");
} }
//变量 //变量
for (String varName : varInitialMap.keySet()) { for (String varName : varInitialMap.keySet()) {
varValue = varInitialMap.get(varName); varValue = varInitialMap.get(varName);
configText.append("-varInitial-|" + varName + "|" + varValue.replace("\n", "") + "\n"); configText.append("-varInitial-|" + varName + "|" + varValue.replace("\n", "") + "\n");
} }
} }
/** /**
* 从生成的配置文件的获取哪些condition需要哪些关键词,然后用于生成condition * 从生成的配置文件的获取哪些condition需要哪些关键词,然后用于生成condition
* @param config * @param config
* @param relationKeywords * @param relationKeywords
* @param exceptRelation * @param exceptRelation
* @param botName * @param botName
*/ */
public void parseKeyword(JSONObject config, Map<String, HashSet<String>> relationKeywords, HashSet<String> exceptRelation, String botName){ public void parseKeyword(JSONObject config, Map<String, HashSet<String>> relationKeywords, HashSet<String> exceptRelation, String botName){
String conditionName, pair[]; String conditionName, pair[];
for(Map premise:JSONArray.parseArray(config.getJSONArray("currentPremiseList").toJSONString(), Map.class)){ for(Map premise:JSONArray.parseArray(config.getJSONArray("currentPremiseList").toJSONString(), Map.class)){
conditionName = (String) premise.get("actionName"); conditionName = (String) premise.get("actionName");
if(!exceptRelation.contains(conditionName)) { if(!exceptRelation.contains(conditionName)) {
//初始化 //初始化
if(!relationKeywords.containsKey(conditionName + "_head")) { if(!relationKeywords.containsKey(conditionName + "_head")) {
relationKeywords.put(conditionName + "_head", new HashSet<String>()); relationKeywords.put(conditionName + "_head", new HashSet<String>());
relationKeywords.put(conditionName + "_tail", new HashSet<String>()); relationKeywords.put(conditionName + "_tail", new HashSet<String>());
} }
//visitorname和bot的替换 //visitorname和bot的替换
premise.put("keywords", ((String)premise.get("keywords")).replace("qiwu", "#visitorname").replace(botName, "#botname")); premise.put("keywords", ((String)premise.get("keywords")).replace("qiwu", "#visitorname").replace(botName, "#botname"));
for (String keyword : ((String) premise.get("keywords")).split("\\+")) { for (String keyword : ((String) premise.get("keywords")).split("\\+")) {
if(keyword.equals("")){ if(keyword.equals("")){
continue; continue;
} else if(keyword.contains(":")){ } else if(keyword.contains(":")){
//有些配置条目要求三元组两边的值都匹配,需要把两边的值分别加入题头和值域 //有些配置条目要求三元组两边的值都匹配,需要把两边的值分别加入题头和值域
pair = keyword.split(":",2); pair = keyword.split(":",2);
if(pair[1].equals("")) if(pair[1].equals(""))
continue; continue;
relationKeywords.get(conditionName + "_head").add(pair[0]); relationKeywords.get(conditionName + "_head").add(pair[0]);
relationKeywords.get(conditionName + "_tail").add(pair[1]); relationKeywords.get(conditionName + "_tail").add(pair[1]);
} else { } else {
relationKeywords.get(conditionName + "_tail").add(keyword); relationKeywords.get(conditionName + "_tail").add(keyword);
} }
} }
} }
} }
for(Map premise:JSONArray.parseArray(config.getJSONArray("historyPremiseList").toJSONString(), Map.class)){ for(Map premise:JSONArray.parseArray(config.getJSONArray("historyPremiseList").toJSONString(), Map.class)){
conditionName = (String) premise.get("actionName"); conditionName = (String) premise.get("actionName");
if(conditionName.startsWith("npc_") || conditionName.startsWith("goods_")) if(conditionName.startsWith("npc_") || conditionName.startsWith("goods_"))
continue; continue;
if(!exceptRelation.contains(conditionName)) { if(!exceptRelation.contains(conditionName)) {
if(!relationKeywords.containsKey(conditionName + "_head")) { if(!relationKeywords.containsKey(conditionName + "_head")) {
relationKeywords.put(conditionName + "_head", new HashSet<String>()); relationKeywords.put(conditionName + "_head", new HashSet<String>());
relationKeywords.put(conditionName + "_tail", new HashSet<String>()); relationKeywords.put(conditionName + "_tail", new HashSet<String>());
} }
premise.put("keywords", ((String)premise.get("keywords")).replace("qiwu", "#visitorname").replace(botName, "#botname")); premise.put("keywords", ((String)premise.get("keywords")).replace("qiwu", "#visitorname").replace(botName, "#botname"));
for (String keyword : ((String) premise.get("keywords")).split("\\+")) { for (String keyword : ((String) premise.get("keywords")).split("\\+")) {
if(keyword.equals("")){ if(keyword.equals("")){
continue; continue;
} else if(keyword.contains(":")){ } else if(keyword.contains(":")){
pair = keyword.split(":",2); pair = keyword.split(":",2);
if(pair[1].equals("")) if(pair[1].equals(""))
continue; continue;
relationKeywords.get(conditionName + "_head").add(pair[0]); relationKeywords.get(conditionName + "_head").add(pair[0]);
relationKeywords.get(conditionName + "_tail").add(pair[1]); relationKeywords.get(conditionName + "_tail").add(pair[1]);
} else { } else {
relationKeywords.get(conditionName + "_tail").add(keyword); relationKeywords.get(conditionName + "_tail").add(keyword);
} }
} }
} }
} }
} }
/** /**
* 根据插入的数据做后处理 * 根据插入的数据做后处理
* @param idList * @param idList
*/ */
public void postProcessing(List<Integer> idList, int categoryId){} public void postProcessing(List<Integer> idList, int categoryId){}
/** /**
* 构造参数配置文件的json版 * 构造参数配置文件的json版
*/ */
public void buildJconfig() { public void buildJconfig() {
} }
public void appendPOS(StringBuffer POS, String name, String tag){ public void appendPOS(StringBuffer POS, String name, String tag){
if(!name.equals("")) { if(!name.equals("")) {
POS.append("="); POS.append("=");
POS.append(name); POS.append(name);
POS.append("|"); POS.append("|");
POS.append(tag); POS.append(tag);
POS.append("\n"); POS.append("\n");
} }
} }
public void queryTypeConfigTermGenerate(Map<String, StringBuffer> keywordMap, String intent, String module, String queryMethod){ public void queryTypeConfigTermGenerate(Map<String, StringBuffer> keywordMap, String intent, String module, String queryMethod){
String conditionKeywords = ""; String conditionKeywords = "";
String conditionNameList[] = keywordMap.get(intent).toString().split(","); String conditionNameList[] = keywordMap.get(intent).toString().split(",");
for (String conditionName : conditionNameList) { for (String conditionName : conditionNameList) {
conditionKeywords = keywordMap.get(intent + "_" + conditionName).toString(); conditionKeywords = keywordMap.get(intent + "_" + conditionName).toString();
configTermText = new ConfigTermText( configTermText = new ConfigTermText(
conditionName + "::match-Include=" + conditionKeywords, " ", conditionName + "::match-Include=" + conditionKeywords, " ",
"match,return-0", "match",
"", "",
" ", " ",
module + "_query:" + queryMethod + ":" + conditionName module + "_query:" + queryMethod + ":" + conditionName
); );
//ConfigTermText.activateCopy(configTermText, configTermTextList, module); //ConfigTermText.activateCopy(configTermText, configTermTextList, module);
//查询文本可能是被无条件剧情激活的,这时候的回答应该包含无条件剧情的剧情文本,这个文本存放在临时变量reply 里面 //查询文本可能是被无条件剧情激活的,这时候的回答应该包含无条件剧情的剧情文本,这个文本存放在临时变量reply 里面
configTermText.setReply(configTermText.getReply() + "{临时变量reply-2}"); configTermText.setReply(configTermText.getReply() + "{临时变量reply-2}");
configTermText.setUpdateKnowledge(configTermText.getUpdateKnowledge() + "-<-process-nextStep:var={临时变量condition-2}"); configTermText.setUpdateKnowledge(configTermText.getUpdateKnowledge() + "-<-process-nextStep:var={临时变量condition-2}");
configTermText.setConfigName(module, true); configTermText.setConfigName(module, true);
configTermTextList.add(configTermText); configTermTextList.add(configTermText);
} }
} }
/** /**
* 将某个意图对应的condition的关键词复制一份,然后清空原来关键词 * 将某个意图对应的condition的关键词复制一份,然后清空原来关键词
* @param intent * @param intent
*/ */
public void copyPattern(String intent){ public void copyPattern(String intent){
for(String conditionName:keywordMap.get(intent).toString().split(",")){ for(String conditionName:keywordMap.get(intent).toString().split(",")){
keywordMap.put(intent + "_" + conditionName + "_" + "pattern", new StringBuffer(keywordMap.get(intent + "_" + conditionName))); keywordMap.put(intent + "_" + conditionName + "_" + "pattern", new StringBuffer(keywordMap.get(intent + "_" + conditionName)));
keywordMap.get(intent + "_" + conditionName).setLength(0); keywordMap.get(intent + "_" + conditionName).setLength(0);
} }
} }
//把查询意图condition关键词模板中的变量槽替换成具体的值 //把查询意图condition关键词模板中的变量槽替换成具体的值
public void appendReplacedKeyword(String intent, List<String[]> replaceList){ public void appendReplacedKeyword(String intent, List<String[]> replaceList){
String pattern, replaceText; String pattern, replaceText;
for(String conditionName:keywordMap.get(intent).toString().split(",")){ for(String conditionName:keywordMap.get(intent).toString().split(",")){
pattern = keywordMap.get( intent + "_" + conditionName + "_pattern").toString(); pattern = keywordMap.get( intent + "_" + conditionName + "_pattern").toString();
for(String[] replacePair: replaceList){ for(String[] replacePair: replaceList){
pattern = pattern.replace(replacePair[0], replacePair[1]); pattern = pattern.replace(replacePair[0], replacePair[1]);
} }
keywordMap.get(intent + "_" + conditionName).append(pattern); keywordMap.get(intent + "_" + conditionName).append(pattern);
} }
} }
} }
package com.qiwu.chatbotbackend.gameDesign; package com.qiwu.chatbotbackend.gameDesign;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.ConfigTermText; import com.qiwu.chatbotbackend.entity.ConfigTermText;
import com.qiwu.chatbotbackend.entity.Premise; import com.qiwu.chatbotbackend.entity.Premise;
import com.qiwu.chatbotbackend.entity.UserInfo; import com.qiwu.chatbotbackend.entity.UserInfo;
import java.io.*; import java.io.*;
import java.util.*; import java.util.*;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static com.qiwu.chatbotbackend.Config.Config.*; import static com.qiwu.chatbotbackend.Config.Config.*;
import static com.qiwu.chatbotbackend.actiongenerate.utils.ConfigTermUtils.textReplace; import static com.qiwu.chatbotbackend.actiongenerate.utils.ConfigTermUtils.textReplace;
public class PlotConstructor2 extends ElementConstructor { public class PlotConstructor2 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>>();
private HashMap<String, JSONObject> plotIndex = new HashMap<String, JSONObject>(); private HashMap<String, JSONObject> plotIndex = new HashMap<String, JSONObject>();
HashMap<String, Boolean> visited = new HashMap<String, Boolean>(); HashMap<String, Boolean> visited = new HashMap<String, Boolean>();
public HashMap<String, JSONObject> getPlotIndex() { public HashMap<String, JSONObject> getPlotIndex() {
return plotIndex; return plotIndex;
} }
static Map<String, String> replaceMap = new LinkedHashMap<String, String>(){ static Map<String, String> replaceMap = new LinkedHashMap<String, String>(){
{ {
} }
}; };
public PlotConstructor2(SqlHelper helper, int botId, String botAccount, Map<String, StringBuffer> keywordMap, HashSet<String> exceptRelation, StringBuffer POS) { public PlotConstructor2(SqlHelper helper, int botId, String botAccount, Map<String, StringBuffer> keywordMap, HashSet<String> exceptRelation, StringBuffer POS) {
super(); super();
this.helper = helper; this.helper = helper;
this.botId = botId; this.botId = botId;
this.botAccount = botAccount; this.botAccount = botAccount;
this.exceptRelation = exceptRelation; this.exceptRelation = exceptRelation;
this.keywordMap = keywordMap; this.keywordMap = keywordMap;
this.POS = POS; this.POS = POS;
replaceMap.put("\r\n", ""); replaceMap.put("\r\n", "");
replaceMap.put("\n", ""); replaceMap.put("\n", "");
replaceMap.put("\t", ""); replaceMap.put("\t", "");
replaceMap.put("\\|", ""); replaceMap.put("\\|", "");
replaceMap.put("~", "~"); replaceMap.put("~", "~");
} }
public void construct(JSONObject jsonObject, UserInfo userinfo) { public void construct(JSONObject jsonObject, UserInfo userinfo) {
try { try {
addGameStartPlot(jsonObject, keywordMap); addGameStartPlot(jsonObject, keywordMap);
JSONArray plots = jsonObject.getJSONArray("plots"); JSONArray plots = jsonObject.getJSONArray("plots");
String start = (String) jsonObject.get("start"), startCondition; String start = (String) jsonObject.get("start"), startCondition;
JSONObject returnMessage = null; JSONObject returnMessage = null;
this.plots = plots; this.plots = plots;
constructAdjList(plots); constructAdjList(plots);
if (plotIndex.containsKey(start)) { if (plotIndex.containsKey(start)) {
//String taskLineName = "任务线_" + plotIndex.get(start).get("place") + "进度"; //String taskLineName = "任务线_" + plotIndex.get(start).get("place") + "进度";
String taskLineName = String.format(TASK_LINE, plotIndex.get(start).get("place")); String taskLineName = String.format(TASK_LINE, plotIndex.get(start).get("place"));
conditionDescription.put(taskLineName, taskLineName); conditionDescription.put(taskLineName, taskLineName);
if(jsonObject.get("firstUnknownText") == null) if(jsonObject.get("firstUnknownText") == null)
varInitialMap.put("unknownText", "你说啥?"); varInitialMap.put("unknownText", "你说啥?");
else else
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) plotIndex.get(start).get("id"))); varInitialMap.put("game_step", String.format(GAME_STEP_FORMAT, botAccount, (String) plotIndex.get(start).get("id")));
conditionDescription.put("unknownText", UNKNOWN_TEXT_DESCRIPTION); conditionDescription.put("unknownText", UNKNOWN_TEXT_DESCRIPTION);
conditionDescription.put("game_step", GAME_STEP_DESCRIPTION); conditionDescription.put("game_step", GAME_STEP_DESCRIPTION);
BFSGenerate4(plotIndex.get(start), userinfo, jsonObject); BFSGenerate4(plotIndex.get(start), userinfo, jsonObject);
varInitialMap.put(start, "1"); varInitialMap.put(start, "1");
ListeningConstructor.cc(botAccount, jsonObject, plotIndex, configTermTextList); ListeningConstructor.cc(botAccount, jsonObject, plotIndex, configTermTextList);
} else { } else {
System.out.println(START_PLOT_NOT_EXIST); System.out.println(START_PLOT_NOT_EXIST);
operationStatus = 0; operationStatus = 0;
message = START_PLOT_NOT_EXIST; message = START_PLOT_NOT_EXIST;
return; return;
} }
} catch(Exception e){ } catch(Exception e){
operationStatus = 0; operationStatus = 0;
message = PLOT_GENERATION_ERROR; message = PLOT_GENERATION_ERROR;
e.printStackTrace(); e.printStackTrace();
return; return;
} }
} }
/** /**
* 根据id构造邻接表,将剧情数据变成树状结构 * 根据id构造邻接表,将剧情数据变成树状结构
* @param plots * @param plots
*/ */
public void constructAdjList(JSONArray plots) { public void constructAdjList(JSONArray plots) {
int length = plots.size(), branchSize; int length = plots.size(), branchSize;
String id = "", nextPlotId = "", nextPlotText; String id = "", nextPlotId = "", nextPlotText;
JSONObject plot = null; JSONObject plot = null;
JSONArray branch = null; JSONArray branch = null;
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
plot = plots.getJSONObject(i); plot = plots.getJSONObject(i);
id = (String) plot.get("id"); id = (String) plot.get("id");
plot.put("index", i); plot.put("index", i);
if (adjList.get(id) == null) { if (adjList.get(id) == null) {
adjList.put(id, new ArrayList<>()); adjList.put(id, new ArrayList<>());
} }
//如果npc是离线的,就过滤掉剧情文本中的变量槽 //如果npc是离线的,就过滤掉剧情文本中的变量槽
varSlotFilt(plot, keywordMap); varSlotFilt(plot, keywordMap);
//添加branch中的下一个plot //添加branch中的下一个plot
branch = plot.getJSONArray("branch"); branch = plot.getJSONArray("branch");
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");
//过滤特殊字符 //过滤特殊字符
branch.getJSONObject(j).put("curPremise", premiseTextFilt(branch.getJSONObject(j).getJSONArray("curPremise"))); branch.getJSONObject(j).put("curPremise", premiseTextFilt(branch.getJSONObject(j).getJSONArray("curPremise")));
branch.getJSONObject(j).put("hisPremise", premiseTextFilt(branch.getJSONObject(j).getJSONArray("hisPremise"))); branch.getJSONObject(j).put("hisPremise", premiseTextFilt(branch.getJSONObject(j).getJSONArray("hisPremise")));
//将剧情和相应文本相对应 //将剧情和相应文本相对应
//plotTextIndex.put(nextPlotId, nextPlotText); //plotTextIndex.put(nextPlotId, nextPlotText);
//在邻接表中放入当前剧情的下一步剧情 //在邻接表中放入当前剧情的下一步剧情
adjList.get(id).add(nextPlotId); adjList.get(id).add(nextPlotId);
} }
//剧情文本特殊字符的过滤 //剧情文本特殊字符的过滤
plot.put("plotText", textReplace(plot.getString("plotText"), replaceMap)); plot.put("plotText", textReplace(plot.getString("plotText"), replaceMap));
plotIndex.put(id, plot); plotIndex.put(id, plot);
} }
} }
/** /**
* 将条件文本中的一些特殊字符过滤调 * 将条件文本中的一些特殊字符过滤调
* @param premiseList 条件列表 * @param premiseList 条件列表
* @return * @return
*/ */
JSONArray premiseTextFilt(JSONArray premiseList){ JSONArray premiseTextFilt(JSONArray premiseList){
JSONObject premise = null; JSONObject premise = null;
int size = premiseList.size(); int size = premiseList.size();
for(int i = 0;i < size;i++){ for(int i = 0;i < size;i++){
premise = premiseList.getJSONObject(i); premise = premiseList.getJSONObject(i);
premise.put("keyword", textReplace(premise.getString("keyword"), replaceMap)); premise.put("keyword", textReplace(premise.getString("keyword"), replaceMap));
//premise.put("keyword", premise.getString("keyword").replace("\r\n", "").replace("\n", "").replace("\r", "")); //premise.put("keyword", premise.getString("keyword").replace("\r\n", "").replace("\n", "").replace("\r", ""));
premiseList.set(i, premise); premiseList.set(i, premise);
} }
return premiseList; return premiseList;
} }
/** /**
* 如果剧情文本中出现变量槽,那么需要判断这个剧情的npc是不是在线模式,如果不是在线模式,就需要把变量槽过滤掉 * 如果剧情文本中出现变量槽,那么需要判断这个剧情的npc是不是在线模式,如果不是在线模式,就需要把变量槽过滤掉
* @param plot * @param plot
*/ */
public static void varSlotFilt(JSONObject plot, Map<String, StringBuffer> keywordMap){ public static void varSlotFilt(JSONObject plot, Map<String, StringBuffer> keywordMap){
String VARIABLE_SEARCH_PATTERN = "【(.*?)@(.*?)(\\$\\{.*?})", npcName, middleText = "", varSlot = ""; //不加 】,直接替换npcName到变量槽的文本 String VARIABLE_SEARCH_PATTERN = "【(.*?)@(.*?)(\\$\\{.*?})", npcName, middleText = "", varSlot = ""; //不加 】,直接替换npcName到变量槽的文本
//System.out.println(plot.getString("id")); //System.out.println(plot.getString("id"));
Pattern replacePattern = Pattern.compile(VARIABLE_SEARCH_PATTERN); Pattern replacePattern = Pattern.compile(VARIABLE_SEARCH_PATTERN);
Matcher m = replacePattern.matcher(plot.getString("plotText")); Matcher m = replacePattern.matcher(plot.getString("plotText"));
while (m.find()) { while (m.find()) {
npcName = m.group(1); npcName = m.group(1);
//onlineModeTalkers, 在CharecterConstructor中定义,q前面加一个逗号是为了防止出现子串匹配的问题 //onlineModeTalkers, 在CharecterConstructor中定义,q前面加一个逗号是为了防止出现子串匹配的问题
//System.out.println("npcName" + npcName); //System.out.println("npcName" + npcName);
//System.out.println("varInitialMap.get(\"onlineModeTalkers\")" + varInitialMap.get("onlineModeTalkers")); //System.out.println("varInitialMap.get(\"onlineModeTalkers\")" + varInitialMap.get("onlineModeTalkers"));
if(keywordMap.get("onlineModeTalkers").indexOf("," + npcName + ",") == -1) { if(keywordMap.get("onlineModeTalkers").indexOf("," + npcName + ",") == -1) {
varSlot = m.group(3); varSlot = m.group(3);
middleText = m.group(2); middleText = m.group(2);
plot.put("plotText", plot.getString("plotText").replace(npcName + "@" + middleText + varSlot, npcName + "@" + middleText)); plot.put("plotText", plot.getString("plotText").replace(npcName + "@" + middleText + varSlot, npcName + "@" + middleText));
} }
} }
} }
/** /**
* *
* 剧情生成中包括3个剧情标识: * 剧情生成中包括3个剧情标识:
* TaskLine 某地点剧情进度 * TaskLine 某地点剧情进度
* TaskCondition 某地点剧情进度用到的condition * TaskCondition 某地点剧情进度用到的condition
* TaskReply 某地点剧情用到的文本 * TaskReply 某地点剧情用到的文本
* 剧情(id)的状态:null标识未激活,1、 2表示激活 * 剧情(id)的状态:null标识未激活,1、 2表示激活
* 将所有剧情根据地点分为多条剧情线,每一条剧情线都有一个计数器,记录当前地点的剧情到了第几步。 * 将所有剧情根据地点分为多条剧情线,每一条剧情线都有一个计数器,记录当前地点的剧情到了第几步。
* 加上剧情计数器, null时未激活,大于等于1时表示已激活 * 加上剧情计数器, null时未激活,大于等于1时表示已激活
* @param root * @param root
* @param userinfo * @param userinfo
*/ */
public void BFSGenerate4(JSONObject root, UserInfo userinfo, JSONObject jsonObject) { public void BFSGenerate4(JSONObject root, UserInfo userinfo, JSONObject jsonObject) {
String id, rootId = (String) root.get("id"), adjId, nextId, conditionName = DEFAULT_CONDITION, String id, rootId = (String) root.get("id"), adjId, nextId, conditionName = DEFAULT_CONDITION,
nextUnknownText, curUnknownText, nextCondition, location, nextLocation, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition, reply; nextUnknownText, curUnknownText, nextCondition, location, nextLocation, taskLineName, nTaskLineName, lastTaskReply, lastTaskCondition, reply;
String hint, gameStep, nextGameStep; String hint, gameStep, nextGameStep;
JSONObject node = null, branchNode = null; JSONObject node = null, branchNode = null;
Boolean curAutoJump, nextAutoJump = false, prevAutoJump, moveWithPlot = false; Boolean curAutoJump, nextAutoJump = false, prevAutoJump, moveWithPlot = false;
StringBuffer skipText = new StringBuffer(), extraUK = new StringBuffer(), extraHP = new StringBuffer(), extraFT = new StringBuffer(), arriveUK = new StringBuffer(); StringBuffer skipText = new StringBuffer(), extraUK = new StringBuffer(), extraHP = new StringBuffer(), extraFT = new StringBuffer(), arriveUK = new StringBuffer();
JSONArray branch = null; JSONArray branch = null;
Boolean preferQA = false; Boolean preferQA = false;
int branchSize; int branchSize;
List<Premise> curPremiseList, historyPremiseList; List<Premise> curPremiseList, historyPremiseList;
//设置初始化unknown文本 //设置初始化unknown文本
root.put("nextUnknownText", varInitialMap.get("unknownText")); root.put("nextUnknownText", varInitialMap.get("unknownText"));
root.put("parentId", "null"); root.put("parentId", "null");
//当前剧情是否自动跳转的标识 //当前剧情是否自动跳转的标识
root.put("autoJump", false); root.put("autoJump", false);
//上一步剧情是否自动跳转的标识 //上一步剧情是否自动跳转的标识
root.put("prevAutoJump", false); root.put("prevAutoJump", false);
jsonObject.put("plotStartText", ((String)jsonObject.get("plotStartText")).replace("\n", "").replace(",", ",")); jsonObject.put("plotStartText", ((String)jsonObject.get("plotStartText")).replace("\n", "").replace(",", ","));
if(root.get("conditionName") != null && !root.get("conditionName").equals("")) if(root.get("conditionName") != null && !root.get("conditionName").equals(""))
conditionName = (String)root.get("conditionName"); conditionName = (String)root.get("conditionName");
else{ else{
//如果剧情是无条件剧情,就设置默认condition //如果剧情是无条件剧情,就设置默认condition
conditionName = DEFAULT_CONDITION; conditionName = DEFAULT_CONDITION;
root.put("conditionName", conditionName); root.put("conditionName", conditionName);
} }
//根据地点生成变量名,标志地点的任务进度,condition和回答 //根据地点生成变量名,标志地点的任务进度,condition和回答
String startPlace = root.getString("place"); String startPlace = root.getString("place");
String startTaskLine = String.format(TASK_LINE, startPlace); String startTaskLine = String.format(TASK_LINE, startPlace);
String startTaskCondition = String.format(TASK_CONDITION, startPlace); String startTaskCondition = String.format(TASK_CONDITION, startPlace);
String startTaskReply = String.format(TASK_REPLY, startPlace); String startTaskReply = String.format(TASK_REPLY, startPlace);
//在配置文件中设置初始值 //在配置文件中设置初始值
varInitialMap.put("site", startPlace); varInitialMap.put("site", startPlace);
varInitialMap.put(startTaskLine, String.format(GAME_STEP_FORMAT, botAccount, rootId)); varInitialMap.put(startTaskLine, String.format(GAME_STEP_FORMAT, botAccount, rootId));
varInitialMap.put(startTaskCondition, ""); varInitialMap.put(startTaskCondition, "");
varInitialMap.put(startTaskReply, ""); varInitialMap.put(startTaskReply, "");
//添加变量的描述 //添加变量的描述
conditionDescription.put(startTaskLine, startTaskLine); conditionDescription.put(startTaskLine, startTaskLine);
conditionDescription.put(startTaskCondition,startTaskCondition); conditionDescription.put(startTaskCondition,startTaskCondition);
conditionDescription.put(startTaskReply, startTaskReply); conditionDescription.put(startTaskReply, startTaskReply);
//generateStartGame(root, jsonObject, startPlace, conditionName); //generateStartGame(root, jsonObject, startPlace, conditionName);
Queue<JSONObject> queue = new LinkedList<JSONObject>(); Queue<JSONObject> queue = new LinkedList<JSONObject>();
queue.add(root); queue.add(root);
//System.out.println(root.toJSONString()); //System.out.println(root.toJSONString());
while (!queue.isEmpty()) { while (!queue.isEmpty()) {
node = queue.remove(); node = queue.remove();
//剧情id //剧情id
id = (String) node.get("id"); id = (String) node.get("id");
location = ((String) node.get("place")).split("\\+")[0]; location = ((String) node.get("place")).split("\\+")[0];
conditionName = (String) node.get("conditionName"); conditionName = (String) node.get("conditionName");
//当前剧情是否自动跳转 //当前剧情是否自动跳转
curAutoJump = node.getBoolean("autoJump"); curAutoJump = node.getBoolean("autoJump");
prevAutoJump = node.getBoolean("prevAutoJump"); prevAutoJump = node.getBoolean("prevAutoJump");
curUnknownText = (String) node.get("unknownText"); curUnknownText = (String) node.get("unknownText");
//preferQA = node.getBoolean("remain"); //preferQA = node.getBoolean("remain");
//剧情状态的名字,任务线xxx的进度 //剧情状态的名字,任务线xxx的进度
taskLineName = String.format(TASK_LINE, location); taskLineName = String.format(TASK_LINE, location);
conditionDescription.put(id, String.format(PLOT_STATUS, id)); conditionDescription.put(id, String.format(PLOT_STATUS, id));
varInitialMap.put(id ,""); varInitialMap.put(id ,"");
//本任务线的最后一个condition和本任务线的最后一个回答 //本任务线的最后一个condition和本任务线的最后一个回答
branch = node.getJSONArray("branch"); branch = node.getJSONArray("branch");
branchSize = branch.size(); branchSize = branch.size();
//遍历剧情分支 //遍历剧情分支
for (int i = 0; i < branchSize; i++) { for (int i = 0; i < branchSize; i++) {
skipText.setLength(0); skipText.setLength(0);
branchNode = branch.getJSONObject(i); branchNode = branch.getJSONObject(i);
//reply = branchNode.getString("reply"); //reply = branchNode.getString("reply");
Map<String, String> updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class); Map<String, String> updateKnowledge = JSONObject.toJavaObject(branchNode.getJSONObject("updateKnowledge"), Map.class);
nextId = branchNode.getString("nextPlotId"); nextId = branchNode.getString("nextPlotId");
preferQA = branchNode.getBoolean("remain"); preferQA = branchNode.getBoolean("remain");
//是否将玩家移动到下个剧情所在地点 //是否将玩家移动到下个剧情所在地点
moveWithPlot = branchNode.getBoolean("moveWithPlot"); moveWithPlot = branchNode.getBoolean("moveWithPlot");
//如果下一部剧情不存在,就新建一个终止结点,id名为当前id+"_end",终止节点剧情文本为当前剧情的unknown文本 //如果下一部剧情不存在,就新建一个终止结点,id名为当前id+"_end",终止节点剧情文本为当前剧情的unknown文本
if(nextId == null || nextId.equals("") || !plotIndex.containsKey(nextId)){ if(nextId == null || nextId.equals("") || !plotIndex.containsKey(nextId)){
nextId = id + "_end"; nextId = id + "_end";
createEndNode(node, id, nextId, curUnknownText); createEndNode(node, id, nextId, curUnknownText);
} }
//如果选了合并剧情/自动跳转,那么一定会把玩家地点切换到下个剧情的地点 //如果选了合并剧情/自动跳转,那么一定会把玩家地点切换到下个剧情的地点
if(moveWithPlot == null || curAutoJump) if(moveWithPlot == null || curAutoJump)
moveWithPlot = true; moveWithPlot = true;
//下一步剧情的unknown文本 //下一步剧情的unknown文本
nextUnknownText = plotIndex.get(nextId).getString("unknownText"); nextUnknownText = plotIndex.get(nextId).getString("unknownText");
//下一步剧情的自动跳转 //下一步剧情的自动跳转
nextAutoJump = plotIndex.get(nextId).getBoolean("autoJump"); nextAutoJump = plotIndex.get(nextId).getBoolean("autoJump");
reply = plotIndex.get(nextId).getString("plotText"); reply = plotIndex.get(nextId).getString("plotText");
if(reply.equals("")) if(reply.equals(""))
reply = curUnknownText; reply = curUnknownText;
//如果存在下一剧情,就将下一步剧情的condition设为要激活的conditin,把地点更新为下一步剧情的地点,并更新任务线进度 //如果存在下一剧情,就将下一步剧情的condition设为要激活的conditin,把地点更新为下一步剧情的地点,并更新任务线进度
nextCondition = plotIndex.get(nextId).getString("conditionName"); nextCondition = plotIndex.get(nextId).getString("conditionName");
if(nextCondition.equals("")) if(nextCondition.equals(""))
//condition为空,则设置默认condition //condition为空,则设置默认condition
nextCondition = DEFAULT_CONDITION; nextCondition = DEFAULT_CONDITION;
nextLocation = plotIndex.get(nextId).getString("place"); nextLocation = plotIndex.get(nextId).getString("place");
//需要更新 下个剧情发生地点 任务线进度 //需要更新 下个剧情发生地点 任务线进度
nTaskLineName = String.format(TASK_LINE, nextLocation); nTaskLineName = String.format(TASK_LINE, nextLocation);
////需要更新 下个剧情发生地点最后一个condition ////需要更新 下个剧情发生地点最后一个condition
lastTaskCondition = String.format(TASK_CONDITION, nextLocation); lastTaskCondition = String.format(TASK_CONDITION, nextLocation);
lastTaskReply = String.format(TASK_REPLY, nextLocation); lastTaskReply = String.format(TASK_REPLY, nextLocation);
//剧情点qa标识 //剧情点qa标识
gameStep = String.format(GAME_STEP_FORMAT, botAccount, id); gameStep = String.format(GAME_STEP_FORMAT, botAccount, id);
nextGameStep = String.format(GAME_STEP_FORMAT, botAccount,nextId); nextGameStep = String.format(GAME_STEP_FORMAT, botAccount,nextId);
/** /**
* 额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情 * 额外条件是任务线进度达到当前剧情,额外更新变量是将任务线移动至下一剧情
* 如果某个地点的剧情已经到结尾啦,那么有两种解决方法: * 如果某个地点的剧情已经到结尾啦,那么有两种解决方法:
* 1: 将剧情停留在最后一步剧情 * 1: 将剧情停留在最后一步剧情
* 2. 设一个专门的剧情表示剧情的结尾 * 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 + "," + nextId + "::match-Include=null";
/** /**
* 剧情分支触发的系统前置条件 * 剧情分支触发的系统前置条件
* 该地点的任务线进度=玩家剧情进度 * 该地点的任务线进度=玩家剧情进度
* 玩家处于剧情地点 * 玩家处于剧情地点
* 剧情已被激活 * 剧情已被激活
*/ */
appendPremise(extraHP, taskLineName, "match", "Include", gameStep); appendPremise(extraHP, taskLineName, "match", "Include", gameStep);
appendPremise(extraHP, "site", "match", "Include", location); appendPremise(extraHP, "site", "match", "Include", location);
appendPremise(extraHP, id, "match", "Include", "1"); appendPremise(extraHP, id, "match", "Include", "1");
/** /**
* 剧情分支触发后的变量更新操作 * 剧情分支触发后的变量更新操作
* 下个剧情发生地点 任务线进度 * 下个剧情发生地点 任务线进度
* 下个剧情发生地点最后一个condition * 下个剧情发生地点最后一个condition
* 当前剧情状态加一 * 当前剧情状态加一
* 下一步剧情设为1, 激活 * 下一步剧情设为1, 激活
* 无匹配次数清零 * 无匹配次数清零
* *
*/ */
appendKnowledge(extraUK, nTaskLineName, nextGameStep); appendKnowledge(extraUK, nTaskLineName, nextGameStep);
appendKnowledge(extraUK, lastTaskCondition, nextCondition); appendKnowledge(extraUK, lastTaskCondition, nextCondition);
appendKnowledge(extraUK, lastTaskReply, reply); appendKnowledge(extraUK, lastTaskReply, reply);
appendKnowledge(extraUK, id, "+1"); appendKnowledge(extraUK, id, "+1");
appendKnowledge(extraUK, nextId, "1"); appendKnowledge(extraUK, nextId, "1");
appendKnowledge(extraUK, UNKNOWN_COUNTER_NAME, "0"); appendKnowledge(extraUK, UNKNOWN_COUNTER_NAME, "0");
//如果剧情结束了,那么qa还是留在最后一部剧情 //如果剧情结束了,那么qa还是留在最后一部剧情
//如果下一步剧情不存在,那么下一步剧情id为当前id加后缀_end,但是用户提交qa的game_step应该还是当前id,没有加上_end //如果下一步剧情不存在,那么下一步剧情id为当前id加后缀_end,但是用户提交qa的game_step应该还是当前id,没有加上_end
if(nextId.endsWith("_end")) { if(nextId.endsWith("_end")) {
nextGameStep = String.format(GAME_STEP_FORMAT, botAccount,id); nextGameStep = String.format(GAME_STEP_FORMAT, botAccount,id);
} }
//System.out.println(id); //System.out.println(id);
appendFeature(extraFT, "match"); appendFeature(extraFT, "match");
//如果下一步剧情是自动跳转,并且(当前剧情和下一部剧情地点相同或者用户选中了自动切换地点), //如果下一步剧情是自动跳转,并且(当前剧情和下一部剧情地点相同或者用户选中了自动切换地点),
// 先把本剧情的文本保留到plot_jump_text, 然后系统会在这个配置文件处理完成后,激活下一个(自动跳转)剧情的配置文件 // 先把本剧情的文本保留到plot_jump_text, 然后系统会在这个配置文件处理完成后,激活下一个(自动跳转)剧情的配置文件
if(doActivatePlot(nextAutoJump, location, nextLocation, moveWithPlot) ){ if(doActivatePlot(nextAutoJump, location, nextLocation, moveWithPlot) ){
appendKnowledge(extraUK, "plot_jump_text", "str+" + reply); appendKnowledge(extraUK, "plot_jump_text", "str+" + reply);
} }
/** /**
* 1. 主角是否随剧情移动 * 1. 主角是否随剧情移动
* 如果随剧情移动,则更新地点和game_step * 如果随剧情移动,则更新地点和game_step
* 如果不随剧情移动,则不更新地点和game_step,添加中间配置"去XX",设高优先级,并更新状态 * 如果不随剧情移动,则不更新地点和game_step,添加中间配置"去XX",设高优先级,并更新状态
* *
* 2. 当前条件是否为空 * 2. 当前条件是否为空
* 如果当前条件为空,则提交qa激活并进入下一步剧情 * 如果当前条件为空,则提交qa激活并进入下一步剧情
* 如果当前条件不为空,则需要满足条件才能进入下一步剧情 * 如果当前条件不为空,则需要满足条件才能进入下一步剧情
* *
* 3. 下一部剧情是否为空 * 3. 下一部剧情是否为空
* *
* *
* 4. 有没有说去XX * 4. 有没有说去XX
* *
* 主角不随剧情移动+当前条件为空+去沙滩 * 主角不随剧情移动+当前条件为空+去沙滩
* 1、沙滩无剧情 * 1、沙滩无剧情
* 2、沙滩有剧情 * 2、沙滩有剧情
* *
* 5. 地点变化 * 5. 地点变化
* 1. 当前所处地点 * 1. 当前所处地点
* 2. 下一步剧情所处地点(包含自动跳转的情况) * 2. 下一步剧情所处地点(包含自动跳转的情况)
* 3. 自动跳转完成后的地点 * 3. 自动跳转完成后的地点
*/ */
/** /**
* 自动跳转前的剧情也要记下来,这里是自动跳转前需要更新的变量(无论是否包含自动跳转都会更新) * 自动跳转前的剧情也要记下来,这里是自动跳转前需要更新的变量(无论是否包含自动跳转都会更新)
* 1. 将自动跳转剧情的关联地点最后被激活的condition更新为yaobuyao (其实这一步是非必须的,) * 1. 将自动跳转剧情的关联地点最后被激活的condition更新为yaobuyao (其实这一步是非必须的,)
* 2. 自动跳转剧情文本保存到beforeJumpTaskReply * 2. 自动跳转剧情文本保存到beforeJumpTaskReply
* 3. 当前剧情和下一步剧情更新状态 * 3. 当前剧情和下一步剧情更新状态
*/ */
//如果用户在分支里选了提前激活 //如果用户在分支里选了提前激活
if(branchNode.containsKey("activateExtraPlot")) { if(branchNode.containsKey("activateExtraPlot")) {
//激活除了下一步剧情以外的剧情 //激活除了下一步剧情以外的剧情
extraActivatedPlot(extraUK, nextLocation, branchNode.getJSONObject("activateExtraPlot")); extraActivatedPlot(extraUK, nextLocation, branchNode.getJSONObject("activateExtraPlot"));
} }
//如果主角的位置随着剧情移动(切换地点)或者下一步剧情地点和当前剧情相同,即如果玩家可以直接到达下一个剧情所在地点,主角地点和game_step要做相应更新, //如果主角的位置随着剧情移动(切换地点)或者下一步剧情地点和当前剧情相同,即如果玩家可以直接到达下一个剧情所在地点,主角地点和game_step要做相应更新,
if(moveWithPlot || location.equals(nextLocation)) { if(moveWithPlot || location.equals(nextLocation)) {
appendKnowledge(extraUK, "site", nextLocation); appendKnowledge(extraUK, "site", nextLocation);
appendKnowledge(extraUK, "game_step", nextGameStep); appendKnowledge(extraUK, "game_step", nextGameStep);
appendKnowledge(extraUK,"unknownText", nextUnknownText); appendKnowledge(extraUK,"unknownText", nextUnknownText);
//extraUK += "-<-site:" + nextLocation + "-<-game_step:" + nextGameStep; //extraUK += "-<-site:" + nextLocation + "-<-game_step:" + nextGameStep;
//如果当前剧情所在地喝下一步剧情所在地不一样,那么unknown文本 //如果当前剧情所在地喝下一步剧情所在地不一样,那么unknown文本
//只有到达下一步剧情所在地时才会更新 //只有到达下一步剧情所在地时才会更新
} else { } else {
if(!location.equals(nextLocation)){ if(!location.equals(nextLocation)){
//System.out.println(id + "报异常" + curUnknownText); //System.out.println(id + "报异常" + curUnknownText);
if(curUnknownText.equals("")) { if(curUnknownText.equals("")) {
//如果没有unknown,就提示他到下一个地点 //如果没有unknown,就提示他到下一个地点
hint = String.format(LOCATION_HINT, nextLocation); hint = String.format(LOCATION_HINT, nextLocation);
//hint = "请到" + nextLocation; //hint = "请到" + nextLocation;
//如果当前地点和下一步剧情地点不同,要提示 //如果当前地点和下一步剧情地点不同,要提示
}else { }else {
//如果有unknown,就提示unknown文本 //如果有unknown,就提示unknown文本
hint = curUnknownText; hint = curUnknownText;
} }
//下一部剧情在不同地点时,为了防止到配置文件重复执行,需要加一个标志表示下一步剧情是否已经发生过 //下一部剧情在不同地点时,为了防止到配置文件重复执行,需要加一个标志表示下一步剧情是否已经发生过
// activate_by 下一个地点的剧情是由当前剧情激活的 // activate_by 下一个地点的剧情是由当前剧情激活的
//_activate_ready 下一个地点的剧情等待被激活 //_activate_ready 下一个地点的剧情等待被激活
appendKnowledge(extraUK, nextLocation + "_activate_by", id); appendKnowledge(extraUK, nextLocation + "_activate_by", id);
appendKnowledge(extraUK, nextLocation + "_activate_ready", "1"); appendKnowledge(extraUK, nextLocation + "_activate_ready", "1");
// 如果不能直接到达所在地点,说明剧情1-1和1-2直接存在一个中间结点,这些更新操作会放在中间结点执行(动态生成,方法名:arriveActivatePlot2 这个中间结点会被当做一个监听剧情来处理) // 如果不能直接到达所在地点,说明剧情1-1和1-2直接存在一个中间结点,这些更新操作会放在中间结点执行(动态生成,方法名:arriveActivatePlot2 这个中间结点会被当做一个监听剧情来处理)
arriveActivatePlot2(jsonObject, id, nextId, nextLocation); arriveActivatePlot2(jsonObject, id, nextId, nextLocation);
//回答改为提示文本 //回答改为提示文本
reply = hint; reply = hint;
} }
} }
//System.out.println(branchNode); //System.out.println(branchNode);
//取出作者设定的剧情条件 //取出作者设定的剧情条件
curPremiseList = JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), Premise.class); curPremiseList = JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), Premise.class);
historyPremiseList = JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), Premise.class); historyPremiseList = JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), Premise.class);
//是否将当前识别到的数据加入到已知数据列表 //是否将当前识别到的数据加入到已知数据列表
if((Boolean)branchNode.get("includeCurInfo")){ if((Boolean)branchNode.get("includeCurInfo")){
appendFeature(extraFT, "includeCurInfo"); appendFeature(extraFT, "includeCurInfo");
} }
//如果分支中存在额外操作,在将这些额外操作(提交表单、激活、存档、读档等)添加到配置文件 //如果分支中存在额外操作,在将这些额外操作(提交表单、激活、存档、读档等)添加到配置文件
if(branchNode.get("extraFeature") != null){ if(branchNode.get("extraFeature") != null){
appendFeature(extraFT, branchNode.getString("extraFeature")); appendFeature(extraFT, branchNode.getString("extraFeature"));
} }
//如果符合激活下一个剧情配置文件的操作 //如果符合激活下一个剧情配置文件的操作
if(doActivatePlot(nextAutoJump, location, nextLocation, moveWithPlot) ){ if(doActivatePlot(nextAutoJump, location, nextLocation, moveWithPlot) ){
//在配置文件中添加激活的操作 //在配置文件中添加激活的操作
appendFeature(extraFT, "activate:after"); appendFeature(extraFT, "activate:after");
//激活下一步剧情id //激活下一步剧情id
nextCondition = "plot_" + nextId; nextCondition = "plot_" + nextId;
} }
//生成配置文件 //生成配置文件
configTermText = new ConfigTermText( configTermText = new ConfigTermText(
curPremiseList, curPremiseList,
historyPremiseList, historyPremiseList,
updateKnowledge, updateKnowledge,
"", extraHP.toString(), extraUK.toString(), "", extraHP.toString(), extraUK.toString(),
extraFT.toString(), reply, nextCondition, "1" extraFT.toString(), reply, nextCondition, "1"
); );
configTermText.setConfigName("plot_" + id, false); configTermText.setConfigName("plot_" + id, false);
//当剧情没有条件限制时的操作(条件剧情) 需要顺便激活qa、地图、物品的查询配置文件, 额外要求当前剧情不是自动跳转(当前剧情不是合并剧情) //当剧情没有条件限制时的操作(条件剧情) 需要顺便激活qa、地图、物品的查询配置文件, 额外要求当前剧情不是自动跳转(当前剧情不是合并剧情)
if (curPremiseList.size() == 0 && historyPremiseList.size() == 0 && !curAutoJump){ if (curPremiseList.size() == 0 && historyPremiseList.size() == 0 && !curAutoJump){
if(preferQA != null && preferQA) { if(preferQA != null && preferQA) {
ConfigTermText termText1, termText2, tmpTermText; ConfigTermText termText1, termText2, tmpTermText;
tmpTermText = configTermText; tmpTermText = configTermText;
termText1 = createTermExtra1(configTermText); termText1 = createTermExtra1(configTermText);
termText2 = createTermExtra2(configTermText); termText2 = createTermExtra2(configTermText);
configTermText = alterTerm(configTermText); configTermText = alterTerm(configTermText);
configTermTextList.add(termText1); configTermTextList.add(termText1);
configTermTextList.add(termText2); configTermTextList.add(termText2);
} }
else { else {
Boolean activateFlag = false; Boolean activateFlag = false;
//有activate意味着下一步剧情是合并剧情 //有activate意味着下一步剧情是合并剧情
if(extraFT.indexOf("activate") != -1) if(extraFT.indexOf("activate") != -1)
activateFlag = true; activateFlag = true;
unconditionalPlotProcess(configTermText, nextCondition, activateFlag); unconditionalPlotProcess(configTermText, nextCondition, activateFlag);
} }
} }
if (branchNode.getBoolean("higherPriority") != null && branchNode.getBoolean("higherPriority")) if (branchNode.getBoolean("higherPriority") != null && branchNode.getBoolean("higherPriority"))
configTermText.setAuxiliaryPriority("3"); configTermText.setAuxiliaryPriority("3");
configTermTextList.add(configTermText); configTermTextList.add(configTermText);
//将子结点加入队列 //将子结点加入队列
adjId = nextId; adjId = nextId;
plotEnQueue(queue, id, adjId, nextUnknownText, curAutoJump); plotEnQueue(queue, id, adjId, nextUnknownText, curAutoJump);
if(branchNode.getJSONObject("activateExtraPlot") != null){ if(branchNode.getJSONObject("activateExtraPlot") != null){
for(String activateId:branchNode.getJSONObject("activateExtraPlot").keySet()){ for(String activateId:branchNode.getJSONObject("activateExtraPlot").keySet()){
plotEnQueue(queue, id, activateId, nextUnknownText, curAutoJump); plotEnQueue(queue, id, activateId, nextUnknownText, curAutoJump);
} }
} }
extraFT.setLength(0); extraFT.setLength(0);
extraHP.setLength(0); extraHP.setLength(0);
extraUK.setLength(0); extraUK.setLength(0);
skipText.setLength(0); skipText.setLength(0);
arriveUK.setLength(0); arriveUK.setLength(0);
} }
} }
/** /**
* ---------------------------------------------------------------------------------------------------- * ----------------------------------------------------------------------------------------------------
* 剧情不设条件时的处理 * 剧情不设条件时的处理
* 1. 如果qa返回大于90则回答common_answer+ 剧情回答,并进入下一步剧情,这里的下一步condition是从激活之前保存的临时变量中读取出来的 * 1. 如果qa返回大于90则回答common_answer+ 剧情回答,并进入下一步剧情,这里的下一步condition是从激活之前保存的临时变量中读取出来的
* 2. 如果qa返回小于90则只回答剧情文本 * 2. 如果qa返回小于90则只回答剧情文本
* 3. 如果qa返回not_found则只回答剧情文本 * 3. 如果qa返回not_found则只回答剧情文本
* 4. 无论哪种情况都会跳下一步剧情 * 4. 无论哪种情况都会跳下一步剧情
*/ */
unknownTypeConfigTermGenerate("sleeping", "queryskip1","qa_status::match-Include=OK,qa_score::number-Smaller=98", unknownTypeConfigTermGenerate("sleeping", "queryskip1","qa_status::match-Include=OK,qa_score::number-Smaller=98",
"match", "{临时变量reply-2}", "process-nextStep:var={临时变量condition-2}"); "match", "{临时变量reply-2}", "process-nextStep:var={临时变量condition-2}");
unknownTypeConfigTermGenerate("sleeping", "queryskip2","qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=98", unknownTypeConfigTermGenerate("sleeping", "queryskip2","qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=98",
"match", "{临时变量reply-2}", "process-nextStep:var={临时变量condition-2}"); "match", "{临时变量reply-2}", "process-nextStep:var={临时变量condition-2}");
unknownTypeConfigTermGenerate("sleeping", "queryskip3","qa_status::match-Include=not_found", unknownTypeConfigTermGenerate("sleeping", "queryskip3","qa_status::match-Include=not_found",
"match", "{临时变量reply-2}", "process-nextStep:var={临时变量condition-2}"); "match", "{临时变量reply-2}", "process-nextStep:var={临时变量condition-2}");
/** /**
* ---------------------------------------------------------------------------------------------------- * ----------------------------------------------------------------------------------------------------
* 待激活列表,用于qa问答 * 待激活列表,用于qa问答
*/ */
//处于激活状态,其他的属于待激活状态,jStatus这一条不设为1,而是0 //处于激活状态,其他的属于待激活状态,jStatus这一条不设为1,而是0
unknownTypeConfigTermGenerate("waiting", "unknownStart","", unknownTypeConfigTermGenerate("waiting", "unknownStart","",
"activate,post::gameQA(" + QA_URL + ")", "{unknownText-2}", ""); "activate,post::gameQA(" + QA_URL + ")", "{unknownText-2}", "");
unknownTypeConfigTermGenerate("sleeping", "unknown1","qa_status::match-Include=not_found", unknownTypeConfigTermGenerate("sleeping", "unknown1","qa_status::match-Include=not_found",
"match,return-0", "{unknownText-2}", ""); "match,return-0", "{unknownText-2}", "");
unknownTypeConfigTermGenerate("sleeping", "unknown2","qa_status::match-Include=not_found,unknownText::match-Include=null", unknownTypeConfigTermGenerate("sleeping", "unknown2","qa_status::match-Include=not_found,unknownText::match-Include=null",
"match,return-0", UNKNOWN_TEXT, ""); "match,return-0", UNKNOWN_TEXT, "");
unknownTypeConfigTermGenerate("sleeping", "unknown3","qa_status::match-Include=OK,qa_score::number-Smaller=98,unknownText::match-Include=null", unknownTypeConfigTermGenerate("sleeping", "unknown3","qa_status::match-Include=OK,qa_score::number-Smaller=98,unknownText::match-Include=null",
"match,return-0", UNKNOWN_TEXT, ""); "match,return-0", UNKNOWN_TEXT, "");
unknownTypeConfigTermGenerate("sleeping", "unknown4","qa_status::match-Include=OK,qa_score::number-Smaller=98", unknownTypeConfigTermGenerate("sleeping", "unknown4","qa_status::match-Include=OK,qa_score::number-Smaller=98",
"match,return-0", "{unknownText-2}", ""); "match,return-0", "{unknownText-2}", "");
//由于剧情跳转时地点可能发生变化, qa问答的句子可能因为npc不再同一位置而被过滤掉,所以将common_answer的字符串合并放在postprocessing中 //由于剧情跳转时地点可能发生变化, qa问答的句子可能因为npc不再同一位置而被过滤掉,所以将common_answer的字符串合并放在postprocessing中
unknownTypeConfigTermGenerate("sleeping", "common_answer","qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=98", unknownTypeConfigTermGenerate("sleeping", "common_answer","qa_status::match-Include=OK,qa_score::number-BiggerOrEqual=98",
"match,return-0", "", ""); "match,return-0", "", "");
//--------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------
/** /**
* ---------------------------------------------------------------------------------------------------- * ----------------------------------------------------------------------------------------------------
* 用于存档 * 用于存档
*/ */
configTermText = new ConfigTermText( configTermText = new ConfigTermText(
"save_game::match-Include=+要:存档", " ", "match,return-0,gameBackup", "save_game::match-Include=+要:存档", " ", "match,return-0,gameBackup",
"{archiveOperation-2}" ," ", "" "{archiveOperation-2}" ," ", ""
); );
configTermText.setAuxiliaryPriority("4"); configTermText.setAuxiliaryPriority("4");
configTermTextList.add(configTermText); configTermTextList.add(configTermText);
} }
public void unknownTypeConfigTermGenerate(String configStatus, String configName, String historyPremise, String feature, String reply, String updateKnowledge){ //
public void unknownTypeConfigTermGenerate(String configStatus, String configName, String historyPremise, String feature, String reply, String updateKnowledge){
configTermText = new ConfigTermText(
" ", historyPremise, feature, configTermText = new ConfigTermText(
reply ," ", UNKNOWN_COUNTER_NAME + ":+1" " ", historyPremise, feature,
); reply ," ", UNKNOWN_COUNTER_NAME + ":+1"
configTermText.setStatus(configStatus); );
configTermText.setConfigName(configName,false); configTermText.setStatus(configStatus);
configTermText.setAuxiliaryPriority("0"); configTermText.setConfigName(configName,false);
configTermText.setAuxiliaryPriority("0");
if(!updateKnowledge.equals(""))
configTermText.setUpdateKnowledge(configTermText.getUpdateKnowledge() + "-<-" + updateKnowledge); if(!updateKnowledge.equals(""))
configTermText.setUpdateKnowledge(configTermText.getUpdateKnowledge() + "-<-" + updateKnowledge);
if(configStatus.equals("waiting")){
configTermText.setNextStep("unknown4,unknown3,unknown2,unknown1,common_answer"); if(configStatus.equals("waiting")){
} configTermText.setNextStep("unknown4,unknown3,unknown2,unknown1,common_answer");
configTermTextList.add(configTermText); }
} configTermTextList.add(configTermText);
}
/**
* 新建一个剧情结点 /**
* @param node * 新建一个剧情结点
* @param id * @param node
* @param nextId * @param id
* @param nextUnknownText * @param nextId
*/ * @param nextUnknownText
public void createEndNode(JSONObject node, String id, String nextId, String nextUnknownText){ */
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 condition = (String) node.get("conditionName");
String location = ((String) node.get("place")).split("\\+")[0];
String nextCondition = condition;
String nextLocation = location; String nextCondition = condition;
String nTaskLineName = String.format(TASK_LINE, nextCondition); String nextLocation = location;
String nTaskLineName = String.format(TASK_LINE, nextCondition);
JSONObject endNode = new JSONObject();
endNode.put("place", location); JSONObject endNode = new JSONObject();
endNode.put("conditionName", condition); endNode.put("place", location);
endNode.put("id", nextId); endNode.put("conditionName", condition);
endNode.put("plotText", nextUnknownText); endNode.put("id", nextId);
endNode.put("autoJump", false); endNode.put("plotText", nextUnknownText);
endNode.put("includeCurInfo", true); endNode.put("autoJump", false);
endNode.put("updateKnowledge", new ArrayList()); endNode.put("includeCurInfo", true);
endNode.put("unknownText", ""); endNode.put("updateKnowledge", new ArrayList());
endNode.put("unknownText", "");
plotIndex.put(nextId, endNode);
visited.put(nextId, true); plotIndex.put(nextId, endNode);
visited.put(nextId, true);
}
}
/**
* 从配置文件中获取游戏开始时 游戏选择 的剧情, 即选择开始或者重新开始或者根据不同地点读档 /**
* @param gameElements * 从配置文件中获取游戏开始时 游戏选择 的剧情, 即选择开始或者重新开始或者根据不同地点读档
* @param keywordMap * @param gameElements
*/ * @param keywordMap
void addGameStartPlot(JSONObject gameElements, Map<String, StringBuffer> keywordMap){ */
void addGameStartPlot(JSONObject gameElements, Map<String, StringBuffer> keywordMap){
File file = null;
FileReader fr = null; File file = null;
BufferedReader br = null; FileReader fr = null;
try { BufferedReader br = null;
file = new File("gameconfig.txt"); try {
fr = new FileReader(file); file = new File("gameconfig.txt");
fr = new FileReader(file);
br = new BufferedReader(fr);
String jsonStr = br.readLine(); 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("startAutoJump", gameElements.getString("startAutoJump"));
jsonStr = jsonStr.replace("plotStartText", gameElements.getString("plotStartText")); jsonStr = jsonStr.replace("firstUnknownText", gameElements.getString("firstUnknownText"));
jsonStr = jsonStr.replace("startId", gameElements.getString("start")); jsonStr = jsonStr.replace("plotStartText", gameElements.getString("plotStartText"));
jsonStr = jsonStr.replace("site_list", keywordMap.get("site_list").toString()); jsonStr = jsonStr.replace("startId", gameElements.getString("start"));
jsonStr = jsonStr.replace("site_list", keywordMap.get("site_list").toString());
//System.out.println("JSONSTR ------------------------------\n" + jsonStr);
JSONObject config = JSONObject.parseObject(jsonStr); //System.out.println("JSONSTR ------------------------------\n" + jsonStr);
JSONObject config = JSONObject.parseObject(jsonStr);
gameElements.getJSONArray("plots").addAll(config.getJSONArray("gameStart"));
gameElements.put("start", "start1"); gameElements.getJSONArray("plots").addAll(config.getJSONArray("gameStart"));
gameElements.put("firstUnknownText", GAME_START_HINT); gameElements.put("start", "start1");
gameElements.put("firstUnknownText", GAME_START_HINT);
br.close();
fr.close(); br.close();
} catch (FileNotFoundException e) { fr.close();
e.printStackTrace(); } catch (FileNotFoundException e) {
} catch (IOException e) { e.printStackTrace();
e.printStackTrace(); } catch (IOException e) {
} e.printStackTrace();
}
}
}
/**
* //如果是无条件剧情,那么需要跟着一个激活操作,激活查询qa、地图、物品、npc的配置文件 /**
* *号是一个通配符,只要配置文件前缀相同就会被激活 * //如果是无条件剧情,那么需要跟着一个激活操作,激活查询qa、地图、物品、npc的配置文件
* @param configTermText * *号是一个通配符,只要配置文件前缀相同就会被激活
* @param nextCondition * @param configTermText
* @param activateFlag * @param nextCondition
*/ * @param activateFlag
public void unconditionalPlotProcess(ConfigTermText configTermText, String nextCondition, Boolean activateFlag){ */
public void unconditionalPlotProcess(ConfigTermText configTermText, String nextCondition, Boolean activateFlag){
configTermText.setFeature(configTermText.getFeature() + ",activate,post::gameQA(" + QA_URL + ")");
configTermText.setFeature(configTermText.getFeature() + ",activate,post::gameQA(" + QA_URL + ")");
//
//if() //
if(activateFlag){ //if()
configTermText.setNextStep(nextCondition+ ",queryskip*,map*,item*,npc*"); if(activateFlag){
}else { configTermText.setNextStep(nextCondition+ ",queryskip*,map*,item*,npc*");
configTermText.setNextStep("queryskip*,map*,item*,npc*"); }else {
} configTermText.setNextStep("queryskip*,map*,item*,npc*");
}
//虽然激活了查询相关的配置文件,但返回给引擎的condition还是应该用剧情里的,所以
//将本配置条目中nextStep的值放在“临时变量condition”中,将本配置条目中的回答放在“临时变量reply”中,激活查询配置后,最后返回的condition应该是剧情指定的下一个condition //虽然激活了查询相关的配置文件,但返回给引擎的condition还是应该用剧情里的,所以
//查询完了之后应该 把这两个临时变量复制到被激活的配置文件中,作为回答返回。 //将本配置条目中nextStep的值放在“临时变量condition”中,将本配置条目中的回答放在“临时变量reply”中,激活查询配置后,最后返回的condition应该是剧情指定的下一个condition
configTermText.setUpdateKnowledge(configTermText.getUpdateKnowledge() + "-<-临时变量condition:"+ nextCondition +"-<-临时变量reply:var={reply-3}"); //查询完了之后应该 把这两个临时变量复制到被激活的配置文件中,作为回答返回。
configTermText.setNextStepStatus("active"); configTermText.setUpdateKnowledge(configTermText.getUpdateKnowledge() + "-<-临时变量condition:"+ nextCondition +"-<-临时变量reply:var={reply-3}");
} configTermText.setNextStepStatus("active");
}
/**
* 在条件文本后面添加一个条件 /**
* @param premiseStr * 在条件文本后面添加一个条件
* @param conditionName * @param premiseStr
* @param cmpType * @param conditionName
* @param operator * @param cmpType
* @param value * @param operator
*/ * @param value
public void appendPremise(StringBuffer premiseStr, String conditionName, String cmpType, String operator, String value){ */
int strLen = premiseStr.length(); public void appendPremise(StringBuffer premiseStr, String conditionName, String cmpType, String operator, String value){
String split_punt = ""; int strLen = premiseStr.length();
String split_punt = "";
if(premiseStr.length() != 0)
split_punt = ","; if(premiseStr.length() != 0)
split_punt = ",";
premiseStr.append(split_punt);
premiseStr.append(conditionName); premiseStr.append(split_punt);
premiseStr.append("::"); premiseStr.append(conditionName);
premiseStr.append(cmpType); premiseStr.append("::");
premiseStr.append("-"); premiseStr.append(cmpType);
premiseStr.append(operator); premiseStr.append("-");
premiseStr.append("="); premiseStr.append(operator);
premiseStr.append(value); premiseStr.append("=");
premiseStr.append(value);
}
}
public void appendKnowledge(StringBuffer knowledgeStr, String key, String value){
knowledgeStr.append("-<-"); public void appendKnowledge(StringBuffer knowledgeStr, String key, String value){
knowledgeStr.append(key); knowledgeStr.append("-<-");
knowledgeStr.append(":"); knowledgeStr.append(key);
knowledgeStr.append(value); knowledgeStr.append(":");
} knowledgeStr.append(value);
}
public void appendFeature(StringBuffer featureStr, String key){
featureStr.append(","); public void appendFeature(StringBuffer featureStr, String key){
featureStr.append(key); featureStr.append(",");
} featureStr.append(key);
}
/**
* 除了激活下一步剧情外,还可以同时激活其他地点的剧情,可以在剧情一开始就把ABC三个地点的剧情都激活,这样就不需要先玩完A,才能玩B /**
* 本方法的主要功能是修改剧情的状态,已知后台会存储剧情一些关于剧情的状态 * 除了激活下一步剧情外,还可以同时激活其他地点的剧情,可以在剧情一开始就把ABC三个地点的剧情都激活,这样就不需要先玩完A,才能玩B
* * TaskLine 某地点剧情进度 * 本方法的主要功能是修改剧情的状态,已知后台会存储剧情一些关于剧情的状态
* * TaskCondition 某地点剧情进度用到的condition * * TaskLine 某地点剧情进度
* * TaskReply 某地点剧情用到的文本 * * TaskCondition 某地点剧情进度用到的condition
* * 剧情(id)的状态:null标识未激活,1、 2表示激活 * * TaskReply 某地点剧情用到的文本
* 如果激活1-1,那么就是将剧情1-1的状态变为1,剧情所在地点的剧情进度更新为1-1,condition更新为1-1用到的condition * * 剧情(id)的状态:null标识未激活,1、 2表示激活
* @param updateKnowledge * 如果激活1-1,那么就是将剧情1-1的状态变为1,剧情所在地点的剧情进度更新为1-1,condition更新为1-1用到的condition
* @param nextPlotLocation * @param updateKnowledge
* @param activateExtraPlot 激活id列表 * @param nextPlotLocation
*/ * @param activateExtraPlot 激活id列表
public void extraActivatedPlot(StringBuffer updateKnowledge, String nextPlotLocation, Map activateExtraPlot){ */
JSONObject plot = null; public void extraActivatedPlot(StringBuffer updateKnowledge, String nextPlotLocation, Map activateExtraPlot){
String plotId = "", location = "", lastTaskCondition = "", lastTaskReply = "", plotText = "", conditionName = "", taskLine = ""; JSONObject plot = null;
StringBuffer newUK = updateKnowledge; String plotId = "", location = "", lastTaskCondition = "", lastTaskReply = "", plotText = "", conditionName = "", taskLine = "";
StringBuffer newUK = updateKnowledge;
Iterator<String> plotIter = activateExtraPlot.keySet().iterator();
Iterator<String> plotIter = activateExtraPlot.keySet().iterator();
while(plotIter.hasNext()){
plotId = plotIter.next(); while(plotIter.hasNext()){
plotText = (String)activateExtraPlot.get(plotId); plotId = plotIter.next();
plotText = (String)activateExtraPlot.get(plotId);
plot = plotIndex.get(plotId);
conditionName = plot.getString("conditionName"); plot = plotIndex.get(plotId);
conditionName = plot.getString("conditionName");
if(conditionName == null || conditionName.equals("")){
conditionName = DEFAULT_CONDITION; if(conditionName == null || conditionName.equals("")){
} conditionName = DEFAULT_CONDITION;
location = plot.getString("place"); }
location = plot.getString("place");
lastTaskCondition = String.format(TASK_CONDITION, location);
lastTaskReply = String.format(TASK_REPLY, location); lastTaskCondition = String.format(TASK_CONDITION, location);
taskLine = String.format(TASK_LINE, location); lastTaskReply = String.format(TASK_REPLY, location);
taskLine = String.format(TASK_LINE, location);
appendKnowledge(newUK, lastTaskCondition, conditionName);
appendKnowledge(newUK, lastTaskReply, plotText); appendKnowledge(newUK, lastTaskCondition, conditionName);
appendKnowledge(newUK, taskLine, String.format(GAME_STEP_FORMAT, botAccount, plotId)); appendKnowledge(newUK, lastTaskReply, plotText);
appendKnowledge(newUK, plotId, "1"); appendKnowledge(newUK, taskLine, String.format(GAME_STEP_FORMAT, botAccount, plotId));
appendKnowledge(newUK, plotId, "1");
}
} }
}
void plotEnQueue(Queue<JSONObject> queue, String parentId, String adjId, String nextUnknownText, Boolean thisAutoJump){
JSONObject adjNode; void plotEnQueue(Queue<JSONObject> queue, String parentId, String adjId, String nextUnknownText, Boolean thisAutoJump){
if (visited.get(adjId) == null && plotIndex.get(adjId) != null) { JSONObject adjNode;
visited.put(adjId, true); if (visited.get(adjId) == null && plotIndex.get(adjId) != null) {
adjNode = plotIndex.get(adjId); visited.put(adjId, true);
adjNode = plotIndex.get(adjId);
adjNode.put("parentId", parentId);
adjNode.put("prevAutoJump", thisAutoJump); adjNode.put("parentId", parentId);
queue.add(adjNode); adjNode.put("prevAutoJump", thisAutoJump);
} else { queue.add(adjNode);
conditionDescription.put(adjId, String.format(PLOT_STATUS, adjId)); } else {
varInitialMap.put(adjId, ""); conditionDescription.put(adjId, String.format(PLOT_STATUS, adjId));
} varInitialMap.put(adjId, "");
} }
}
/**
* 如果剧情1-1的地点是在沙滩,剧情1-2的地点实在营地,作者的游戏编辑平台里没有选中切换地点,那么就需要玩家一步一步地从沙滩走到营地(具体方法说“到xx,到营地”),然后才能开始1-2的剧情 /**
* 这个时候就需要一个中间结点,当玩家说到营地的时候,才会执行剧情状态的更新,并且回答1-2的剧情文本 * 如果剧情1-1的地点是在沙滩,剧情1-2的地点实在营地,作者的游戏编辑平台里没有选中切换地点,那么就需要玩家一步一步地从沙滩走到营地(具体方法说“到xx,到营地”),然后才能开始1-2的剧情
* 这块处理会被当做监听模块的一个剧情处理 * 这个时候就需要一个中间结点,当玩家说到营地的时候,才会执行剧情状态的更新,并且回答1-2的剧情文本
*/ * 这块处理会被当做监听模块的一个剧情处理
void arriveActivatePlot2(JSONObject gameElements, String plotId, String nextId, String nextLocation){ */
void arriveActivatePlot2(JSONObject gameElements, String plotId, String nextId, String nextLocation){
JSONObject updateKnowledge = new JSONObject();
JSONArray curPremiseList = new JSONArray(); JSONObject updateKnowledge = new JSONObject();
//curPremiseList.add(curPremise.toString()); JSONArray curPremiseList = new JSONArray();
//curPremiseList.add(curPremise.toString());
JSONArray hisPremiseList = new JSONArray();
//hisPremiseList.add(hisPremise.toString()); JSONArray hisPremiseList = new JSONArray();
//hisPremiseList.add(hisPremise.toString());
//激活下一步剧情的几个条件:1. condition 到沙滩 2. 沙滩_activate_by 沙滩的剧情是有当前剧情激活的 3. 沙滩的剧情处于等待激活的状态 4. 当前地点和沙滩地点相邻或可以直接到达
// 2.3 两个条件是特意加的 //激活下一步剧情的几个条件:1. condition 到沙滩 2. 沙滩_activate_by 沙滩的剧情是有当前剧情激活的 3. 沙滩的剧情处于等待激活的状态 4. 当前地点和沙滩地点相邻或可以直接到达
curPremiseList.add(new Premise(GOTO_CONDITION, "match", "Include", nextLocation)); // 2.3 两个条件是特意加的
hisPremiseList.add(new Premise(nextLocation + "_activate_by", "match", "Include", plotId)); curPremiseList.add(new Premise(GOTO_CONDITION, "match", "Include", nextLocation));
hisPremiseList.add(new Premise(nextLocation + "_activate_ready", "match", "Include", "1")); hisPremiseList.add(new Premise(nextLocation + "_activate_by", "match", "Include", plotId));
hisPremiseList.add(new Premise("isNeighbour:" + GOTO_CONDITION, "match", "Include", "1+3+4")); hisPremiseList.add(new Premise(nextLocation + "_activate_ready", "match", "Include", "1"));
hisPremiseList.add(new Premise("isNeighbour:" + GOTO_CONDITION, "match", "Include", "1+3+4"));
//无匹配次数清零
updateKnowledge.put(UNKNOWN_COUNTER_NAME, "0"); //无匹配次数清零
updateKnowledge.put(UNKNOWN_COUNTER_NAME, "0");
JSONObject listeningConfig = new JSONObject();
listeningConfig.put("curPremise", curPremiseList); JSONObject listeningConfig = new JSONObject();
listeningConfig.put("hisPremise", hisPremiseList); listeningConfig.put("curPremise", curPremiseList);
listeningConfig.put("updateKnowledge", updateKnowledge); listeningConfig.put("hisPremise", hisPremiseList);
listeningConfig.put("nextPlotId", nextId); listeningConfig.put("updateKnowledge", updateKnowledge);
listeningConfig.put("priority", "1"); //剧情优先级默认为1 listeningConfig.put("nextPlotId", nextId);
listeningConfig.put("priority", "1"); //剧情优先级默认为1
if(gameElements.getJSONArray("listeningActions") == null)
gameElements.put("listeningActions", new JSONArray()); if(gameElements.getJSONArray("listeningActions") == null)
gameElements.put("listeningActions", new JSONArray());
gameElements.getJSONArray("listeningActions").add(listeningConfig); //放到监听剧情列表
gameElements.getJSONArray("listeningActions").add(listeningConfig); //放到监听剧情列表
}
}
/**
* 判断是否满足激活下一部剧情的条件 /**
* 如果下一步剧情是自动跳转,并且(当前剧情和下一部剧情地点相同或者用户选中了自动切换地点),就为真 * 判断是否满足激活下一部剧情的条件
* @param nextAutoJump * 如果下一步剧情是自动跳转,并且(当前剧情和下一部剧情地点相同或者用户选中了自动切换地点),就为真
* @param location * @param nextAutoJump
* @param nextLocation * @param location
* @param moveWithPlot * @param nextLocation
* @return * @param moveWithPlot
*/ * @return
Boolean doActivatePlot(Boolean nextAutoJump, String location, String nextLocation, Boolean moveWithPlot) { */
Boolean doActivatePlot(Boolean nextAutoJump, String location, String nextLocation, Boolean moveWithPlot) {
return nextAutoJump && (location.equals(nextLocation) || moveWithPlot);
} return nextAutoJump && (location.equals(nextLocation) || moveWithPlot);
}
// public void premiseTextFilt(JSONArray premiseList){
// int size = premiseList.size(); // public void premiseTextFilt(JSONArray premiseList){
// JSONObject premise = null; // int size = premiseList.size();
// // JSONObject premise = null;
// for(int i = 0;i < size;i++){ //
// premise = premiseList.getJSONObject(i); // for(int i = 0;i < size;i++){
// // premise = premiseList.getJSONObject(i);
// premise.put("keyword", textReplace(premise.getString("keyword"), replaceMap)); //
// } // premise.put("keyword", textReplace(premise.getString("keyword"), replaceMap));
// } // }
// }
/**
* @param term 原始的配置数据 /**
* @return 生成的用于QA的配置 * @param term 原始的配置数据
*/ * @return 生成的用于QA的配置
private ConfigTermText alterTerm(ConfigTermText term) { */
ConfigTermText newTerm = (ConfigTermText)term.clone(); private ConfigTermText alterTerm(ConfigTermText term) {
newTerm.setUpdateKnowledge(""); ConfigTermText newTerm = (ConfigTermText)term.clone();
String stemStr = newTerm.getConfigName(); newTerm.setUpdateKnowledge("");
String feature = newTerm.getFeature(); String stemStr = newTerm.getConfigName();
feature = feature + ",activate,post::gameQA(" + QA_URL + ")"; String feature = newTerm.getFeature();
newTerm.setFeature(feature); feature = feature + ",activate,post::gameQA(" + QA_URL + ")";
newTerm.setNextStep(stemStr+"_qa1,"+stemStr+"_qa2"); newTerm.setFeature(feature);
return newTerm; newTerm.setNextStep(stemStr+"_qa1,"+stemStr+"_qa2");
} return newTerm;
}
private ConfigTermText createTermExtra1(ConfigTermText term) {
String hPremise = "qa_score::number-Bigger=90"; private ConfigTermText createTermExtra1(ConfigTermText term) {
String featureStr = "match,activate,return-0"; String hPremise = "qa_score::number-Bigger=90";
String nextStr = "map*,item*,npc*"; String featureStr = "match,activate,return-0";
String knowledgeStr = UNKNOWN_COUNTER_NAME+":+1"; String nextStr = "map*,item*,npc*";
String configName = term.getConfigName()+"_qa1"; String knowledgeStr = UNKNOWN_COUNTER_NAME+":+1";
ConfigTermText newTerm = new ConfigTermText(" ", hPremise, featureStr, "", nextStr, knowledgeStr); String configName = term.getConfigName()+"_qa1";
newTerm.setConfigName(configName, false); ConfigTermText newTerm = new ConfigTermText(" ", hPremise, featureStr, "", nextStr, knowledgeStr);
newTerm.setStatus("sleeping"); newTerm.setConfigName(configName, false);
return newTerm; newTerm.setStatus("sleeping");
} return newTerm;
}
private ConfigTermText createTermExtra2(ConfigTermText term) {
String hPremise = "qa_score::number-Smaller=90"; private ConfigTermText createTermExtra2(ConfigTermText term) {
String featureStr = "match,activate"; String hPremise = "qa_score::number-Smaller=90";
String nextStr = "map*,item*,npc*"; String featureStr = "match,activate";
String configName = term.getConfigName()+"_qa2"; String nextStr = "map*,item*,npc*";
if(term.getFeature().indexOf("activate") != -1) { String configName = term.getConfigName()+"_qa2";
nextStr = term.getNextStep() + "," + nextStr; if(term.getFeature().indexOf("activate") != -1) {
} nextStr = term.getNextStep() + "," + nextStr;
ConfigTermText newTerm = (ConfigTermText)term.clone(); }
newTerm.setHisPremise(hPremise); ConfigTermText newTerm = (ConfigTermText)term.clone();
newTerm.setConfigName(configName, false); newTerm.setHisPremise(hPremise);
newTerm.setFeature(featureStr); newTerm.setConfigName(configName, false);
newTerm.setNextStep(nextStr); newTerm.setFeature(featureStr);
newTerm.setStatus("sleeping"); newTerm.setNextStep(nextStr);
return newTerm; newTerm.setStatus("sleeping");
} return newTerm;
}
}
}
package com.qiwu.chatbotbackend.task.utils; package com.qiwu.chatbotbackend.task.utils;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; import com.qiwu.chatbotbackend.GameEnvironment.GameEnv;
import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.db.SqlHelper;
import com.qiwu.chatbotbackend.entity.*; import com.qiwu.chatbotbackend.entity.*;
import com.qiwu.chatbotbackend.processing.ChatCacheController; import com.qiwu.chatbotbackend.processing.ChatCacheController;
import com.qiwu.chatbotbackend.processing.LogWriter; import com.qiwu.chatbotbackend.processing.LogWriter;
import com.qiwu.chatbotbackend.processing.SimpleUtil; import com.qiwu.chatbotbackend.processing.SimpleUtil;
import com.qiwu.chatbotbackend.processing.WorldController; import com.qiwu.chatbotbackend.processing.WorldController;
import javax.servlet.ServletContext; import javax.servlet.ServletContext;
import java.io.IOException; import java.io.IOException;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.*; import java.util.*;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import static com.qiwu.chatbotbackend.Config.Config.*; import static com.qiwu.chatbotbackend.Config.Config.*;
import static com.qiwu.chatbotbackend.processing.FormsPoster.TALKER; import static com.qiwu.chatbotbackend.processing.FormsPoster.TALKER;
public class GameBotUtil extends BasicBotUtil{ public class GameBotUtil extends BasicBotUtil{
WorldController worldController = null; WorldController worldController = null;
public static String LOAD_BY_SITE_CONDITION = "load_game_by_site"; public static String LOAD_BY_SITE_CONDITION = "load_game_by_site";
public static String LOAD_BY_LAST = "load_last"; public static String LOAD_BY_LAST = "load_last";
public GameBotUtil(Map<String, String> curInfoPoint, ChatCache chatCache, UserInfo userinfo, LogWriter logWriter, WorldController worldController){ public GameBotUtil(Map<String, String> curInfoPoint, ChatCache chatCache, UserInfo userinfo, LogWriter logWriter, WorldController worldController){
super(curInfoPoint, chatCache, userinfo, logWriter); super(curInfoPoint, chatCache, userinfo, logWriter);
this.worldController = worldController; this.worldController = worldController;
this.botType = "game"; this.botType = "game";
} }
/** /**
* 对表单数据做预处理 * 对表单数据做预处理
* @param receiveParameters * @param receiveParameters
* @param context * @param context
* @return * @return
* @throws IOException * @throws IOException
*/ */
@Override @Override
public boolean preprocessing(Map<String, String[]> receiveParameters, ServletContext context) throws IOException { public boolean preprocessing(Map<String, String[]> receiveParameters, ServletContext context) throws IOException {
Boolean debugFlag = super.infoPointPreprocessing(receiveParameters, context, false); Boolean debugFlag = super.infoPointPreprocessing(receiveParameters, context, false);
//将要去的地点的别名替换为真名 //将要去的地点的别名替换为真名
// String conditionList[] = {"yaobuyao", "want_know_zenmezuo"}; // String conditionList[] = {"yaobuyao", "want_know_zenmezuo"};
// //
// for(String conditionName: conditionList) { // for(String conditionName: conditionList) {
// //
// if (!curInfoPoint.get(conditionName).equals("") && !curInfoPoint.get(conditionName).equals("unknown")) { // if (!curInfoPoint.get(conditionName).equals("") && !curInfoPoint.get(conditionName).equals("unknown")) {
// String info = curInfoPoint.get(conditionName), newInfo = curInfoPoint.get(conditionName); // String info = curInfoPoint.get(conditionName), newInfo = curInfoPoint.get(conditionName);
// String destination = info.split(":")[1]; // String destination = info.split(":")[1];
// String site = historyInfoPoint.get("site"); // String site = historyInfoPoint.get("site");
// try { // try {
// newInfo = info.replace(destination, worldController.findLocationName(gameEnv, destination, site)); // newInfo = info.replace(destination, worldController.findLocationName(gameEnv, destination, site));
// }catch(Exception e){ // }catch(Exception e){
// e.printStackTrace(); // e.printStackTrace();
// } // }
// //
// logWriter.record(conditionName + ": 将’" + info + "‘替换为‘" + newInfo + "'", 1); // logWriter.record(conditionName + ": 将’" + info + "‘替换为‘" + newInfo + "'", 1);
// curInfoPoint.put(conditionName, newInfo); // curInfoPoint.put(conditionName, newInfo);
// } // }
// } // }
// historyInfoPoint.put("current_plot_site", historyInfoPoint.get("site")); // historyInfoPoint.put("current_plot_site", historyInfoPoint.get("site"));
//将上一轮使用的nextStep(condition)放在临时变量中 //将上一轮使用的nextStep(condition)放在临时变量中
String activeList[] = chatCache.getInfoPoint().get("activeList").split("\\|"); String activeList[] = chatCache.getInfoPoint().get("activeList").split("\\|");
if(activeList.length == 0){ if(activeList.length == 0){
chatCache.getInfoPoint().put("临时变量condition", "yaobuyao"); chatCache.getInfoPoint().put("临时变量condition", DEFAULT_CONDITION);
}else { }else {
chatCache.getInfoPoint().put("临时变量condition", activeList[activeList.length-1]); chatCache.getInfoPoint().put("临时变量condition", activeList[activeList.length-1]);
} }
int randomNumber = (int)(Math.random() * 10000); int randomNumber = (int)(Math.random() * 10000);
chatCache.getInfoPoint().put(PLOT_RANDOM_NUM, String.valueOf(randomNumber)); chatCache.getInfoPoint().put(PLOT_RANDOM_NUM, String.valueOf(randomNumber));
return debugFlag; return debugFlag;
} }
@Override @Override
public boolean postprocessing(String chatKey, ServletContext context, Solution bestMatch){ public boolean postprocessing(String chatKey, ServletContext context, Solution bestMatch){
StringBuffer finalText = new StringBuffer(); StringBuffer finalText = new StringBuffer();
String plotText = SimpleUtil.randStr(bestMatch.getAnswer().split("~")); String plotText = SimpleUtil.randStr(bestMatch.getAnswer().split("~"));
//将自动跳转文本、qa文本、查询文本拼接 //将自动跳转文本、qa文本、查询文本拼接
String queryList[] = {"common_answer", "plot_jump_text", "map_query", "goods_query", "npc_query", "plot_text", "error_message"}; String queryList[] = {"common_answer", "plot_jump_text", "map_query", "goods_query", "npc_query", "plot_text", "error_message"};
String queryResult; String queryResult;
//有些特殊文本在开头是不加npc名字和情绪的 //有些特殊文本在开头是不加npc名字和情绪的
Set<String> keepNoSpeaker = new HashSet<String>(){ Set<String> keepNoSpeaker = new HashSet<String>(){
{ {
add("sendData:archiveList"); add("sendData:archiveList");
add(GAME_START_HINT); add(GAME_START_HINT);
} }
}; };
chatCache.getInfoPoint().put("plot_text", plotText); chatCache.getInfoPoint().put("plot_text", plotText);
//整合qa问答、地图、npc查询文本和剧情文本 //整合qa问答、地图、npc查询文本和剧情文本
for(String queryName:queryList){ for(String queryName:queryList){
queryResult = chatCache.getInfoPoint().get(queryName); queryResult = chatCache.getInfoPoint().get(queryName);
if(queryResult != null){ if(queryResult != null){
if(queryResult.equals("") && !queryName.equals(queryList[queryList.length-2])){ //不为剧情文本 if(queryResult.equals("") && !queryName.equals(queryList[queryList.length-2])){ //不为剧情文本
//剧情可以为空,其他不行 //剧情可以为空,其他不行
continue; continue;
} }
switch (queryName){ switch (queryName){
case "common_answer": case "common_answer":
//qa返回结果不为No answer,就添加到回答文本 //qa返回结果不为No answer,就添加到回答文本
if(!queryResult.equals("no answer")) if(!queryResult.equals("no answer"))
finalText.append(queryResult); finalText.append(queryResult);
break; break;
case "plot_jump_text": case "plot_jump_text":
//添加剧情自动跳转文本 //添加剧情自动跳转文本
finalText.append(queryResult); finalText.append(queryResult);
break; break;
case "map_query": case "map_query":
case "goods_query": case "goods_query":
case "npc_query": case "npc_query":
case "error_message": case "error_message":
//这四类文本(查询+错误信息)都是动态生成的,没有npc和情绪信息,所以需要添加npc和情绪 //这四类文本(查询+错误信息)都是动态生成的,没有npc和情绪信息,所以需要添加npc和情绪
queryResult = appendTalker(findRelateTalkers(false).get(0), queryResult, chatCache.getInfoPoint(), chatCache.getGameEnv()); queryResult = appendTalker(findRelateTalkers(false).get(0), queryResult, chatCache.getInfoPoint(), chatCache.getGameEnv());
finalText.append(queryResult); finalText.append(queryResult);
break; break;
case "plot_text": case "plot_text":
//有以下剧情文本是 //有以下剧情文本是
if(keepNoSpeaker.contains(plotText)){ //不需要添加人名和情绪 if(keepNoSpeaker.contains(plotText)){ //不需要添加人名和情绪
finalText.setLength(0); finalText.setLength(0);
finalText.append(plotText); finalText.append(plotText);
} }
//文本为空跳过 //文本为空跳过
else if(plotText.equals("") && finalText.length() != 0){ else if(plotText.equals("") && finalText.length() != 0){
continue; continue;
}else { }else {
//对剧情文本做处理,或者说对unknown文本做处理 //对剧情文本做处理,或者说对unknown文本做处理
finalText.append(plotTextFilt(plotText)); finalText.append(plotTextFilt(plotText));
} }
break; break;
} }
chatCache.getInfoPoint().put(queryName, ""); chatCache.getInfoPoint().put(queryName, "");
} }
} }
bestMatch.setAnswer(finalText.toString()); bestMatch.setAnswer(finalText.toString());
return true; return true;
} }
@Override @Override
public String getKeyword(Map<String, String> infoPoint, Map<String, String> infoPoint2, Boolean chooseLater, String actionName){ public String getKeyword(Map<String, String> infoPoint, Map<String, String> infoPoint2, Boolean chooseLater, String actionName){
String keyword = ""; String keyword = "";
String nameSeries[] = actionName.split("_"); String nameSeries[] = actionName.split("_");
//变量名以npc_开头,就从游戏环境中查询相应的值 //变量名以npc_开头,就从游戏环境中查询相应的值
if(actionName.startsWith("npc_")){ if(actionName.startsWith("npc_")){
if(nameSeries.length == 4){ if(nameSeries.length == 4){
keyword = chatCache.getGameEnv().queryNpcAttrByNpcName(nameSeries[2], nameSeries[3]); keyword = chatCache.getGameEnv().queryNpcAttrByNpcName(nameSeries[2], nameSeries[3]);
}else if (nameSeries.length == 3){ }else if (nameSeries.length == 3){
if(nameSeries[2].equals("物品栏")) { if(nameSeries[2].equals("物品栏")) {
//如果是物品栏就调用专门的函数查询物品栏的所有数据 //如果是物品栏就调用专门的函数查询物品栏的所有数据
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
List<String> goods = chatCache.getGameEnv().queryGoodsByNpcName(nameSeries[1]); List<String> goods = chatCache.getGameEnv().queryGoodsByNpcName(nameSeries[1]);
for (String good : goods) { for (String good : goods) {
sb.append("+").append(good); sb.append("+").append(good);
} }
keyword = sb.toString(); keyword = sb.toString();
}else{ }else{
keyword = chatCache.getGameEnv().queryNpcAttrByNpcName(nameSeries[1], nameSeries[2]); keyword = chatCache.getGameEnv().queryNpcAttrByNpcName(nameSeries[1], nameSeries[2]);
} }
} }
}else if (actionName.startsWith("goods_")) { }else if (actionName.startsWith("goods_")) {
if(nameSeries.length == 3) { if(nameSeries.length == 3) {
nameSeries[2] = nameSeries[2].replace("所属角色", "owner"); nameSeries[2] = nameSeries[2].replace("所属角色", "owner");
keyword = chatCache.getGameEnv().queryGoodsAttrByGoodsName(nameSeries[1], nameSeries[2]); keyword = chatCache.getGameEnv().queryGoodsAttrByGoodsName(nameSeries[1], nameSeries[2]);
} }
//System.out.println("return" + keyword); //System.out.println("return" + keyword);
}else if(actionName.startsWith("isNeighbour")){ }else if(actionName.startsWith("isNeighbour")){
String opPair[] = actionName.split(":"); String opPair[] = actionName.split(":");
if(!curInfoPoint.containsKey(opPair[1]) || curInfoPoint.get(opPair[1]).equals("unknown") || curInfoPoint.get(opPair[1]).equals("")){ if(!curInfoPoint.containsKey(opPair[1]) || curInfoPoint.get(opPair[1]).equals("unknown") || curInfoPoint.get(opPair[1]).equals("")){
keyword = "not_exist"; keyword = "not_exist";
}else { }else {
logWriter.record("isNeighbour(" + chatCache.getInfoPoint().get("site") + "," + curInfoPoint.get(opPair[1]).split(":")[1] + ")", 1); logWriter.record("isNeighbour(" + chatCache.getInfoPoint().get("site") + "," + curInfoPoint.get(opPair[1]).split(":")[1] + ")", 1);
keyword = String.valueOf(chatCache.getGameEnv().isNeighbour(chatCache.getInfoPoint().get("site"), curInfoPoint.get(opPair[1]).split(":")[1])); keyword = String.valueOf(chatCache.getGameEnv().isNeighbour(chatCache.getInfoPoint().get("site"), curInfoPoint.get(opPair[1]).split(":")[1]));
logWriter.record("返回:" + keyword, 1); logWriter.record("返回:" + keyword, 1);
} }
}else { }else {
/** /**
* 如果chooseLater为真,则先提取infoPint2中的关键字,如果infoPoint2中不存在,再提取infoPoint中的关键字 * 如果chooseLater为真,则先提取infoPint2中的关键字,如果infoPoint2中不存在,再提取infoPoint中的关键字
*/ */
if(chooseLater){ if(chooseLater){
keyword = infoPoint2.get(actionName); keyword = infoPoint2.get(actionName);
if(keyword != null && !keyword.equals("")) if(keyword != null && !keyword.equals(""))
return keyword; return keyword;
} }
keyword = infoPoint.get(actionName); keyword = infoPoint.get(actionName);
} }
if(keyword == null) if(keyword == null)
keyword = ""; keyword = "";
return keyword; return keyword;
}; };
@Override @Override
public void putKeyword(String variableName, String updateValue){ public void putKeyword(String variableName, String updateValue){
String namePair[] = variableName.split("_"); String namePair[] = variableName.split("_");
//如果变量名开头为NPC或者item,就专门交给游戏环境处理 //如果变量名开头为NPC或者item,就专门交给游戏环境处理
if ((namePair[0].equals("npc") || namePair[0].equals("goods") || namePair[0].equals("map") || namePair[0].equals("place"))) { if ((namePair[0].equals("npc") || namePair[0].equals("goods") || namePair[0].equals("map") || namePair[0].equals("place"))) {
try { try {
if (!updateValue.startsWith("query") && !updateValue.startsWith("update")) { if (!updateValue.startsWith("query") && !updateValue.startsWith("update")) {
updateValue = "update:" + updateValue; updateValue = "update:" + updateValue;
} }
variableName = variableName.replace("所属玩家", "owner"); variableName = variableName.replace("所属玩家", "owner");
String returnStr = worldController.worldOperation(chatCache.getGameEnv(), variableName, updateValue, curInfoPoint, chatCache.getInfoPoint()); String returnStr = worldController.worldOperation(chatCache.getGameEnv(), variableName, updateValue, curInfoPoint, chatCache.getInfoPoint());
updateValue = returnStr; updateValue = returnStr;
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
updateValue = GAME_MODULE_ERROR; updateValue = GAME_MODULE_ERROR;
} }
} }
chatCache.getInfoPoint().put(variableName, updateValue); chatCache.getInfoPoint().put(variableName, updateValue);
} }
public String knowledgeProcess(String variableName, String updateValue){ public String knowledgeProcess(String variableName, String updateValue){
String values[] = updateValue.split(":",2), returnValue; String values[] = updateValue.split(":",2), returnValue;
if(values.length > 1 && values[0].equals("update")) if(values.length > 1 && values[0].equals("update"))
returnValue = values[1]; returnValue = values[1];
else else
returnValue = updateValue; returnValue = updateValue;
return returnValue; return returnValue;
} }
/** /**
* 主要用于游戏存档和读档 * 主要用于游戏存档和读档
* @param ansAction * @param ansAction
* @param solution * @param solution
* @throws IOException * @throws IOException
*/ */
@Override @Override
public void extraOperation(Action ansAction, Solution solution) throws IOException { public void extraOperation(Action ansAction, Solution solution) throws IOException {
Boolean flag = true; Boolean flag = true;
String userKey = curInfoPoint.get("userKey"); String userKey = curInfoPoint.get("userKey");
String randKey = curInfoPoint.get("randKey"); String randKey = curInfoPoint.get("randKey");
String keyword = "", site; String keyword = "", site;
SqlHelper helper = null; SqlHelper helper = null;
ChatCache chatCache = null; ChatCache chatCache = null;
try { try {
helper = new SqlHelper(); helper = new SqlHelper();
//未登录用户没有存取档的操作 //未登录用户没有存取档的操作
if(userKey.equals(randKey)) if(userKey.equals(randKey))
return; return;
if(ansAction.getFeatureMap().containsKey("newGame")) { if(ansAction.getFeatureMap().containsKey("newGame")) {
System.out.println("newGame"); System.out.println("newGame");
this.chatCache.setGameStart(true); this.chatCache.setGameStart(true);
}else if (ansAction.getFeatureMap().containsKey("gameBackup")) { }else if (ansAction.getFeatureMap().containsKey("gameBackup")) {
System.out.println("gameBackup"); System.out.println("gameBackup");
chatCache = new ChatCache(userKey, randKey, chatCache.getGameEnv(), chatCache.getInfoPoint()); chatCache = new ChatCache(userKey, randKey, chatCache.getGameEnv(), chatCache.getInfoPoint());
flag = ChatCacheController.saveChatCache(chatCache, null); flag = ChatCacheController.saveChatCache(chatCache, null);
if(flag) if(flag)
solution.setAnswer(String.format(TALKER_PATTERN, chatCache.getInfoPoint().get(ASSISTANT), ASSISTANT_EMOTION) + "存档成功"); solution.setAnswer(String.format(TALKER_PATTERN, chatCache.getInfoPoint().get(ASSISTANT), ASSISTANT_EMOTION) + "存档成功");
else else
solution.setAnswer(String.format(TALKER_PATTERN, chatCache.getInfoPoint().get(ASSISTANT), ASSISTANT_EMOTION) + "存档失败"); solution.setAnswer(String.format(TALKER_PATTERN, chatCache.getInfoPoint().get(ASSISTANT), ASSISTANT_EMOTION) + "存档失败");
} else if (ansAction.getFeatureMap().containsKey("loadLastArchive")) { } else if (ansAction.getFeatureMap().containsKey("loadLastArchive")) {
System.out.println("loadLastArchive"); System.out.println("loadLastArchive");
ArchiveInfo archiveInfo = helper.queryUserLastGameArchive(userKey); ArchiveInfo archiveInfo = helper.queryUserLastGameArchive(userKey);
if(archiveInfo != null){ if(archiveInfo != null){
System.out.println("存档Id" + archiveInfo.getArchiveId()); System.out.println("存档Id" + archiveInfo.getArchiveId());
}else{ }else{
System.out.println("没有找到存档"); System.out.println("没有找到存档");
} }
loading(archiveInfo, solution); loading(archiveInfo, solution);
this.chatCache.setGameStart(true); this.chatCache.setGameStart(true);
} else if (ansAction.getFeatureMap().containsKey("loadArchiveBySite")) { } else if (ansAction.getFeatureMap().containsKey("loadArchiveBySite")) {
System.out.println("loadArchiveBySite"); System.out.println("loadArchiveBySite");
if (curInfoPoint.get(LOAD_BY_SITE_CONDITION) != null) { if (curInfoPoint.get(LOAD_BY_SITE_CONDITION) != null) {
site = curInfoPoint.get(LOAD_BY_SITE_CONDITION).split(":")[1]; site = curInfoPoint.get(LOAD_BY_SITE_CONDITION).split(":")[1];
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); this.chatCache.setGameStart(true);
}else{ }else{
System.out.println("没有识别到" + LOAD_BY_SITE_CONDITION); System.out.println("没有识别到" + LOAD_BY_SITE_CONDITION);
} }
} else if(ansAction.getFeatureMap().containsKey("sendArchiveList")){ } else if(ansAction.getFeatureMap().containsKey("sendArchiveList")){
System.out.println("sendArchiveList"); System.out.println("sendArchiveList");
DataDeliver dataDeliver = new DataDeliver(); DataDeliver dataDeliver = new DataDeliver();
JSONObject data = new JSONObject(); JSONObject data = new JSONObject();
List<ArchiveInfo> archiveList = helper.queryArchiveByUserKey(userKey); List<ArchiveInfo> archiveList = helper.queryArchiveByUserKey(userKey);
data.put("data", JSONObject.toJSON(archiveList)); data.put("data", JSONObject.toJSON(archiveList));
data.put("dataType", "archiveList"); data.put("dataType", "archiveList");
data.put("userKey", userKey); data.put("userKey", userKey);
dataDeliver.setData(data); dataDeliver.setData(data);
dataDeliver.start(); dataDeliver.start();
solution.setAnswer("sendData:archiveList:"); //两个冒号,取第二个 solution.setAnswer("sendData:archiveList:"); //两个冒号,取第二个
} }
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally{ } finally{
helper.destroy(); helper.destroy();
} }
} }
private void loading(ArchiveInfo archiveInfo, Solution solution) throws Exception { private void loading(ArchiveInfo archiveInfo, Solution solution) throws Exception {
String keyword = "", site; String keyword = "", site;
ChatCache loadCache = null; ChatCache loadCache = null;
if (archiveInfo != null) { if (archiveInfo != null) {
//如果存在读档,就要将自动跳转和qa的临时数据清空 //如果存在读档,就要将自动跳转和qa的临时数据清空
chatCache.getInfoPoint().put("plot_jump_text", ""); chatCache.getInfoPoint().put("plot_jump_text", "");
chatCache.getInfoPoint().put("common_answer", ""); chatCache.getInfoPoint().put("common_answer", "");
loadCache = ChatCacheController.loadChatCache(archiveInfo); loadCache = ChatCacheController.loadChatCache(archiveInfo);
//this.chatCache = new ChatCache(this.chatCache.getUserKey(), this.chatCache.getRandKey(), loadCache.getGameEnv(), loadCache.getInfoPoint()); //this.chatCache = new ChatCache(this.chatCache.getUserKey(), this.chatCache.getRandKey(), loadCache.getGameEnv(), loadCache.getInfoPoint());
this.chatCache.setInfoPoint(loadCache.getInfoPoint()); this.chatCache.setInfoPoint(loadCache.getInfoPoint());
this.chatCache.setGameEnv(loadCache.getGameEnv()); this.chatCache.setGameEnv(loadCache.getGameEnv());
System.out.println("----------读档中------------"); System.out.println("----------读档中------------");
site = loadCache.getInfoPoint().get("site"); site = loadCache.getInfoPoint().get("site");
String nextStep = loadCache.getInfoPoint().get(String.format(TASK_CONDITION, site)); String nextStep = loadCache.getInfoPoint().get(String.format(TASK_CONDITION, site));
String reply = loadCache.getInfoPoint().get(String.format(TASK_REPLY, site)); String reply = loadCache.getInfoPoint().get(String.format(TASK_REPLY, site));
solution.setAnswer(reply); solution.setAnswer(reply);
solution.setNext("nextStep=" + nextStep); solution.setNext("nextStep=" + nextStep);
this.chatCache.setReload(true); this.chatCache.setReload(true);
}else{ }else{
System.out.println("没有找到该存档"); System.out.println("没有找到该存档");
} }
} }
//将文本中存在的变量槽位{npc_xxx}替换成变量值,游戏专用版 //将文本中存在的变量槽位{npc_xxx}替换成变量值,游戏专用版
//@Override //@Override
public String varSlotReplace2(String text){ public String varSlotReplace2(String text){
String VARIABLE_REPLACE_PATTERN = "\\$\\{(.*?)}"; String VARIABLE_REPLACE_PATTERN = "\\$\\{(.*?)}";
Pattern replacePattern = Pattern.compile(VARIABLE_REPLACE_PATTERN); Pattern replacePattern = Pattern.compile(VARIABLE_REPLACE_PATTERN);
String varElements[] = {}, result = ""; String varElements[] = {}, result = "";
String keyword, variable, variableSlot, reply = text; String keyword, variable, variableSlot, reply = text;
Matcher m = replacePattern.matcher(reply); Matcher m = replacePattern.matcher(reply);
while (m.find()) { while (m.find()) {
variable = m.group(1); variable = m.group(1);
varElements = variable.split("_"); varElements = variable.split("_");
variableSlot = "${" + variable + "}"; variableSlot = "${" + variable + "}";
switch (varElements[0]){ switch (varElements[0]){
//如果以npc、goods、map开头,就要从游戏环境里查询出它的值,然后做替换。 //如果以npc、goods、map开头,就要从游戏环境里查询出它的值,然后做替换。
case "globalVariable": case "globalVariable":
reply = reply.replace(variableSlot, chatCache.getInfoPoint().get(variable)); reply = reply.replace(variableSlot, chatCache.getInfoPoint().get(variable));
case "npc": case "npc":
result = chatCache.getGameEnv().queryNpcAttrByNpcName(varElements[1], varElements[2]); result = chatCache.getGameEnv().queryNpcAttrByNpcName(varElements[1], varElements[2]);
reply = reply.replace(variableSlot, result); reply = reply.replace(variableSlot, result);
case "goods": case "goods":
result = chatCache.getGameEnv().queryGoodsAttrByGoodsName(varElements[1], varElements[2]); result = chatCache.getGameEnv().queryGoodsAttrByGoodsName(varElements[1], varElements[2]);
reply = reply.replace(variableSlot, result); reply = reply.replace(variableSlot, result);
case "map": case "map":
System.out.println("地图替换还没写"); System.out.println("地图替换还没写");
default: default:
if(curInfoPoint.get(variable) != null && !curInfoPoint.get(variable).equals("")){ if(curInfoPoint.get(variable) != null && !curInfoPoint.get(variable).equals("")){
reply = reply.replace(variableSlot, curInfoPoint.get(variable)); reply = reply.replace(variableSlot, curInfoPoint.get(variable));
}else if(chatCache.getInfoPoint().get(variable) != null && !chatCache.getInfoPoint().get(variable).equals("")){ }else if(chatCache.getInfoPoint().get(variable) != null && !chatCache.getInfoPoint().get(variable).equals("")){
reply = reply.replace(variableSlot, chatCache.getInfoPoint().get(variable)); reply = reply.replace(variableSlot, chatCache.getInfoPoint().get(variable));
} }
} }
} }
return reply; return reply;
} }
public static Matcher findTalker(String reply){ public static Matcher findTalker(String reply){
System.out.println(reply); System.out.println(reply);
Pattern findTalker = Pattern.compile(TALKER); Pattern findTalker = Pattern.compile(TALKER);
Matcher m = findTalker.matcher(reply); Matcher m = findTalker.matcher(reply);
return m; return m;
} }
static String findFirstTalker(String reply){ static String findFirstTalker(String reply){
String npc = ""; String npc = "";
Pattern findTalker = Pattern.compile(TALKER); Pattern findTalker = Pattern.compile(TALKER);
Matcher m = findTalker.matcher(reply); Matcher m = findTalker.matcher(reply);
if(m.find()) { if(m.find()) {
npc = m.group(1); npc = m.group(1);
} }
return npc; return npc;
} }
/** /**
* 查看回答文本的说话这是否在当前地点 * 查看回答文本的说话这是否在当前地点
* 0:没有说话者 * 0:没有说话者
* 1:说话者在当前地点 * 1:说话者在当前地点
* 2:说话者不在当前地点或者不能说话 * 2:说话者不在当前地点或者不能说话
* @param reply * @param reply
* @param curInfoPoint * @param curInfoPoint
* @param historyInfoPoint * @param historyInfoPoint
* @param gameEnv * @param gameEnv
* @param site * @param site
* @param logWriter * @param logWriter
* @return * @return
*/ */
public static Integer sameLocation(String reply, Map<String ,String> curInfoPoint, Map<String ,String> historyInfoPoint, GameEnv gameEnv, String site, LogWriter logWriter){ public static Integer sameLocation(String reply, Map<String ,String> curInfoPoint, Map<String ,String> historyInfoPoint, GameEnv gameEnv, String site, LogWriter logWriter){
String npc, location; String npc, location;
Matcher m = findTalker(reply); Matcher m = findTalker(reply);
int flag = 1; int flag = 1;
if(m.find()) { if(m.find()) {
npc = m.group(1); npc = m.group(1);
location = gameEnv.queryNpcAttrByNpcName(npc, "location"); location = gameEnv.queryNpcAttrByNpcName(npc, "location");
System.out.println("location:" + location + ", npc:" + npc); System.out.println("location:" + location + ", npc:" + npc);
if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){ if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){
if(gameEnv.queryNpcAttrByNpcName(npc, "能否说话") == null || gameEnv.queryNpcAttrByNpcName(npc, "能否说话").equals("能")){ if(gameEnv.queryNpcAttrByNpcName(npc, "能否说话") == null || gameEnv.queryNpcAttrByNpcName(npc, "能否说话").equals("能")){
flag = 1; flag = 1;
logWriter.record("\"" + reply + "\":匹配", 1); logWriter.record("\"" + reply + "\":匹配", 1);
}else { }else {
flag = 2; flag = 2;
logWriter.record(npc + "不能说话", 1); logWriter.record(npc + "不能说话", 1);
} }
}else { }else {
logWriter.record("\"" + reply + "\":" + npc +"不在" + site + ",跳过",1 ); logWriter.record("\"" + reply + "\":" + npc +"不在" + site + ",跳过",1 );
flag = 2; flag = 2;
} }
}else{ }else{
logWriter.record("\"" + reply + "\":没有npc名",1 ); logWriter.record("\"" + reply + "\":没有npc名",1 );
flag = 0; flag = 0;
} }
return flag; return flag;
} }
/** /**
* 查看回答文本的说话这是否在当前地点 * 查看回答文本的说话这是否在当前地点
* 0:没有说话者 * 0:没有说话者
* 1:说话者在当前地点 * 1:说话者在当前地点
* 2:说话者不在当前地点或者不能说话 * 2:说话者不在当前地点或者不能说话
* @param npc * @param npc
* @param site * @param site
* @param onlineDetect npc是在线类型才可以通过 * @param onlineDetect npc是在线类型才可以通过
* @return * @return
*/ */
public Boolean canTalk(String npc, String site, Boolean onlineDetect){ public Boolean canTalk(String npc, String site, Boolean onlineDetect){
String location; String location;
Boolean flag = false; Boolean flag = false;
location = chatCache.getGameEnv().queryNpcAttrByNpcName(npc, "location"); location = chatCache.getGameEnv().queryNpcAttrByNpcName(npc, "location");
if( location == null){ if( location == null){
return false; return false;
} }
if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){ if (location.equals(site) || location.equals("无处不在") || location.equals("任意地点")){
if(chatCache.getGameEnv().queryNpcAttrByNpcName(npc, "能否说话") == null || chatCache.getGameEnv().queryNpcAttrByNpcName(npc, "能否说话").equals("能")){ if(chatCache.getGameEnv().queryNpcAttrByNpcName(npc, "能否说话") == null || chatCache.getGameEnv().queryNpcAttrByNpcName(npc, "能否说话").equals("能")){
if(onlineDetect){ if(onlineDetect){
if(isOnlineMode(npc, chatCache.getInfoPoint())){ if(isOnlineMode(npc, chatCache.getInfoPoint())){
logWriter.record("\"" + npc + "\":匹配", 1); logWriter.record("\"" + npc + "\":匹配", 1);
flag = true; flag = true;
} }
}else { }else {
flag = true; flag = true;
} }
}else { }else {
logWriter.record(npc + "不能说话", 1); logWriter.record(npc + "不能说话", 1);
} }
}else { }else {
logWriter.record("\"" + npc + "\":" + npc +"不在" + site + ",跳过",1 ); logWriter.record("\"" + npc + "\":" + npc +"不在" + site + ",跳过",1 );
} }
return flag; return flag;
} }
public static String appendTalker(String npc, String text, Map<String ,String> historyInfoPoint, GameEnv gameEnv){ public static String appendTalker(String npc, String text, Map<String ,String> historyInfoPoint, GameEnv gameEnv){
return String.format(TALKER_PATTERN, npc, ASSISTANT_EMOTION) + text; return String.format(TALKER_PATTERN, npc, ASSISTANT_EMOTION) + text;
} }
/** /**
* 判断文本类型 * 判断文本类型
* 1. direct_return:不需要额外处理,直接返回 * 1. direct_return:不需要额外处理,直接返回
* 2. less_talker:文本数据不完整,文本开头缺少【%s@%s】 * 2. less_talker:文本数据不完整,文本开头缺少【%s@%s】
* 3. to_unknown: 用unknown无匹配文本作为回答 * 3. to_unknown: 用unknown无匹配文本作为回答
* @param reply * @param reply
* @return * @return
*/ */
String plotTextFilt(String reply){ String plotTextFilt(String reply){
String textType, returnText = "plot text filt error", plotLastTalker; String textType, returnText = "plot text filt error", plotLastTalker;
String site = chatCache.getInfoPoint().get("site"); String site = chatCache.getInfoPoint().get("site");
textType = textTypeDetect(reply, site); textType = textTypeDetect(reply, site);
System.out.println("textType:" + textType); System.out.println("textType:" + textType);
switch(textType){ switch(textType){
case "direct_return": case "direct_return":
returnText = reply; returnText = reply;
break; break;
case "less_talker": case "less_talker":
//没有npc就添加npc //没有npc就添加npc
return appendTalker(findRelateTalkers(false).get(0), reply, chatCache.getInfoPoint(), chatCache.getGameEnv()); return appendTalker(findRelateTalkers(false).get(0), reply, chatCache.getInfoPoint(), chatCache.getGameEnv());
case "to_unknown": case "to_unknown":
//先设置一个默认答案,在本地点没有可以回答unknown //先设置一个默认答案,在本地点没有可以回答unknown
returnText = NO_ONE_CAN_REPLY_UNKNOWN; returnText = NO_ONE_CAN_REPLY_UNKNOWN;
Set<String> candidates = new HashSet<String>(); Set<String> candidates = new HashSet<String>();
Map<String, List<String>> npcTextMap = null; Map<String, List<String>> npcTextMap = null;
String unknownList = "", foundNPC; String unknownList = "", foundNPC;
String fieldList[] = {"unknownTextList", "finalUnknownText"}; String fieldList[] = {"unknownTextList", "finalUnknownText"};
String lastReply = chatCache.getInfoPoint().get("lastReply"); String lastReply = chatCache.getInfoPoint().get("lastReply");
//找到上一个回答, //找到上一个回答,
plotLastTalker = findTextLastTalker(lastReply, site); plotLastTalker = findTextLastTalker(lastReply, site);
for(String unknownField:fieldList){ for(String unknownField:fieldList){
candidates.clear(); candidates.clear();
if(userinfo.varInitialMap.get(unknownField) != null) { if(userinfo.varInitialMap.get(unknownField) != null) {
unknownList = userinfo.varInitialMap.get(unknownField); unknownList = userinfo.varInitialMap.get(unknownField);
npcTextMap = unknownTextClassify(unknownList); npcTextMap = unknownTextClassify(unknownList);
if(!plotLastTalker.equals("")) { if(!plotLastTalker.equals("")) {
candidates.add(plotLastTalker); candidates.add(plotLastTalker);
} }
//先找剧情相关的npc //先找剧情相关的npc
foundNPC = foundCandidateText(candidates, npcTextMap); foundNPC = foundCandidateText(candidates, npcTextMap);
if(!foundNPC.equals("")){ if(!foundNPC.equals("")){
returnText = SimpleUtil.randStr(npcTextMap.get(foundNPC)); returnText = SimpleUtil.randStr(npcTextMap.get(foundNPC));
break; break;
}else{ }else{
//再找地点相关的npc //再找地点相关的npc
candidates.addAll(findRelateTalkers(true)); candidates.addAll(findRelateTalkers(true));
foundNPC = foundCandidateText(candidates, npcTextMap); foundNPC = foundCandidateText(candidates, npcTextMap);
if(!foundNPC.equals("")){ if(!foundNPC.equals("")){
returnText = SimpleUtil.randStr(npcTextMap.get(foundNPC)); returnText = SimpleUtil.randStr(npcTextMap.get(foundNPC));
break; break;
} }
} }
} }
} }
break; break;
} }
return returnText; return returnText;
} }
public String textTypeDetect(String text, String site){ public String textTypeDetect(String text, String site){
int code = 0; int code = 0;
String textType = "to_unknown", npc; String textType = "to_unknown", npc;
Boolean flag = true; Boolean flag = true;
npc = findFirstTalker(text); npc = findFirstTalker(text);
if(text.equals("")){ if(text.equals("")){
textType = "to_unknown"; textType = "to_unknown";
}else if(npc.equals("")) { }else if(npc.equals("")) {
textType = "less_talker"; textType = "less_talker";
}else if(canTalk(npc, site, false)){ }else if(canTalk(npc, site, false)){
textType = "direct_return"; textType = "direct_return";
}else{ }else{
textType = "to_unknown"; textType = "to_unknown";
} }
return textType; return textType;
} }
private static Boolean isOnlineMode(String npc, Map<String, String> historyInfoPoint){ private static Boolean isOnlineMode(String npc, Map<String, String> historyInfoPoint){
return historyInfoPoint.get("onlineModeTalkers").contains("," + npc + ","); return historyInfoPoint.get("onlineModeTalkers").contains("," + npc + ",");
} }
/** /**
* 找到文本中最后一个可以说话的人, 可以说话是指npc处于玩家所在地点,不是离线模式等 * 找到文本中最后一个可以说话的人, 可以说话是指npc处于玩家所在地点,不是离线模式等
* @param text 文本 * @param text 文本
* @param site 玩家当前所在地点 * @param site 玩家当前所在地点
* @return * @return
*/ */
private String findTextLastTalker(String text, String site){ private String findTextLastTalker(String text, String site){
Matcher m = findTalker(text); Matcher m = findTalker(text);
String npc, lastTalker = ""; String npc, lastTalker = "";
while(m.find()) { while(m.find()) {
//回答unknown文本的npc必须处于在线模式 //回答unknown文本的npc必须处于在线模式
npc = m.group(1); npc = m.group(1);
//处于离线模式 可以说话 相同地点 //处于离线模式 可以说话 相同地点
if(canTalk(npc, site, true)) { if(canTalk(npc, site, true)) {
//找到最后一个说话且处于离线模式的npc //找到最后一个说话且处于离线模式的npc
lastTalker = npc; lastTalker = npc;
}else{ }else{
System.out.println(npc + "是离线模式"); System.out.println(npc + "是离线模式");
} }
} }
return lastTalker; return lastTalker;
} }
/** /**
* 找到用来说话的人 * 找到用来说话的人
* includeSiteNPC 是否包含当前地点的npc * includeSiteNPC 是否包含当前地点的npc
*/ */
private List<String> findRelateTalkers(Boolean includeSiteNPC){ private List<String> findRelateTalkers(Boolean includeSiteNPC){
String site = chatCache.getInfoPoint().get("site"); String site = chatCache.getInfoPoint().get("site");
String lastReply = chatCache.getInfoPoint().get("lastReply"); String lastReply = chatCache.getInfoPoint().get("lastReply");
List<String> talkers = new ArrayList<String>(); List<String> talkers = new ArrayList<String>();
if(lastReply == null) lastReply = ""; if(lastReply == null) lastReply = "";
String plotLastTalker = findTextLastTalker(lastReply, site); String plotLastTalker = findTextLastTalker(lastReply, site);
if(!plotLastTalker.equals("")){ if(!plotLastTalker.equals("")){
talkers.add(plotLastTalker); talkers.add(plotLastTalker);
} }
if(includeSiteNPC){ if(includeSiteNPC){
List<String> npcList = chatCache.getGameEnv().queryAroundNpcBySite(chatCache.getInfoPoint().get("site")); List<String> npcList = chatCache.getGameEnv().queryAroundNpcBySite(chatCache.getInfoPoint().get("site"));
for(String npc:npcList){ for(String npc:npcList){
if(canTalk(npc, site, true)){ if(canTalk(npc, site, true)){
talkers.add(npc); talkers.add(npc);
} }
} }
} }
if(talkers.size() == 0){ if(talkers.size() == 0){
talkers.add(chatCache.getInfoPoint().get(ASSISTANT)); talkers.add(chatCache.getInfoPoint().get(ASSISTANT));
} }
return talkers; return talkers;
} }
//从unknown文本中提取npc名字 //从unknown文本中提取npc名字
private Map<String, List<String>> unknownTextClassify(String unknownText){ private Map<String, List<String>> unknownTextClassify(String unknownText){
String talker; String talker;
Map<String, List<String>> npcTextMap = new HashMap<String, List<String>>(); Map<String, List<String>> npcTextMap = new HashMap<String, List<String>>();
for(String ans:unknownText.split("~")){ for(String ans:unknownText.split("~")){
talker = findFirstTalker(ans); talker = findFirstTalker(ans);
npcTextMap.putIfAbsent(talker, new ArrayList<String>()); npcTextMap.putIfAbsent(talker, new ArrayList<String>());
npcTextMap.get(talker).add(ans); npcTextMap.get(talker).add(ans);
} }
return npcTextMap; return npcTextMap;
} }
private String foundCandidateText(Set<String> candidates, Map<String, List<String>> npcTextMap){ private String foundCandidateText(Set<String> candidates, Map<String, List<String>> npcTextMap){
String foundNPC = ""; String foundNPC = "";
for(String npc:candidates) { for(String npc:candidates) {
//先看剧情中最后说话的人有没有unknown文本,如果有就。。。 //先看剧情中最后说话的人有没有unknown文本,如果有就。。。
if (npcTextMap.get(npc) != null && npcTextMap.get(npc).size() > 0) { if (npcTextMap.get(npc) != null && npcTextMap.get(npc).size() > 0) {
foundNPC = npc; foundNPC = npc;
break; break;
} }
} }
return foundNPC; return foundNPC;
} }
} }
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