Commit 6faa3ec8 by 赵国君

some minor changes

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