Commit d592cee2 by hxw

添加游戏生成模块

parent 1214cb0d
package db; package db;
import entity.JConfig;
import entity.QuestionKeyWord; import entity.QuestionKeyWord;
import java.sql.Connection; import java.sql.*;
import java.sql.PreparedStatement; import java.util.ArrayList;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List; import java.util.List;
public class SqlHelper { public class SqlHelper {
...@@ -131,6 +130,56 @@ public class SqlHelper { ...@@ -131,6 +130,56 @@ public class SqlHelper {
return b; return b;
} }
public boolean batchInsertConfigByBotId(int botId, List<JConfig> jConfigList, List<Integer> idList) {
int count[];
boolean insertFlag = true;
String sql = "insert into chatbot_config (botId, categoryId, configData, configName) VALUES (?, ?, ?, ?)";
try {
conn.setAutoCommit(false); // 需要用到事务,不能让他自动提交,需要手动提交
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
for (JConfig jConfig : jConfigList) {
ps.setString(1, String.valueOf(botId));
ps.setString(2, String.valueOf(0));
ps.setString(3, jConfig.toJson().toJSONString());
ps.setString(4, "");
ps.addBatch();
}
count = ps.executeBatch();
conn.commit(); //提交事务,这个非常重要
for (int i : count) {
if (i == 0) {
conn.rollback(); // 回滚,非常重要
System.out.println("======出现异常,回滚=========");
insertFlag = false;
}
}
ResultSet rs = ps.getGeneratedKeys();
while(rs.next())
idList.add(rs.getInt(1));
ps.close();
rs.close();
} catch (SQLException e) {
try {
conn.rollback(); // 回滚,非常重要
} catch (SQLException e1) {
e1.printStackTrace();
}
System.out.println("------出现异常,回滚----------");
e.printStackTrace();
}
return insertFlag ;
}
} }
...@@ -19,6 +19,7 @@ public class Condition { ...@@ -19,6 +19,7 @@ public class Condition {
public String[] answer = {"",}; public String[] answer = {"",};
public String nextStep = ""; public String nextStep = "";
public String feature = ""; public String feature = "";
public HashMap<String, String> featureMap = new HashMap<String, String>();
public String indexName = ""; public String indexName = "";
public int id =0; public int id =0;
public String status = "waiting"; public String status = "waiting";
...@@ -29,6 +30,22 @@ public class Condition { ...@@ -29,6 +30,22 @@ public class Condition {
this.activePriority = priority; this.activePriority = priority;
} }
public Condition(Condition originCondition, int basePriority) {
this.priority = originCondition.priority;
this.auxiliaryPriority = originCondition.auxiliaryPriority;
this.keywordSet = originCondition.keywordSet;
this.historyPremise = originCondition.historyPremise;
this.currentPremise = originCondition.currentPremise;
this.answer = originCondition.answer;
this.nextStep = originCondition.nextStep;
this.feature = originCondition.feature;
this.featureMap = originCondition.featureMap;
this.indexName = originCondition.indexName;
this.id = originCondition.id;
this.status = originCondition.status;
this.activePriority = originCondition.activePriority + basePriority;
}
public Condition() { public Condition() {
} }
......
package entity;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JConfig {
private int id = 0;
private String jCurPremise = "";
private String jHisPremise = "";
private String jFeature = "";
private String jNextStep = "";
private String jReply = "";
private String jAuxiliaryPriority = "0";
private String jStatus = "0";
private String curPremise = "";
private String hisPremise = "";
private String feature = "";
private String reply = "";
private String nextStep = "";
private String auxiliaryPriority = "0";
private String status = "waiting";
public void setAuxiliaryPriority(String auxiliaryPriority) {
this.auxiliaryPriority = auxiliaryPriority;
}
private String updateKnowledge = "";
private String nextStepStatus = "return";
Map<String, String> statusMap = new HashMap<String, String>(){
{
put("return","return");
put("return-1","back");
put("return-0","stay");
put("activate","activate");
}
};
public JConfig(String curPremise, String hisPremise, String feature, String reply, String nextStep)
{
this.curPremise = curPremise;
this.hisPremise = hisPremise;
this.feature = feature;
this.reply = reply;
this.nextStep = nextStep;
}
public JConfig(List<String> curPremise, List<String> hisPremise, String extraCP, String extraHP, String feature, String reply, String nextStep)
{
String curPremiseStr = "";
String hisPremiseStr = "";
String extraCurPremise = "";
String extraHisPremise = "";
for(String premise: curPremise)
curPremiseStr += "," + premise;
for(String premise: hisPremise)
hisPremiseStr += "," + premise;
if(!extraCP.equals(""))
curPremiseStr += "," + extraCP;
if(!extraHP.equals(""))
hisPremiseStr += "," + extraHP;
this.curPremise = curPremiseStr.substring(1, curPremiseStr.length());
this.hisPremise = hisPremiseStr.substring(1, hisPremiseStr.length());
this.feature = feature;
this.reply = reply;
this.nextStep = nextStep;
}
public JConfig(List<String> curPremise, List<String> hisPremise, String extraCP, String extraHP, String feature, String reply, String nextStep, List<String> updateKnowledgeList, String extraUK)
{
String curPremiseStr = "";
String hisPremiseStr = "";
String extraCurPremise = "";
String extraHisPremise = "";
for(String premise: curPremise)
curPremiseStr += "," + premise;
for(String premise: hisPremise)
hisPremiseStr += "," + premise;
if(!extraCP.equals(""))
curPremiseStr += "," + extraCP;
if(!extraHP.equals(""))
hisPremiseStr += "," + extraHP;
for(String knowledge:updateKnowledgeList)
updateKnowledge += "-<-" + knowledge;
updateKnowledge += "-<-" + extraUK;
this.curPremise = curPremiseStr.substring(1, curPremiseStr.length());
this.hisPremise = hisPremiseStr.substring(1, hisPremiseStr.length());
this.feature = feature;
this.reply = reply;
this.nextStep = nextStep;
}
public JConfig(String curPremise, String hisPremise, String feature, String reply, String nextStep, String updateKnowledge)
{
this.curPremise = curPremise;
this.hisPremise = hisPremise;
this.feature = feature;
this.updateKnowledge = "-<-" + updateKnowledge;
this.reply = reply;
this.nextStep = nextStep;
}
public void appendJPremise(JSONArray premiseList, String premise){
String pair1[] = premise.split("=");
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];
JSONObject premiseJ = new JSONObject();
premiseJ.put("keywords", keywords);
premiseJ.put("actionName", conditionName);
premiseJ.put("cmpType", cmpType);
premiseJ.put("question", "不知");
premiseJ.put("operator", operator);
premiseList.add(premiseJ);
}
public void appendJKnowledge(JSONArray knowledgeList, String knowledge){
if(knowledge.equals(""))
return;
String pair[] = knowledge.split(":");
JSONObject knowledgeJ = new JSONObject();
knowledgeJ.put("variableName", pair[0]);
knowledgeJ.put("keyword", pair[1]);
knowledgeList.add(knowledgeJ);
}
public void appendJNextStep(JSONArray nextStepList, String next){
String pair[] = next.split("-");
JSONObject nextStepJ = new JSONObject();
JSONArray exceptJ = new JSONArray();
for(int i = 1;i < pair.length;i++)
exceptJ.add(pair[i]);
nextStepJ.put("nextStep", pair[0]);
nextStepJ.put("except", exceptJ);
nextStepList.add(nextStepJ);
}
public JSONObject toJson(){
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);
}
data.put("currentPremiseList", curPremiseList);
//添加已知信息的内容
for(String premise:hisPremise.split(",")){
if(!premise.equals("") && !premise.equals(" "))
appendJPremise(hisPremiseList, premise);
}
data.put("historyPremiseList", hisPremiseList);
//添加下一步状态
data.put("nextStepStatus", statusMap.get(nextStepStatus));
//添加configName
data.put("configName", "");
//添加config状态
data.put("configStatus", 0);
//添加post参数
data.put("doPost", false);
data.put("postURL", "");
data.put("postType", "all");
//添加回答
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);
}
data.put("updateKnowledge", knowledgeList);
}
//添加下一步
JSONArray nextStepList = new JSONArray();
for(String next: nextStep.split(",")){
appendJNextStep(nextStepList, next);
}
data.put("nextStepList", nextStepList);
return data;
}
public String toString(){
if(!updateKnowledge.equals(""))
updateKnowledge = ",updateKnowledge" + updateKnowledge;
String text = curPremise + "|" +
hisPremise + "|" +
feature + updateKnowledge + "|" +
"auxiliaryPriority=" + auxiliaryPriority + "|=>|" +
reply + "|" +
"nextStep=" + nextStep + "|" +
"status=" + status + "|" +
"configId=";
return text;
}
}
package entity;
/**
* 包含后台返回数据的实体类。
*/
public class Solution {
int status = 0;
String answer;
String next;
public String getAnswer() {
return answer;
}
public int getStatus() {
return status;
}
public void setAnswer(String answer) {
this.answer = answer;
}
public void setStatus(int status) {
this.status = status;
}
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
public Solution(int status, String answers, String next){
this.answer = answers;
this.next = next;
this.status = status;
}
public Solution(){}
}
...@@ -17,15 +17,15 @@ public class UserInfo { ...@@ -17,15 +17,15 @@ public class UserInfo {
} }
}; };
this.id2config = new HashMap<Integer, String>(); this.id2config = new HashMap<Integer, String>();
this.sleepingConfig = new HashMap<String, String>(); this.id2condition = new HashMap<Integer, Condition>();
} }
public HashMap<String,List<Condition>> conditionTable; public HashMap<String,List<Condition>> conditionTable;
public HashMap<String, String>sleepingConfig;
public String configStr; public String configStr;
public String userName; public String userName;
public HashMap<String,String> extraInfo; public HashMap<String,String> extraInfo;
public HashMap<Integer, String> id2config; public HashMap<Integer, String> id2config;
public HashMap<Integer, Condition> id2condition;
......
...@@ -2,6 +2,8 @@ package gameDesign; ...@@ -2,6 +2,8 @@ package gameDesign;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import db.SqlHelper;
import entity.JConfig;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
...@@ -9,24 +11,33 @@ import java.util.List; ...@@ -9,24 +11,33 @@ import java.util.List;
public class ElementConstructor { public class ElementConstructor {
int botId = 0;
SqlHelper helper = null;
List<JSONObject> configDataList = new ArrayList<JSONObject>(); List<JSONObject> configDataList = new ArrayList<JSONObject>();
List<JConfig> jConfigList = new ArrayList<JConfig>();
String userName; String userName;
String configText = ""; String configText = "";
JConfig jConfig = null;
public List<JConfig> getjConfigList() { return jConfigList; }
public void construct(JSONObject jsonObject){}
public void construct(){} public List<JSONObject> getConfigDataList() { return configDataList; }
public List<JSONObject> getConfigDataList() { public void ElementConstructor(String userName){ this.userName = userName; }
return configDataList;
}
public void ElementConstructor(String userName){ public String getConfigText() { return configText; }
this.userName = userName; public void generateConfigText(List<Integer> idList){
} int id, length = idList.size();
JConfig jConfig = null;
for(int i = 0; i< length;i++){
jConfig = jConfigList.get(i);
id = idList.get(i);
configText += jConfig.toString() + id + "\n";
}
public String getConfigText() {
return configText;
} }
/** /**
......
...@@ -3,29 +3,36 @@ package gameDesign; ...@@ -3,29 +3,36 @@ package gameDesign;
import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import db.SqlHelper; import db.SqlHelper;
import entity.JConfig;
import entity.UserInfo; import entity.UserInfo;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.StringReader; import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
public class MapConstructor extends ElementConstructor{ public class MapConstructor extends ElementConstructor{
int counter = 1;
int[][] matrix; int[][] matrix;
int locationNum; int locationNum;
HashMap<Integer, JSONObject> id2j = new HashMap<Integer, JSONObject>(); HashMap<Integer, JSONObject> id2j = new HashMap<Integer, JSONObject>();
JSONArray locations = null; JSONArray locations = null;
SqlHelper helper = null;
public MapConstructor(SqlHelper helper) {
public MapConstructor(SqlHelper helper, int botId) {
super(); super();
this.helper = helper; this.helper = helper;
this.botId = botId;
} }
...@@ -82,7 +89,8 @@ public class MapConstructor extends ElementConstructor{ ...@@ -82,7 +89,8 @@ public class MapConstructor extends ElementConstructor{
generateWhereIam(jsonObject); generateWhereIam(jsonObject);
generateHowToThere(floyd.pathMatirx, floyd.preTable, jsonObject); generateHowToThere(floyd.pathMatirx, floyd.preTable, jsonObject);
//
} }
/** /**
...@@ -90,10 +98,15 @@ public class MapConstructor extends ElementConstructor{ ...@@ -90,10 +98,15 @@ public class MapConstructor extends ElementConstructor{
*/ */
public void generateWhereIam(JSONObject jsonObject){ public void generateWhereIam(JSONObject jsonObject){
String zainaKeywords = (String)jsonObject.get("zaina"); String zainaKeywords = (String)jsonObject.get("zaina");
configText += "zaina=" + zainaKeywords + "| " jConfig = new JConfig(
+ "|match|=>|你在{site-2}|nextStep=yaozuo|status=waiting|configId=" "zaina::match-Keyword=" + zainaKeywords,
+ counter + "\n"; " ",
counter++; "match",
"你在{site-2}",
"yaobuyao"
);
jConfigList.add(jConfig);
} }
...@@ -107,6 +120,7 @@ public class MapConstructor extends ElementConstructor{ ...@@ -107,6 +120,7 @@ public class MapConstructor extends ElementConstructor{
String placeA, placeB, descriptionB, placeKeywords, text, pathNode; String placeA, placeB, descriptionB, placeKeywords, text, pathNode;
String zenmequKeywords = (String)jsonObject.get("zenmequ"); String zenmequKeywords = (String)jsonObject.get("zenmequ");
for(int i = 0;i < locationNum;i++){ for(int i = 0;i < locationNum;i++){
for(int j = 0;j < locationNum;j++){ for(int j = 0;j < locationNum;j++){
...@@ -116,19 +130,25 @@ public class MapConstructor extends ElementConstructor{ ...@@ -116,19 +130,25 @@ public class MapConstructor extends ElementConstructor{
placeKeywords = zenmequKeywords.replace("地点", placeB); placeKeywords = zenmequKeywords.replace("地点", placeB);
if(i == j){ if(i == j){
configText += "zenmequ=" + placeKeywords + "|site=" + placeA jConfig = new JConfig(
+ "|match|=>|" + "你已经在" + placeB + "了|nextStep=yaozuo|status=waiting|configId=" "zenmequ::match-Keyword=" + placeKeywords,
+ counter + "\n"; "site::match-Keyword=" + placeA,
"match",
counter++; "你已经在" + placeB + "了",
"yaobuyao"
);
jConfigList.add(jConfig);
continue; continue;
}; };
if(pathMatirx[i][j] == 1){ if(pathMatirx[i][j] == 1){
configText += "zenmequ=" + placeKeywords + "|site=" + placeA jConfig = new JConfig(
+ "|match|=>|" + placeB + "就在附近哦|nextStep=yaozuo|status=waiting|configId=" "zenmequ::match-Keyword=" + placeKeywords,
+ counter + "\n"; "site::match-Keyword=" + placeA,
"match",
counter++; placeB + "就在附近哦",
"yaobuyao"
);
jConfigList.add(jConfig);
}else if(pathMatirx[i][j] > 1 && pathMatirx[i][j] < Integer.MAX_VALUE){ }else if(pathMatirx[i][j] > 1 && pathMatirx[i][j] < Integer.MAX_VALUE){
int k = preTable[i][j]; int k = preTable[i][j];
...@@ -137,10 +157,15 @@ public class MapConstructor extends ElementConstructor{ ...@@ -137,10 +157,15 @@ public class MapConstructor extends ElementConstructor{
pathNode += (String)locations.getJSONObject(k).get("name"); pathNode += (String)locations.getJSONObject(k).get("name");
k = preTable[k][j]; k = preTable[k][j];
} }
configText += "zenmequ=" + placeKeywords + "|site=" + placeA + "|match|=>|经过" + pathNode
+ "就可以到达" + placeB + "|nextStep=yaozuo|status=waiting|configId=" + counter + "\n";
counter++; jConfig = new JConfig(
"zenmequ::match-Keyword=" + placeKeywords,
"site::match-Keyword=" + placeA,
"match",
"经过" + pathNode + "就可以到达" + placeB,
"yaobuyao"
);
jConfigList.add(jConfig);
} }
} }
} }
...@@ -165,17 +190,17 @@ public class MapConstructor extends ElementConstructor{ ...@@ -165,17 +190,17 @@ public class MapConstructor extends ElementConstructor{
} }
} }
configText += "nengquna=" + nengqunaKeywords + "|site=" + placeA jConfig = new JConfig(
+ "|match|=>|你可以去" + pathNode + "|nextStep=yaozuo|status=waiting|configId=" "nengquna::match-Keyword=" + nengqunaKeywords,
+ counter + "\n"; "site::match-Keyword=" + placeA,
"match",
"你可以去" + pathNode,
"yaobuyao"
);
jConfigList.add(jConfig);
counter++;
} }
...@@ -189,31 +214,38 @@ public class MapConstructor extends ElementConstructor{ ...@@ -189,31 +214,38 @@ public class MapConstructor extends ElementConstructor{
String placeA, placeB, descriptionB, placeKeywords, text, pathNode; String placeA, placeB, descriptionB, placeKeywords, text, pathNode;
String qunaKeywords = (String)jsonObject.get("quna"); String qunaKeywords = (String)jsonObject.get("quna");
for(int i = 0;i < locationNum;i++){
for(int j = 0;j < locationNum;j++){
for(int i = 0;i < locationNum;i++){
for(int j = 0;j < locationNum;j++){
placeA = (String)locations.getJSONObject(i).get("name"); placeA = (String)locations.getJSONObject(i).get("name");
placeB = (String)locations.getJSONObject(j).get("name"); placeB = (String)locations.getJSONObject(j).get("name");
descriptionB = (String)locations.getJSONObject(j).get("description"); descriptionB = (String)locations.getJSONObject(j).get("description");
placeKeywords = qunaKeywords.replace("地点", placeB); placeKeywords = qunaKeywords.replace("地点", placeB);
if(i == j){
configText += "quna=" + placeKeywords + "|site=" + placeA
+ "|match|=>|" + "你已经在" + placeB + "了|nextStep=yaozuo|status=waiting|configId="
+ counter + "\n";
counter++;
if(i == j){
jConfig = new JConfig(
"quna::match-Keyword=" + placeKeywords,
"site::match-Keyword=" + placeA,
"match",
"你已经在" + placeB + "了",
"yaobuyao"
);
jConfigList.add(jConfig);
continue; continue;
}; };
if(pathMatirx[i][j] == 1){ if(pathMatirx[i][j] == 1){
jConfig = new JConfig(
configText += "quna=" + placeKeywords + "|site=" + placeA "quna::match-Keyword=" + placeKeywords,
+ "|match,updateKnowledge-<-site:" + placeB + "|=>|" + descriptionB + "|nextStep=yaozuo|status=waiting|configId=" "site::match-Keyword=" + placeA,
+ counter + "\n"; "match,updateKnowledge-<-site:" + placeB,
"" + descriptionB,
counter++; "yaobuyao"
);
jConfigList.add(jConfig);
}else if(pathMatirx[i][j] > 1 && pathMatirx[i][j] < Integer.MAX_VALUE){ }else if(pathMatirx[i][j] > 1 && pathMatirx[i][j] < Integer.MAX_VALUE){
int k = preTable[i][j]; int k = preTable[i][j];
...@@ -222,13 +254,18 @@ public class MapConstructor extends ElementConstructor{ ...@@ -222,13 +254,18 @@ public class MapConstructor extends ElementConstructor{
pathNode += (String)locations.getJSONObject(k).get("name"); pathNode += (String)locations.getJSONObject(k).get("name");
k = preTable[k][j]; k = preTable[k][j];
} }
configText += "quna=" + placeKeywords + "|site=" + placeA + "|match|=>|从" jConfig = new JConfig(
+ placeA + "不能直接到达" + placeB + ", 需要经过" + pathNode "quna::match-Keyword=" + placeKeywords,
+ "才能到达" + placeB + "|nextStep=yaozuo|status=waiting|configId=" + counter + "\n"; "site::match-Keyword=" + placeA,
"match",
counter++; "从" + placeA + "不能直接到达" + placeB + ", 需要经过" + pathNode + "才能到达" + placeB,
"yaobuyao"
);
jConfigList.add(jConfig);
} }
} }
} }
} }
} }
package gameDesign;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import db.SqlHelper;
import entity.JConfig;
import java.util.*;
public class PlotConstructor extends ElementConstructor{
JSONArray plots = null;
HashMap<String, ArrayList<String>> adjList = new HashMap<String ,ArrayList<String>>();
HashMap<String, ArrayList<String>> revAdjList = new HashMap<String ,ArrayList<String>>();
HashMap<String, JSONObject> id2j = new HashMap<String, JSONObject>();
HashMap<String, Boolean> visited = new HashMap<String, Boolean>();
public PlotConstructor(SqlHelper helper, int botId){
super();
this.helper = helper;
this.botId = botId;
}
public void construct(JSONObject jsonObject){
JSONArray plots = jsonObject.getJSONArray("plots");
String start = (String)jsonObject.get("start");
this.plots = plots;
constructAdjList(plots);
BFSGenerate(id2j.get(start));
}
//根据id构造邻接表
public void constructAdjList(JSONArray plots){
int length = plots.size(), branchSize;
String id = "", nextPlotId = "";
JSONObject plot = null;
JSONArray branch = null;
for(int i = 0;i < length;i++){
plot = plots.getJSONObject(i);
id = (String)plot.get("id");
plot.put("index", i);
if(adjList.get(id) == null){
adjList.put(id, new ArrayList<>());
}
//添加branch中的下一个plot
branch = plot.getJSONArray("branch");
branchSize = branch.size();
for(int j =0;j < branchSize;j++) {
nextPlotId = (String)branch.getJSONObject(j).get("nextPlotId");
if(revAdjList.get(nextPlotId) == null){
revAdjList.put(nextPlotId, new ArrayList<>());
}
adjList.get(id).add(nextPlotId);
revAdjList.get(nextPlotId).add(id);
}
id2j.put(id, plot);
}
}
public void BFSGenerate(JSONObject root){
String id = (String)root.get("id"), adjId, nextId, taskName = "", value = "" ,extraHP = "", extraUK="", nextTaskName;
boolean newBranch, manyParent;
JSONObject node = null, branchNode = null, adjNode = null;
JSONArray branch = null;
List<String> adjNodeList = null;
int priority, taskStep, nextPriority, nextTaskStep, branchSize;
root.put("priority", 0);
root.put("taskName", id);
root.put("taskStep", 0);
Queue<JSONObject> queue = new LinkedList<JSONObject>();
queue.add(root);
while(!queue.isEmpty()){
node = queue.remove();
id = (String)node.get("id");
taskName = (String)node.get("taskName");
priority = (Integer)node.get("priority");
taskStep = (Integer)node.get("taskStep");
//初始化
newBranch = false;
manyParent = false;
adjNodeList = adjList.get(id);
visited.put(id ,true);
//查看是否存在多个子结点,如果有就是一个分支
if(adjNodeList.size() > 1)
newBranch = true;
//查看是否存在多个父节点
if(revAdjList.get(id) != null)
manyParent = revAdjList.get(id).size() > 1;
if(newBranch){
//多个分支时nextTaskName为子结点的id名,不在这里设
nextTaskStep = 1;
priority++;
}
else{
if(manyParent){
nextTaskName = id;
nextTaskStep = 1;
priority++;
}
else{
nextTaskName = taskName;
nextTaskStep = taskStep + 1;
}
}
branch = node.getJSONArray("branch");
branchSize = branch.size();
for(int i =0;i < branchSize;i++) {
branchNode = branch.getJSONObject(i);
nextId = (String)branchNode.get("nextPlotId");
if(node == root)
extraHP = " ";
else
extraHP = taskName + "::match-Keyword=" + taskStep;
if(newBranch || (revAdjList.get(nextId) != null && revAdjList.get(nextId).size() > 1))
extraUK = nextId + ":" + 1;
else
extraUK = taskName + ":" + (taskStep + 1);
jConfig = new JConfig(
JSONArray.parseArray(branchNode.getJSONArray("curPremise").toJSONString(), String.class),
JSONArray.parseArray(branchNode.getJSONArray("hisPremise").toJSONString(), String.class),
"",
extraHP,
"match",
(String) branchNode.get("reply"),
(String) branchNode.get("nextStep"),
JSONArray.parseArray(branchNode.getJSONArray("updateKnowledge").toJSONString(), String.class),
extraUK
);
jConfig.setAuxiliaryPriority("" + priority);
jConfigList.add(jConfig);
if(branchNode.get("nextPlotId") != null){
adjId = (String)branchNode.get("nextPlotId");
if(visited.get(adjId) == null && id2j.get(adjId) != null) {
adjNode = id2j.get(adjId);
adjNode.put("priority", priority);
adjNode.put("taskStep", nextTaskStep);
if(newBranch){
adjNode.put("taskName", adjId);
}else{
adjNode.put("taskName", taskName);
}
queue.add(adjNode);
}
}
}
}
}
}
package gameDesign;
public class Scene {
}
...@@ -15,32 +15,47 @@ import java.util.List; ...@@ -15,32 +15,47 @@ import java.util.List;
public class ConditionTableController { public class ConditionTableController {
public static boolean deleteConfig(String userName, String configId, String data, ServletContext context) throws IOException { public static boolean deleteConfig(String userName, String configId, String data, ServletContext context) throws IOException {
int id = Integer.parseInt(configId);
Condition condition = new Condition(); Condition condition = new Condition();
ProcessQuestion process = new ProcessQuestion(); ProcessQuestion process = new ProcessQuestion();
//data=configLine+"---"+conditionNameList //data=configLine+"---"+conditionNameList
String conditionNameList[] = data.split(","); String conditionNameList[] = data.split(",");
String conditionName = "";
if(context.getAttribute(userName) == null){ if(context.getAttribute(userName) == null){
process.userConfigInit(userName, context); process.userConfigInit(userName, context);
} }
UserInfo userinfo = (UserInfo) context.getAttribute(userName); UserInfo userInfo = (UserInfo) context.getAttribute(userName);
if (userinfo.id2config.containsKey(Integer.parseInt(configId))) {
Condition oldCondition = new Condition(); if (userInfo.id2config.containsKey(id)) {
oldCondition = process.buildCondition(oldCondition, userinfo.id2config.get(Integer.parseInt(configId)));
//-------------------
String conditionName = oldCondition.indexName; try {
if (userinfo.conditionTable.get(conditionName) != null) { Condition oldCondition = userInfo.id2condition.get(id);
List<Condition> conditionList = userinfo.conditionTable.get(conditionName); conditionName = oldCondition.indexName;
Iterator<Condition> condIter = userinfo.conditionTable.get(conditionName).iterator(); }catch (Exception e){
e.printStackTrace();
}
//-------------------
//Condition oldCondition = new Condition();
//oldCondition = process.buildCondition(oldCondition, userinfo.id2config.get(id));
//String conditionName = oldCondition.indexName;
if (userInfo.conditionTable.get(conditionName) != null) {
List<Condition> conditionList = userInfo.conditionTable.get(conditionName);
Iterator<Condition> condIter = userInfo.conditionTable.get(conditionName).iterator();
while (condIter.hasNext()) { while (condIter.hasNext()) {
Condition c = condIter.next(); Condition c = condIter.next();
if (c.id == Integer.parseInt(configId)) { if (c.id == id) {
condIter.remove(); condIter.remove();
} }
} }
} }
userinfo.id2config.remove(Integer.parseInt(configId)); userInfo.id2config.remove(id);
userInfo.id2condition.remove(id);
} else{ } else{
System.out.println("未找到要删除的configId"); System.out.println("未找到要删除的configId");
} }
...@@ -52,14 +67,22 @@ public class ConditionTableController { ...@@ -52,14 +67,22 @@ public class ConditionTableController {
Condition condition = new Condition(); Condition condition = new Condition();
ProcessQuestion process = new ProcessQuestion(); ProcessQuestion process = new ProcessQuestion();
//data=configLine+"---"+conditionNameList //data=configLine+"---"+conditionNameList
String conditionName = "";
for(int configId:idGroup) { for(int configId:idGroup) {
if (userInfo.id2config.containsKey(configId)) { if (userInfo.id2config.containsKey(configId)) {
Condition oldCondition = new Condition(); try {
oldCondition = process.buildCondition(oldCondition, userInfo.id2config.get(configId)); Condition oldCondition = userInfo.id2condition.get(configId);
conditionName = oldCondition.indexName;
}catch (Exception e){
e.printStackTrace();
}
//Condition oldCondition = new Condition();
//oldCondition = process.buildCondition(oldCondition, userInfo.id2config.get(configId));
//String conditionName = oldCondition.indexName;
String conditionName = oldCondition.indexName;
if (userInfo.conditionTable.get(conditionName) != null) { if (userInfo.conditionTable.get(conditionName) != null) {
List<Condition> conditionList = userInfo.conditionTable.get(conditionName); List<Condition> conditionList = userInfo.conditionTable.get(conditionName);
Iterator<Condition> condIter = userInfo.conditionTable.get(conditionName).iterator(); Iterator<Condition> condIter = userInfo.conditionTable.get(conditionName).iterator();
...@@ -72,11 +95,13 @@ public class ConditionTableController { ...@@ -72,11 +95,13 @@ public class ConditionTableController {
} }
userInfo.id2config.remove(configId); userInfo.id2config.remove(configId);
userInfo.id2condition.remove(configId);
} else { } else {
System.out.println("未找到要删除的configId:" + configId); System.out.println("未找到要删除的configId:" + configId);
} }
} }
return true; return true;
} }
...@@ -89,74 +114,37 @@ public class ConditionTableController { ...@@ -89,74 +114,37 @@ public class ConditionTableController {
String dataPair[] = data.split("---"); String dataPair[] = data.split("---");
String configLine = dataPair[0]; String configLine = dataPair[0];
String conditionNameList[]; String conditionNameList[];
int id = Integer.parseInt(configId);
if(dataPair.length > 1)
conditionNameList = dataPair[1].split(",");
else
conditionNameList = new String[]{"emptySet",};
condition = process.buildCondition(condition, configLine); condition = process.buildCondition(condition, configLine);
if(context.getAttribute(userName) == null){ if(context.getAttribute(userName) == null){
process.userConfigInit(userName, context); process.userConfigInit(userName, context);
} }
UserInfo userinfo = (UserInfo) context.getAttribute(userName); UserInfo userinfo = (UserInfo) context.getAttribute(userName);
if(userinfo.conditionTable.get(conditionNameList[0]) == null){
if(userinfo.conditionTable.get(condition.indexName) == null){
List<Condition> conditionList = new ArrayList<Condition>(); List<Condition> conditionList = new ArrayList<Condition>();
userinfo.conditionTable.put(conditionNameList[0], conditionList); userinfo.conditionTable.put(condition.indexName, conditionList);
} }
userinfo.conditionTable.get(conditionNameList[0]).add(condition); userinfo.conditionTable.get(condition.indexName).add(condition);
userinfo.id2config.put(Integer.parseInt(configId), configLine); userinfo.id2config.put(id, configLine);
userinfo.id2condition.put(id, condition);
return true; return true;
} }
public static boolean updateConfig(String userName, String configId, String data, ServletContext context) throws IOException { public static boolean updateExtraInfo(String userName, String data, ServletContext context) throws IOException {
Condition condition = new Condition();
ProcessQuestion process = new ProcessQuestion(); ProcessQuestion process = new ProcessQuestion();
//data=configLine+"---"+conditionNameList
String dataPair[] = data.split("---");
String configLine = dataPair[0];
String conditionNameList[] = dataPair[1].split(",");
condition = process.buildCondition(condition, configLine);
if(context.getAttribute(userName) == null){ if(context.getAttribute(userName) == null){
process.userConfigInit(userName, context); process.userConfigInit(userName, context);
} }
UserInfo userinfo = (UserInfo) context.getAttribute(userName); UserInfo userinfo = (UserInfo) context.getAttribute(userName);
if (userinfo.id2config.get(condition.id) == null){
}else {
for (String conditionName : conditionNameList) {
if (userinfo.conditionTable.get(conditionName) == null) {
continue;
}
List<Condition> conditionList = userinfo.conditionTable.get(conditionName);
int condLength = conditionList.size();
for (int i = 0; i < condLength; i++) {
if (conditionList.get(i).id == Integer.parseInt(configId)) {
conditionList.set(i, condition);
}
}
}
userinfo.id2config.put(Integer.parseInt(configId), configLine);
}
return true;
}
public static boolean updateExtraInfo(String userName, String data, ServletContext context) throws IOException {
ProcessQuestion process = new ProcessQuestion();
if(context.getAttribute(userName) == null){
if(context.getAttribute(userName) == null){
process.userConfigInit(userName, context);
}
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
String extraElements[] = data.split("\\|"); String extraElements[] = data.split("\\|");
userinfo.extraInfo.put(extraElements[1],extraElements[2]); userinfo.extraInfo.put(extraElements[1],extraElements[2]);
......
package processing; package processing;
import entity.AnswerNextStep; import entity.Solution;
import net.sf.json.JSONObject; import net.sf.json.JSONObject;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.HashMap;
public class MyFunc { public class MyFunc {
...@@ -20,7 +17,7 @@ public class MyFunc { ...@@ -20,7 +17,7 @@ public class MyFunc {
/** /**
* 将后台返回的数据转成json格式 * 将后台返回的数据转成json格式
*/ */
public static String toJson(AnswerNextStep ans) { public static String toJson(Solution ans) {
JSONObject jobj = new JSONObject(); JSONObject jobj = new JSONObject();
jobj.put("solution", ans.getAnswer()); jobj.put("solution", ans.getAnswer());
jobj.put("status", ans.getStatus()); jobj.put("status", ans.getStatus());
......
package processing; package processing;
import entity.AnswerNextStep; import entity.Solution;
import entity.Condition; import entity.Condition;
import entity.UserInfo; import entity.UserInfo;
import net.sf.json.JSONObject; import net.sf.json.JSONObject;
...@@ -9,7 +9,6 @@ import org.apache.http.HttpEntity; ...@@ -9,7 +9,6 @@ import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair; import org.apache.http.message.BasicNameValuePair;
...@@ -20,12 +19,13 @@ import javax.servlet.ServletContext; ...@@ -20,12 +19,13 @@ import javax.servlet.ServletContext;
import java.io.*; import java.io.*;
import java.sql.SQLException; import java.sql.SQLException;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
public class ProcessQuestion { public class ProcessQuestion {
static Map<Integer, Condition> activatedMap = new HashMap<Integer, Condition>();
static String CONFIG_DIR = System.getProperty("user.dir")+"/config"; static String CONFIG_DIR = System.getProperty("user.dir")+"/config";
/* /*
...@@ -108,7 +108,7 @@ public class ProcessQuestion { ...@@ -108,7 +108,7 @@ public class ProcessQuestion {
public static Condition buildCondition(Condition condition,String line){ public static Condition buildCondition(Condition condition,String line){
String feature,element[],pair[],next[],cur_premises[],history_premises[],premises[],firstCnditionName; String feature,url,element[],pair[],next[],cur_premises[],history_premises[],premises[],features[],firstCnditionName;
line = line.split("---")[0]; line = line.split("---")[0];
...@@ -136,6 +136,25 @@ public class ProcessQuestion { ...@@ -136,6 +136,25 @@ public class ProcessQuestion {
condition.status = next[2].split("=")[1]; condition.status = next[2].split("=")[1];
condition.feature = feature; condition.feature = feature;
//featureMap的构建
features = feature.split(",");
for (String feat:features){
if(feat.equals("") || feat.equals(" ")){
continue;
}else if(feat.startsWith("updateKnowledge")){
pair = feat.split("-<-",2);
condition.featureMap.put(pair[0], pair[1]);
}else if(feat.startsWith("post")){
pair = feature.split("\\(",2);
url = pair[1];
url = url.substring(0,url.length()-1);
condition.featureMap.put("post", url);
}else{
condition.featureMap.put(feat, "");
}
}
ProcessQuestion.insertPremise(condition.currentPremise,cur_premises); ProcessQuestion.insertPremise(condition.currentPremise,cur_premises);
ProcessQuestion.insertPremise(condition.historyPremise,history_premises); ProcessQuestion.insertPremise(condition.historyPremise,history_premises);
//满足条件越多,优先级越大 //满足条件越多,优先级越大
...@@ -169,9 +188,13 @@ public class ProcessQuestion { ...@@ -169,9 +188,13 @@ public class ProcessQuestion {
HashMap<String, List<Condition>> conditionTable = null; HashMap<String, List<Condition>> conditionTable = null;
if(overRide) if(overRide) {
conditionTable = new HashMap<String, List<Condition>>(); conditionTable = new HashMap<String, List<Condition>>();
else { userinfo.id2condition.clear();
userinfo.id2config.clear();
userinfo.extraInfo.clear();
userinfo.configStr = "";
}else {
conditionTable = userinfo.conditionTable; conditionTable = userinfo.conditionTable;
} }
...@@ -194,8 +217,11 @@ public class ProcessQuestion { ...@@ -194,8 +217,11 @@ public class ProcessQuestion {
conditionList = new ArrayList<Condition>(); conditionList = new ArrayList<Condition>();
conditionList.add(condition); conditionList.add(condition);
conditionTable.put(condition.indexName, conditionList); conditionTable.put(condition.indexName, conditionList);
if(condition.id != 0) if(condition.id != 0) {
userinfo.id2config.put(condition.id, line); userinfo.id2config.put(condition.id, line);
userinfo.id2condition.put(condition.id, condition);
}
} }
} }
userinfo.conditionTable = conditionTable; userinfo.conditionTable = conditionTable;
...@@ -307,7 +333,7 @@ public class ProcessQuestion { ...@@ -307,7 +333,7 @@ public class ProcessQuestion {
currentAction = userinfo.extraInfo.get("activeAction"); currentAction = userinfo.extraInfo.get("activeAction");
historyInfoPoint.put("currentAction", currentAction); historyInfoPoint.put("currentAction", currentAction);
}else }else
currentAction = ""; currentAction = " ";
curInfoPoint.put("emptySet", new String[]{" ",}); curInfoPoint.put("emptySet", new String[]{" ",});
...@@ -331,13 +357,14 @@ public class ProcessQuestion { ...@@ -331,13 +357,14 @@ public class ProcessQuestion {
* @param conditionTable 满足什么条件,就回答什么,下一步跳什么 * @param conditionTable 满足什么条件,就回答什么,下一步跳什么
* @return bestMatch 状态表中满足条件最多的一条 * @return bestMatch 状态表中满足条件最多的一条
*/ */
public Condition getAnswer(Map<String,String[]> curInfoPoint,Map<String,String> historyInfoPoint,HashMap<String,List<Condition>> conditionTable, ServletContext context) throws IOException { public Condition getBestMatch(Map<String,String[]> curInfoPoint,Map<String,String> historyInfoPoint,HashMap<String,List<Condition>> conditionTable, ServletContext context) throws IOException {
Integer configId = 0; Integer configId = 0;
List<Condition> conditionList = null; List<Condition> conditionList = null;
Condition bestMatch = new Condition(-1); Condition bestMatch = new Condition(-1),iterCon;
Iterator<String> it = curInfoPoint.keySet().iterator(); Iterator<String> it = curInfoPoint.keySet().iterator();
HashMap<Integer, Condition> extraActivatedConfig = new HashMap<Integer, Condition>(); Queue<Condition> activatedQueue = new LinkedList<Condition>();
Queue<Condition> activatedCondition = new LinkedList<Condition>();
while (it.hasNext()) { while (it.hasNext()) {
...@@ -353,25 +380,50 @@ public class ProcessQuestion { ...@@ -353,25 +380,50 @@ public class ProcessQuestion {
for (Condition condition : conditionList) { for (Condition condition : conditionList) {
if(condition.status.equals("waiting") && conditionSatisfy(curInfoPoint, historyInfoPoint, condition)){ if(condition.status.equals("waiting") && conditionSatisfy(curInfoPoint, historyInfoPoint, condition)){
if(condition.feature.contains("activate")){ if(condition.featureMap.get("instantPost") != null){
activateConfig(extraActivatedConfig, curInfoPoint.get("bot_name")[0], condition.priority, condition.nextStep, context);
}
//Post后还是可以激活
if(condition.featureMap.get("activate") != null){
bestMatch = condition;
activateCondition(activatedQueue, curInfoPoint.get("bot_name")[0], condition.priority, condition.nextStep, context);
} else if((condition.priority > bestMatch.priority) || (condition.priority == bestMatch.priority && condition.auxiliaryPriority > bestMatch.auxiliaryPriority)) } else if((condition.priority > bestMatch.priority) || (condition.priority == bestMatch.priority && condition.auxiliaryPriority > bestMatch.auxiliaryPriority))
bestMatch = condition; bestMatch = condition;
} }
} }
} }
} }
Iterator<Integer> extraConfigIter = extraActivatedConfig.keySet().iterator();
Condition extraCondition = null; bestMatch = activatedQueueMatching(bestMatch, activatedQueue, curInfoPoint, historyInfoPoint, context);
while(extraConfigIter.hasNext()){
configId = extraConfigIter.next();
extraCondition = extraActivatedConfig.get(configId);
if(extraCondition.activePriority > bestMatch.activePriority && conditionSatisfy(curInfoPoint, historyInfoPoint, extraCondition)){ return bestMatch;
bestMatch = extraCondition; }
public Condition activatedQueueMatching(Condition bestMatch,Queue<Condition> activatedQueue, Map<String,String[]> curInfoPoint,Map<String,String> historyInfoPoint, ServletContext context){
Condition condition;
//待激活配置条目被激活后的匹配
while(!activatedQueue.isEmpty()){
condition = activatedQueue.remove();
activatedMap.remove(condition.id);
if(conditionSatisfy(curInfoPoint, historyInfoPoint, condition)){
if(condition.feature.contains("activate")){
bestMatch = condition;
activateCondition(activatedQueue, curInfoPoint.get("bot_name")[0], condition.priority, condition.nextStep, context);
} else if((condition.activePriority > bestMatch.activePriority) || (condition.activePriority == bestMatch.activePriority && condition.auxiliaryPriority > bestMatch.auxiliaryPriority)){
bestMatch = condition;
}
} }
} }
return bestMatch; return bestMatch;
} }
/** /**
...@@ -438,7 +490,13 @@ public class ProcessQuestion { ...@@ -438,7 +490,13 @@ public class ProcessQuestion {
public boolean premiseSatisfy(String keyword, String cmpType, HashSet<String> keywordSet){ public boolean premiseSatisfy(String keyword, String cmpType, HashSet<String> keywordSet){
boolean flag = true; boolean flag = true;
String operator = "";
String splitPair[] = cmpType.split("-");
if (splitPair.length > 1){
operator = splitPair[1];
cmpType = splitPair[0];
}
try { try {
if (cmpType.equals("match")) { if (cmpType.equals("match")) {
...@@ -453,7 +511,45 @@ public class ProcessQuestion { ...@@ -453,7 +511,45 @@ public class ProcessQuestion {
} }
} }
} else if (cmpType.equals("numberBigger") && StringUtils.isNumeric(keyword)) { } else if (cmpType.equals("number") && !keyword.equals("") && StringUtils.isNumeric(keyword)) {
int candidateA = 0;
int candidateB = 0;
candidateA = Integer.parseInt(keyword);
for(String k: keywordSet){
if(!k.equals("")) {
candidateB = Integer.parseInt(k);
break;
}
}
if(operator.equals("Bigger"))
flag = candidateA > candidateB;
else if (operator.equals("BiggerOrEqual"))
flag = candidateA >= candidateB;
else if (operator.equals("Smaller"))
flag = candidateA < candidateB;
else if (operator.equals("SmallerOrEqual"))
flag = candidateA <= candidateB;
} else if (cmpType.equals("time")){
long candidateA,candidateB = 0;
candidateA = MyFunc.transferToMillisecond(keyword);
for(String k: keywordSet){
if(!k.equals("")) {
candidateB = MyFunc.transferToMillisecond(k);
break;
}
}
if(operator.equals("Early"))
flag = candidateA < candidateB;
else if(operator.equals("Later"))
flag = candidateA > candidateB;
}
//--------------------------------------------------------------------
//为兼容旧数据
else if (cmpType.equals("numberBigger") && StringUtils.isNumeric(keyword)) {
int candidateA = 0; int candidateA = 0;
int candidateB = 0; int candidateB = 0;
candidateA = Integer.parseInt(keyword); candidateA = Integer.parseInt(keyword);
...@@ -546,14 +642,17 @@ public class ProcessQuestion { ...@@ -546,14 +642,17 @@ public class ProcessQuestion {
* @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字 * @param historyInfoPoint 历史信息点,即引擎前几轮识别的conditionName和关键字
* @return 返回给引擎的数据 * @return 返回给引擎的数据
*/ */
public AnswerNextStep getBestMatch(Condition ansCondition,Map<String,String[]> curInfoPoint,Map<String,String> historyInfoPoint,ServletContext context,UserInfo userinfo) throws IOException, ParseException { public Solution getSolution(Condition ansCondition, Map<String,String[]> curInfoPoint, Map<String,String> historyInfoPoint, ServletContext context, UserInfo userinfo) throws IOException, ParseException {
Iterator<String> it = curInfoPoint.keySet().iterator(); Iterator<String> it = curInfoPoint.keySet().iterator();
String actionName; String actionName;
AnswerNextStep ans = new AnswerNextStep(0, "", ""); Solution ans = new Solution(0, "", "");
//如果一条配置文件有多个答案,则随机选择一个答案
//如果一条配置文件有多个答案,则随
// 机选择一个答案
int randNum = (int) (Math.random() * ansCondition.answer.length); int randNum = (int) (Math.random() * ansCondition.answer.length);
ans.setAnswer(ansCondition.answer[randNum]); ans.setAnswer(ansCondition.answer[randNum]);
//System.out.println(ans.getAnswer()); //System.out.println(ans.getAnswer());
...@@ -576,6 +675,13 @@ public class ProcessQuestion { ...@@ -576,6 +675,13 @@ public class ProcessQuestion {
}else if (ansCondition.feature.contains("return-0")){ }else if (ansCondition.feature.contains("return-0")){
String activeList[] = historyInfoPoint.get("activeList").split("\\|"); String activeList[] = historyInfoPoint.get("activeList").split("\\|");
ans.setNext("nextStep=" + activeList[activeList.length - 1]); ans.setNext("nextStep=" + activeList[activeList.length - 1]);
}else if (ansCondition.featureMap.containsKey("activate")){
String activeList[] = historyInfoPoint.get("activeList").split("\\|");
if (activeList.length == 1)
ans.setNext("nextStep=" + activeList[activeList.length - 1]);
else {
ans.setNext("nextStep=" + activeList[activeList.length - 2]);
}
} }
//updateKnowledge关键字 //updateKnowledge关键字
...@@ -611,7 +717,7 @@ public class ProcessQuestion { ...@@ -611,7 +717,7 @@ public class ProcessQuestion {
return ans; return ans;
} }
public void infoTransition(Map<String,String[]> curInfoPoint,Map<String,String> historyInfoPoint, AnswerNextStep ans, ServletContext context, boolean debugFlag){ public void infoTransition(Map<String,String[]> curInfoPoint, Map<String,String> historyInfoPoint, Solution ans, ServletContext context, boolean debugFlag){
//将当前信息点更新至历史信息点,并且替换答案中的相应变量,变量结构为{xxx-1}或者{xxx-2} //将当前信息点更新至历史信息点,并且替换答案中的相应变量,变量结构为{xxx-1}或者{xxx-2}
Iterator<String> it = curInfoPoint.keySet().iterator(); Iterator<String> it = curInfoPoint.keySet().iterator();
String actionName, lastReply; String actionName, lastReply;
...@@ -652,7 +758,7 @@ public class ProcessQuestion { ...@@ -652,7 +758,7 @@ public class ProcessQuestion {
public void appendDebugInfo(AnswerNextStep ans,Map<String,String[]> curInfoPoint,Map<String,String> historyInfoPoint,ServletContext context) { public void appendDebugInfo(Solution ans, Map<String,String[]> curInfoPoint, Map<String,String> historyInfoPoint, ServletContext context) {
Iterator<String> it = null; Iterator<String> it = null;
String key, values[], value; String key, values[], value;
...@@ -696,7 +802,7 @@ public class ProcessQuestion { ...@@ -696,7 +802,7 @@ public class ProcessQuestion {
* @param ans 返回给用户的数据 * @param ans 返回给用户的数据
* @param ansCondition 满足条件最多的condition(配置文件的某一行) * @param ansCondition 满足条件最多的condition(配置文件的某一行)
*/ */
public AnswerNextStep postToServer(AnswerNextStep ans, Condition ansCondition, Map<String,String[]> curInfoPoint,Map<String,String> historyInfoPoint) throws IOException { public Solution postToServer(Solution ans, Condition ansCondition, Map<String,String[]> curInfoPoint, Map<String,String> historyInfoPoint) throws IOException {
String url = null,features[] = ansCondition.feature.trim().split(","),elem[], subElem[], key, postType = "all"; String url = null,features[] = ansCondition.feature.trim().split(","),elem[], subElem[], key, postType = "all";
Map<String, String> infoMap = new HashMap<String, String>(); Map<String, String> infoMap = new HashMap<String, String>();
List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>(); List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
...@@ -784,6 +890,7 @@ public class ProcessQuestion { ...@@ -784,6 +890,7 @@ public class ProcessQuestion {
ans.setAnswer((String) jobj.get(keyName)); ans.setAnswer((String) jobj.get(keyName));
} else { } else {
ans.setAnswer(ans.getAnswer().replace("{" + keyName + "}", jobj.getString(keyName))); ans.setAnswer(ans.getAnswer().replace("{" + keyName + "}", jobj.getString(keyName)));
historyInfoPoint.put(keyName, jobj.getString(keyName));
} }
} }
} else { } else {
...@@ -799,7 +906,7 @@ public class ProcessQuestion { ...@@ -799,7 +906,7 @@ public class ProcessQuestion {
} }
public AnswerNextStep findNewNext(AnswerNextStep ans, Condition ansCondition, Map<String,String[]> curInfoPoint,Map<String,String> historyInfoPoint){ public Solution findNewNext(Solution ans, Condition ansCondition, Map<String,String[]> curInfoPoint, Map<String,String> historyInfoPoint){
String nextOptions[] = ansCondition.nextStep.split(","); String nextOptions[] = ansCondition.nextStep.split(",");
String conditionName,premises[],cpPair[]; String conditionName,premises[],cpPair[];
boolean flag = true; boolean flag = true;
...@@ -904,24 +1011,29 @@ public class ProcessQuestion { ...@@ -904,24 +1011,29 @@ public class ProcessQuestion {
} }
} }
public void activateConfig(HashMap<Integer, Condition> extraActivatedConfig, String userName, int basePriority, String activateList, ServletContext context){
public void activateCondition(Queue<Condition> activatedQueue, String userName, int basePriority, String activateList, ServletContext context){
UserInfo userinfo = (UserInfo) context.getAttribute(userName); UserInfo userinfo = (UserInfo) context.getAttribute(userName);
String configStr = ""; String configStr = "";
Integer configId; Integer configId;
Condition newCondition, originCondition;
for(String configIdStr:activateList.split(",")){ for(String configIdStr:activateList.split(",")){
if (!StringUtils.isNumeric(configIdStr)) if (!StringUtils.isNumeric(configIdStr))
continue; continue;
configId = Integer.parseInt(configIdStr); configId = Integer.parseInt(configIdStr);
Condition condition = new Condition();
configStr = userinfo.id2config.get(configId); configStr = userinfo.id2config.get(configId);
if(configStr != null) { if(configStr != null) {
condition = ProcessQuestion.buildCondition(condition, configStr); originCondition = userinfo.id2condition.get(configId);
newCondition = new Condition(originCondition, basePriority);
if (extraActivatedConfig.containsKey(configId) && condition.priority + basePriority > extraActivatedConfig.get(configId).activePriority) { //condition = ProcessQuestion.buildCondition(condition, configStr);
extraActivatedConfig.get(configId).activePriority = condition.priority + basePriority;
} else if (!extraActivatedConfig.containsKey(configId)) { if (activatedMap.containsKey(configId) && newCondition.activePriority > activatedMap.get(configId).activePriority) {
condition.activePriority = condition.priority + basePriority; activatedMap.get(configId).activePriority = newCondition.activePriority;
extraActivatedConfig.put(configId, condition); } else if (!activatedMap.containsKey(configId)) {
activatedMap.put(configId, newCondition);
activatedQueue.add(newCondition);
} }
} }
} }
...@@ -929,6 +1041,19 @@ public class ProcessQuestion { ...@@ -929,6 +1041,19 @@ public class ProcessQuestion {
} }
public Solution postActivate(Condition ansCondition, Map<String,String[]> curInfoPoint, Map<String,String> historyInfoPoint, ServletContext context, UserInfo userinfo) throws IOException, ParseException {
Queue<Condition> activatedQueue = new LinkedList<Condition>();
Solution bestMatch = null;
activateCondition(activatedQueue, userinfo.userName, ansCondition.priority, ansCondition.nextStep, context);
ansCondition = activatedQueueMatching(ansCondition, activatedQueue, curInfoPoint, historyInfoPoint, context);
bestMatch = getSolution(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo);
return bestMatch;
}
......
...@@ -5,7 +5,9 @@ import com.alibaba.fastjson.JSONObject; ...@@ -5,7 +5,9 @@ import com.alibaba.fastjson.JSONObject;
import db.SqlHelper; import db.SqlHelper;
import entity.Condition; import entity.Condition;
import entity.UserInfo; import entity.UserInfo;
import gameDesign.ElementConstructor;
import gameDesign.MapConstructor; import gameDesign.MapConstructor;
import gameDesign.PlotConstructor;
import processing.MyFunc; import processing.MyFunc;
import processing.ProcessQuestion; import processing.ProcessQuestion;
import processing.ConditionTableController; import processing.ConditionTableController;
...@@ -21,16 +23,19 @@ import java.io.IOException; ...@@ -21,16 +23,19 @@ import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringReader; import java.io.StringReader;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List; import java.util.List;
@WebServlet(name = "GameDesignServlet",urlPatterns = {"/gameDesign"}) @WebServlet(name = "GameDesignServlet",urlPatterns = {"/gameDesign"})
public class GameDesignServlet extends HttpServlet { public class GameDesignServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Integer botId; Integer botId;
String userName = null; String userName = null, mergedConfigText = "";
ServletContext context = this.getServletContext(); ServletContext context = this.getServletContext();
boolean flag; boolean flag;
SqlHelper helper = null; SqlHelper helper = null;
List<Integer> idList = new ArrayList<>();
ElementConstructor constructor = null;
try { try {
helper = new SqlHelper(); helper = new SqlHelper();
...@@ -40,18 +45,28 @@ public class GameDesignServlet extends HttpServlet { ...@@ -40,18 +45,28 @@ public class GameDesignServlet extends HttpServlet {
//读取并解析json数据 //读取并解析json数据
String jsonStr = MyFunc.readJSONString(request); String jsonStr = MyFunc.readJSONString(request);
if(context.getAttribute(userName) == null){
ProcessQuestion.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
if(jsonStr != null && !jsonStr.equals("")){ if(jsonStr != null && !jsonStr.equals("")){
JSONObject jsonObject = JSONObject.parseObject(jsonStr); JSONObject jsonObject = JSONObject.parseObject(jsonStr);
botId = (Integer)jsonObject.get("botId"); botId = (Integer)jsonObject.get("botId");
userName = (String)jsonObject.get("userName"); userName = (String)jsonObject.get("userName");
//moduleType = (String)jsonObject.get("moduleType");
List<Integer> idGroup = JSONArray.parseArray(jsonObject.getJSONArray("configIdGroup").toJSONString(), Integer.class); List<Integer> idGroup = JSONArray.parseArray(jsonObject.getJSONArray("configIdGroup").toJSONString(), Integer.class);
/*
假设重新重新建用户信息
if(context.getAttribute(userName) == null){
ProcessQuestion.userConfigInit(userName, context);
}
UserInfo userinfo = (UserInfo) context.getAttribute(userName);
*/
UserInfo userinfo = new UserInfo(userName);
//清空之前生成的配置条目 //清空之前生成的配置条目
if(idGroup.size() > 0) { if(idGroup.size() > 0) {
try { try {
...@@ -61,13 +76,30 @@ public class GameDesignServlet extends HttpServlet { ...@@ -61,13 +76,30 @@ public class GameDesignServlet extends HttpServlet {
} }
} }
MapConstructor mapConst = new MapConstructor(helper); for(String moduleType:jsonObject.parseArray(jsonObject.getJSONArray("moduleType").toJSONString(), String.class)) {
mapConst.construct(jsonObject); switch (moduleType) {
case "map":
constructor = new MapConstructor(helper, botId);
break;
case "plot":
constructor = new PlotConstructor(helper, botId);
break;
}
StringReader sr = new StringReader(mapConst.getConfigText()); constructor.construct(jsonObject);
//先清空再插入
idList.clear();
helper.batchInsertConfigByBotId(botId, constructor.getjConfigList(), idList);
constructor.generateConfigText(idList);
mergedConfigText += constructor.getConfigText();
}
StringReader sr = new StringReader(mergedConfigText);
BufferedReader br = new BufferedReader(sr); BufferedReader br = new BufferedReader(sr);
ProcessQuestion.buildUserInfo(br, userinfo, false); ProcessQuestion.buildUserInfo(br, userinfo, true);
context.setAttribute(userName, userinfo);
ConditionTableController.writeConfigText(userName, userinfo); ConditionTableController.writeConfigText(userName, userinfo);
helper.destroy();
} }
......
package servlet; package servlet;
import entity.AnswerNextStep; import entity.Solution;
import entity.Condition; import entity.Condition;
import entity.UserInfo; import entity.UserInfo;
import processing.ChatCacheController; import processing.ChatCacheController;
...@@ -29,7 +29,7 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -29,7 +29,7 @@ public class GetAnswerServlet extends HttpServlet {
request.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8");
Map<String,String[]> curInfoPoint = new HashMap<>(request.getParameterMap()); Map<String,String[]> curInfoPoint = new HashMap<>(request.getParameterMap());
Map<String, String> historyInfoPoint = null; Map<String, String> historyInfoPoint = null;
AnswerNextStep bestMatch = null; Solution bestMatch = null;
Condition ansCondition = null; Condition ansCondition = null;
String ansJ,return_str="",state = ""; String ansJ,return_str="",state = "";
String chatKey = curInfoPoint.get("chat_key")[0]; String chatKey = curInfoPoint.get("chat_key")[0];
...@@ -72,12 +72,17 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -72,12 +72,17 @@ public class GetAnswerServlet extends HttpServlet {
/*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/ /*得到答案更新历史信息点&生成答案,,清楚超时chatkey_key,生成更新数据库,转成json,输出*/
//process.removeTimeoutChatkey(context); //process.removeTimeoutChatkey(context);
//System.out.println(userinfo.conditionTable); //测试 //System.out.println(userinfo.conditionTable); //测试
ansCondition = process.getAnswer(curInfoPoint,historyInfoPoint,userinfo.conditionTable, context); ansCondition = process.getBestMatch(curInfoPoint,historyInfoPoint,userinfo.conditionTable, context);
if (state.equals("") && ansCondition.priority == -1) if (state.equals("") && ansCondition.priority == -1)
state = "我不理解,"; state = "我不理解,";
if (state.equals("")) { if (state.equals("")) {
try { try {
bestMatch = process.getBestMatch(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo); bestMatch = process.getSolution(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo);
if(ansCondition.featureMap.containsKey("activate") && ansCondition.featureMap.containsKey("post")){
//如果当前condition包含激活和提交表单两个操作,那么在提交操作完成之后会再激活一次待激活列表,简称后激活阶段
bestMatch = process.postActivate(ansCondition, curInfoPoint, historyInfoPoint, context, userinfo);
}
} catch (ParseException e) { } catch (ParseException e) {
e.printStackTrace(); e.printStackTrace();
} }
...@@ -90,7 +95,7 @@ public class GetAnswerServlet extends HttpServlet { ...@@ -90,7 +95,7 @@ public class GetAnswerServlet extends HttpServlet {
} }
//bestMatch.setAnswer(" \n" + return_str + "\n " + bestMatch.getAnswer()); //bestMatch.setAnswer(" \n" + return_str + "\n " + bestMatch.getAnswer());
}else{ }else{
bestMatch = new AnswerNextStep(0," \n" + return_str + "\n " +state,"nextStep=" + historyInfoPoint.get("currentAction")); bestMatch = new Solution(0," \n" + return_str + "\n " +state,"nextStep=" + historyInfoPoint.get("currentAction"));
} }
......
...@@ -38,7 +38,7 @@ public class ReloadConfigServlet extends HttpServlet { ...@@ -38,7 +38,7 @@ public class ReloadConfigServlet extends HttpServlet {
BufferedReader br = new BufferedReader(reader); BufferedReader br = new BufferedReader(reader);
try { try {
userinfo = ProcessQuestion.buildUserInfo(br, userinfo); userinfo = ProcessQuestion.buildUserInfo(br, userinfo, true);
context.setAttribute(userinfo.userName,userinfo); context.setAttribute(userinfo.userName,userinfo);
}catch(Exception e){ }catch(Exception e){
flag = false; flag = false;
......
...@@ -24,7 +24,6 @@ public class UpdateSingleConfigServlet extends HttpServlet { ...@@ -24,7 +24,6 @@ public class UpdateSingleConfigServlet extends HttpServlet {
System.out.println("userName:"+userName + " " + "type:" + processType + " " + "configId:" + "configId:" + configId + " " + "configData:" + data); System.out.println("userName:"+userName + " " + "type:" + processType + " " + "configId:" + "configId:" + configId + " " + "configData:" + data);
if(context.getAttribute(userName) != null) { if(context.getAttribute(userName) != null) {
System.out.println("11");
switch (processType) { switch (processType) {
case "insert_config": case "insert_config":
ConditionTableController.insertConfig(userName, configId, data, context); ConditionTableController.insertConfig(userName, configId, data, context);
...@@ -47,12 +46,10 @@ public class UpdateSingleConfigServlet extends HttpServlet { ...@@ -47,12 +46,10 @@ public class UpdateSingleConfigServlet extends HttpServlet {
response.setStatus(200); response.setStatus(200);
}else if(processType.equals("batch_update")){ }else if(processType.equals("batch_update")){
System.out.println("22");
batchUpdate(userName, data, context); batchUpdate(userName, data, context);
writeConfig(userName, context); writeConfig(userName, context);
response.setStatus(200); response.setStatus(200);
}else{ }else{
System.out.println("33");
response.setStatus(111); response.setStatus(111);
} }
......
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