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 String getConfigText() { return configText; }
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);
public void ElementConstructor(String userName){ configText += jConfig.toString() + id + "\n";
this.userName = userName;
} }
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 {
Condition condition = new Condition();
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){
process.userConfigInit(userName, context);
}
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 { public static boolean updateExtraInfo(String userName, String data, ServletContext context) throws IOException {
ProcessQuestion process = new ProcessQuestion(); ProcessQuestion process = new ProcessQuestion();
if(context.getAttribute(userName) == null){
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);
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());
......
...@@ -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;
}
constructor.construct(jsonObject);
//先清空再插入
idList.clear();
helper.batchInsertConfigByBotId(botId, constructor.getjConfigList(), idList);
constructor.generateConfigText(idList);
mergedConfigText += constructor.getConfigText();
StringReader sr = new StringReader(mapConst.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